:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): surface memory watchdog kills to the run (#107623)
Alessandro Pogliaghi0016cee194b7
diff --git a/products/desktop/packages/agent/src/acp-extensions.ts b/products/desktop/packages/agent/src/acp-extensions.tsindex e4e3d22bdf13..f3b4ee86ffe0 100644--- a/products/desktop/packages/agent/src/acp-extensions.ts+++ b/products/desktop/packages/agent/src/acp-extensions.ts@@ -104,8 +104,19 @@ export const POSTHOG_NOTIFICATIONS = {MCP_RESPONSE: "_posthog/mcp_response",CREDENTIAL_REQUEST: "_posthog/credential_request",CREDENTIAL_RESPONSE: "_posthog/credential_response",+ PROCESS_KILLED: "_posthog/process_killed",} as const;+export type ProcessKilledParams = {+ pid: number;+ comm: string;+ treeRssBytes: number;+ memoryCurrentBytes: number;+ memoryLimitBytes: number;+ signal: string;+ at: string;+};+export type SteerDeclineCause =| "cancelled"| "compacting"diff --git a/products/desktop/packages/agent/src/otel-telemetry.test.ts b/products/desktop/packages/agent/src/otel-telemetry.test.tsindex c6039a6d41a3..c3ab1b10a399 100644--- a/products/desktop/packages/agent/src/otel-telemetry.test.ts+++ b/products/desktop/packages/agent/src/otel-telemetry.test.ts@@ -269,6 +269,28 @@ describe("OtelRunTelemetry", () => {severityText: "WARN",body: "tool call failed",},+ {+ name: "process_killed",+ entry: makeEntry("_posthog/process_killed", {+ pid: 4242,+ comm: "vitest",+ treeRssBytes: 12_884_901_888,+ memoryCurrentBytes: 14_602_888_806,+ memoryLimitBytes: 17_179_869_184,+ signal: "SIGTERM",+ at: "2026-01-01T00:00:00.000Z",+ }),+ severityText: "WARN",+ body: "process killed (vitest)",+ attrs: {+ event_type: "_posthog/process_killed",+ process_comm: "vitest",+ process_signal: "SIGTERM",+ process_tree_rss_bytes: 12_884_901_888,+ memory_current_bytes: 14_602_888_806,+ memory_limit_bytes: 17_179_869_184,+ },+ },])("maps $name", ({ entry, severityText = "INFO", body, attrs = {} }) => {const mapped = mapNotificationToLogRecord(entry);@@ -363,6 +385,25 @@ describe("OtelRunTelemetry", () => {);});+ it("never exports the killed process command line", () => {+ const mapped = mapNotificationToLogRecord(+ makeEntry("_posthog/process_killed", {+ pid: 4242,+ comm: "node",+ command: "node test.js --token=SECRET",+ treeRssBytes: 1,+ memoryCurrentBytes: 2,+ memoryLimitBytes: 3,+ signal: "SIGKILL",+ }),+ );++ expect(mapped).not.toBeNull();+ expect(JSON.stringify([mapped?.body, mapped?.attributes])).not.toContain(+ "SECRET",+ );+ });+it("never exports initialization error detail", () => {const mapped = mapNotificationToLogRecord(makeEntry("_posthog/initialization_failed", {diff --git a/products/desktop/packages/agent/src/otel-telemetry.ts b/products/desktop/packages/agent/src/otel-telemetry.tsindex c5cda4c9cdff..226ab19539f1 100644--- a/products/desktop/packages/agent/src/otel-telemetry.ts+++ b/products/desktop/packages/agent/src/otel-telemetry.ts@@ -247,6 +247,20 @@ export function mapNotificationToLogRecord(}case POSTHOG_NOTIFICATIONS.COMPACT_BOUNDARY:return record(INFO, "compact boundary", method, {});+ case POSTHOG_NOTIFICATIONS.PROCESS_KILLED: {+ const attrs: Attributes = {};+ const comm = strAttr(attrs, "process_comm", params.comm);+ strAttr(attrs, "process_signal", params.signal);+ numAttr(attrs, "process_tree_rss_bytes", params.treeRssBytes);+ numAttr(attrs, "memory_current_bytes", params.memoryCurrentBytes);+ numAttr(attrs, "memory_limit_bytes", params.memoryLimitBytes);+ return record(+ WARN,+ `process killed${comm ? ` (${comm})` : ""}`,+ method,+ attrs,+ );+ }case POSTHOG_NOTIFICATIONS.PERMISSION_REQUEST:case POSTHOG_NOTIFICATIONS.PERMISSION_RESPONSE:case POSTHOG_NOTIFICATIONS.PERMISSION_RESOLVED: {diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex b71a82cbe7ee..83cc59913a33 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -69,6 +69,7 @@ import packageJson from "../../package.json" with { type: "json" };import {POSTHOG_METHODS,POSTHOG_NOTIFICATIONS,+ type ProcessKilledParams,type SteerDeclineCause,} from "../acp-extensions";import {@@ -145,6 +146,11 @@ import {} from "./gateway-env";import { type JwtPayload, JwtValidationError, validateJwt } from "./jwt";import { type McpRelayResponse, McpRelayServer } from "./mcp-relay-server";+import {+ CliProcessRegistry,+ isTaskRunSandbox,+ MemoryWatchdogWatcher,+} from "./memory-watchdog";import {checkoutExistingPullRequest,type ExistingPrCheckoutResult,@@ -616,6 +622,9 @@ export class AgentServer {private readonly posthogExecPermissionRegex: RegExp;private readonly posthogExecPermissionRegexSource: string;private mcpRelayServer: McpRelayServer | null = null;+ private memoryWatchdogWatcher: MemoryWatchdogWatcher | null = null;+ private pendingProcessKills: ProcessKilledParams[] = [];+ private readonly cliProcesses = new CliProcessRegistry(process.env);private codexTokenClient: CodexSubscriptionTokenClient | null = null;private readonly credentialRelay = new CredentialRelay({emitEvent: (event) => this.broadcastEvent(event),@@ -1021,9 +1030,47 @@ export class AgentServer {);});+ await this.startMemoryWatchdogWatcher();await this.autoInitializeSession();}+ private async startMemoryWatchdogWatcher(): Promise<void> {+ if (!isTaskRunSandbox(process.env) || this.memoryWatchdogWatcher) return;+ const watcher = new MemoryWatchdogWatcher({+ onProcessKilled: (params) => this.emitProcessKilled(params),+ logger: this.logger,+ });+ if (await watcher.start()) {+ this.memoryWatchdogWatcher = watcher;+ }+ }++ private emitProcessKilled(params: ProcessKilledParams): void {+ const notification = {+ jsonrpc: "2.0",+ method: POSTHOG_NOTIFICATIONS.PROCESS_KILLED,+ params,+ };+ if (this.session) {+ this.broadcastAndPersistNotification(notification);+ return;+ }+ this.pendingProcessKills.push(params);+ }++ private flushPendingProcessKills(): void {+ if (!this.session || this.pendingProcessKills.length === 0) return;+ const kills = this.pendingProcessKills;+ this.pendingProcessKills = [];+ for (const params of kills) {+ this.broadcastAndPersistNotification({+ jsonrpc: "2.0",+ method: POSTHOG_NOTIFICATIONS.PROCESS_KILLED,+ params,+ });+ }+ }+private async loadResumeState(taskId: string,resumeRunId: string,@@ -1152,6 +1199,7 @@ export class AgentServer {this.logger.debug("Stopping agent server...");this.shutdownController.abort(new CredentialRelayError("cancelled"));this.credentialRelay.stop();+ this.memoryWatchdogWatcher?.stop();try {await withTimeout(Promise.allSettled([@@ -2242,6 +2290,16 @@ export class AgentServer {this.handleAcpTransportMessage(message, eventId),stampedRunTraceId: this.stampedRunTraceId,logger: this.logger,+ processCallbacks: isTaskRunSandbox(process.env)+ ? {+ onProcessSpawned: ({ pid }) => {+ void this.cliProcesses.spawned(pid);+ },+ onProcessExited: (pid) => {+ void this.cliProcesses.exited(pid);+ },+ }+ : undefined,claudeGatewayEnv:runtimeAdapter !== "codex" && claudeSubscriptionToken === null? gatewayEnv@@ -2504,6 +2562,7 @@ export class AgentServer {};this.initializingTelemetry = undefined;this.flushPreSessionEvents();+ this.flushPendingProcessKills();this.logger = new Logger({debug: true,diff --git a/products/desktop/packages/agent/src/server/memory-watchdog.test.ts b/products/desktop/packages/agent/src/server/memory-watchdog.test.tsnew file mode 100644index 000000000000..003e11a511d7--- /dev/null+++ b/products/desktop/packages/agent/src/server/memory-watchdog.test.ts@@ -0,0 +1,200 @@+import {+ appendFile,+ mkdtemp,+ open,+ readFile,+ rm,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ProcessKilledParams } from "../acp-extensions";+import { Logger } from "../utils/logger";+import {+ CliProcessRegistry,+ JsonlTail,+ MemoryWatchdogWatcher,+ toProcessKilledParams,+} from "./memory-watchdog";++const KILL_RECORD = {+ event: "kill",+ ts: 1_767_225_600.5,+ pid: 4242,+ comm: "vitest",+ cmdline: "node /workspace/node_modules/.bin/vitest run",+ tree_rss: 12_884_901_888,+ signal: "SIGTERM",+ current: 14_602_888_806,+ limit: 17_179_869_184,+ candidate_count: 2,+};++const KILL_PARAMS: ProcessKilledParams = {+ pid: 4242,+ comm: "vitest",+ treeRssBytes: 12_884_901_888,+ memoryCurrentBytes: 14_602_888_806,+ memoryLimitBytes: 17_179_869_184,+ signal: "SIGTERM",+ at: "2026-01-01T00:00:00.500Z",+};++describe("memory watchdog", () => {+ it.each([+ {+ name: "a line split across two reads",+ chunks: ['{"event":"kill","pid"', ":1}\n"],+ expected: [[], [{ event: "kill", pid: 1 }]],+ },+ {+ name: "several lines in one read",+ chunks: ['{"a":1}\n{"b":2}\n'],+ expected: [[{ a: 1 }, { b: 2 }]],+ },+ {+ name: "a trailing partial line held until its newline",+ chunks: ['{"a":1}\n{"b"', ":2}\n"],+ expected: [[{ a: 1 }], [{ b: 2 }]],+ },+ {+ name: "a multibyte character split across reads",+ chunks: [+ Buffer.from('{"comm":"né"}\n').subarray(0, 11),+ Buffer.from('{"comm":"né"}\n').subarray(11),+ ],+ expected: [[], [{ comm: "né" }]],+ },+ {+ name: "malformed and blank lines skipped",+ chunks: ['not json\n\n[1]\n{"a":1}\n'],+ expected: [[{ a: 1 }]],+ },+ ])("tails $name", ({ chunks, expected }) => {+ const tail = new JsonlTail();+ const results = chunks.map((chunk) =>+ tail.consume(typeof chunk === "string" ? Buffer.from(chunk) : chunk),+ );++ expect(results).toEqual(expected);+ expect(tail.position).toBe(+ chunks.reduce(+ (total, chunk) =>+ total ++ (typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk.length),+ 0,+ ),+ );+ });++ it.each([+ { name: "a kill record", record: KILL_RECORD, expected: KILL_PARAMS },+ {+ name: "a numeric signal",+ record: { ...KILL_RECORD, signal: 9, cmdline: ["node", "big.js"] },+ expected: { ...KILL_PARAMS, signal: "SIGKILL" },+ },+ {+ name: "a pressure record",+ record: { ...KILL_RECORD, event: "pressure" },+ expected: null,+ },+ {+ name: "a kill record without sizes",+ record: { ...KILL_RECORD, tree_rss: undefined },+ expected: null,+ },+ {+ name: "a kill record without comm",+ record: { ...KILL_RECORD, comm: 7 },+ expected: null,+ },+ ])("maps $name", ({ record, expected }) => {+ expect(toProcessKilledParams(record)).toEqual(expected);+ });++ describe("watcher", () => {+ let dir: string;+ let path: string;++ beforeEach(async () => {+ dir = await mkdtemp(join(tmpdir(), "memory-watchdog-"));+ path = join(dir, "events.jsonl");+ });++ afterEach(async () => {+ await rm(dir, { recursive: true, force: true });+ });++ it("reports each kill once across appends, a missing file, truncation and replacement", async () => {+ const onProcessKilled = vi.fn();+ const watcher = new MemoryWatchdogWatcher({+ onProcessKilled,+ logger: new Logger({ debug: false }),+ path,+ });++ await watcher.poll();+ await writeFile(+ path,+ `${JSON.stringify({ event: "watchdog_started", ts: 1 })}\n${JSON.stringify(KILL_RECORD).slice(0, 20)}`,+ );+ await watcher.poll();+ await appendFile(path, `${JSON.stringify(KILL_RECORD).slice(20)}\n`);+ await watcher.poll();+ await watcher.poll();+ await writeFile(path, `${JSON.stringify({ ...KILL_RECORD, pid: 7 })}\n`);+ await watcher.poll();+ const keep = await open(path, "r");+ await rm(path);+ await writeFile(+ path,+ `${JSON.stringify({ event: "watchdog_started", ts: 2 })}\n${JSON.stringify({ ...KILL_RECORD, pid: 8 })}\n`,+ );+ await watcher.poll();+ await keep.close();++ expect(onProcessKilled.mock.calls).toEqual([+ [KILL_PARAMS],+ [{ ...KILL_PARAMS, pid: 7 }],+ [{ ...KILL_PARAMS, pid: 8 }],+ ]);+ });++ it.each([+ {+ name: "keeps the other pid after one of two exits",+ steps: [+ ["spawned", 11],+ ["spawned", 12],+ ["exited", 11],+ ],+ expected: "12\n",+ },+ {+ name: "ignores an exit for an unknown pid",+ steps: [+ ["spawned", 11],+ ["exited", 99],+ ],+ expected: "11\n",+ },+ {+ name: "writes an empty file after the last exit",+ steps: [+ ["spawned", 11],+ ["exited", 11],+ ],+ expected: "",+ },+ ] as const)("cli pid file $name", async ({ steps, expected }) => {+ const pidPath = join(dir, "agent-cli.pid");+ const registry = new CliProcessRegistry({}, pidPath);++ await Promise.all(steps.map(([action, pid]) => registry[action](pid)));++ expect(await readFile(pidPath, "utf8")).toBe(expected);+ });+ });+});diff --git a/products/desktop/packages/agent/src/server/memory-watchdog.ts b/products/desktop/packages/agent/src/server/memory-watchdog.tsnew file mode 100644index 000000000000..d4ce3bb3806e--- /dev/null+++ b/products/desktop/packages/agent/src/server/memory-watchdog.ts@@ -0,0 +1,239 @@+import { constants as fsConstants } from "node:fs";+import { access, open, stat, writeFile } from "node:fs/promises";+import { constants as osConstants } from "node:os";+import { dirname } from "node:path";+import type { ProcessKilledParams } from "../acp-extensions";+import type { Logger } from "../utils/logger";++export const MEMORY_WATCHDOG_EVENTS_PATH = "/tmp/posthog-memory-watchdog.jsonl";+export const AGENT_CLI_PID_PATH = "/tmp/agent-cli.pid";+export const VM_CLI_OOM_SCORE_ADJ = 500;+const POLL_INTERVAL_MS = 1_000;+const MAX_READ_BYTES = 1024 * 1024;+const NEWLINE = 0x0a;++export class JsonlTail {+ private offset = 0;+ private remainder: Buffer = Buffer.alloc(0);++ get position(): number {+ return this.offset;+ }++ reset(): void {+ this.offset = 0;+ this.remainder = Buffer.alloc(0);+ }++ consume(chunk: Buffer): Record<string, unknown>[] {+ this.offset += chunk.length;+ const data =+ this.remainder.length > 0+ ? Buffer.concat([this.remainder, chunk])+ : chunk;+ const records: Record<string, unknown>[] = [];+ let lineStart = 0;+ let newlineIndex = data.indexOf(NEWLINE, lineStart);+ while (newlineIndex !== -1) {+ const record = parseJsonLine(data.subarray(lineStart, newlineIndex));+ if (record) records.push(record);+ lineStart = newlineIndex + 1;+ newlineIndex = data.indexOf(NEWLINE, lineStart);+ }+ this.remainder = Buffer.from(data.subarray(lineStart));+ return records;+ }+}++function parseJsonLine(line: Buffer): Record<string, unknown> | null {+ const text = line.toString("utf8").trim();+ if (!text) return null;+ try {+ const parsed: unknown = JSON.parse(text);+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)+ ? (parsed as Record<string, unknown>)+ : null;+ } catch {+ return null;+ }+}++function finiteNumber(value: unknown): number | null {+ return typeof value === "number" && Number.isFinite(value) ? value : null;+}++function signalName(value: unknown): string | null {+ if (typeof value === "string" && value) return value;+ const signal = finiteNumber(value);+ if (signal === null) return null;+ const name = Object.entries(osConstants.signals).find(+ ([, number]) => number === signal,+ )?.[0];+ return name ?? String(signal);+}++function recordTime(value: unknown): string {+ const seconds = finiteNumber(value);+ return new Date(seconds === null ? Date.now() : seconds * 1000).toISOString();+}++export function toProcessKilledParams(+ record: Record<string, unknown>,+): ProcessKilledParams | null {+ if (record.event !== "kill") return null;+ const pid = finiteNumber(record.pid);+ const treeRssBytes = finiteNumber(record.tree_rss);+ const memoryCurrentBytes = finiteNumber(record.current);+ const memoryLimitBytes = finiteNumber(record.limit);+ const signal = signalName(record.signal);+ if (+ pid === null ||+ typeof record.comm !== "string" ||+ treeRssBytes === null ||+ memoryCurrentBytes === null ||+ memoryLimitBytes === null ||+ signal === null+ ) {+ return null;+ }+ return {+ pid,+ comm: record.comm,+ treeRssBytes,+ memoryCurrentBytes,+ memoryLimitBytes,+ signal,+ at: recordTime(record.ts),+ };+}++export function isTaskRunSandbox(env: NodeJS.ProcessEnv): boolean {+ return Boolean(env.POSTHOG_TASK_RUN_ID);+}++export interface MemoryWatchdogWatcherOptions {+ onProcessKilled: (params: ProcessKilledParams) => void;+ logger: Logger;+ path?: string;+ intervalMs?: number;+}++export class MemoryWatchdogWatcher {+ private readonly path: string;+ private readonly intervalMs: number;+ private readonly tail = new JsonlTail();+ private timer: ReturnType<typeof setInterval> | null = null;+ private polling = false;+ private inode: number | null = null;++ constructor(private readonly options: MemoryWatchdogWatcherOptions) {+ this.path = options.path ?? MEMORY_WATCHDOG_EVENTS_PATH;+ this.intervalMs = options.intervalMs ?? POLL_INTERVAL_MS;+ }++ async start(): Promise<boolean> {+ if (this.timer) return true;+ try {+ await access(dirname(this.path), fsConstants.W_OK);+ } catch {+ return false;+ }+ this.timer = setInterval(() => {+ void this.poll();+ }, this.intervalMs);+ this.timer.unref?.();+ return true;+ }++ stop(): void {+ if (!this.timer) return;+ clearInterval(this.timer);+ this.timer = null;+ }++ async poll(): Promise<void> {+ if (this.polling) return;+ this.polling = true;+ try {+ for (const params of await this.readNewKills()) {+ this.options.onProcessKilled(params);+ }+ } catch (error) {+ this.options.logger.debug("Memory watchdog events read failed", {+ error: error instanceof Error ? error.message : String(error),+ });+ } finally {+ this.polling = false;+ }+ }++ private async readNewKills(): Promise<ProcessKilledParams[]> {+ let size: number;+ let inode: number;+ try {+ const stats = await stat(this.path);+ size = stats.size;+ inode = stats.ino;+ } catch {+ return [];+ }+ if (this.inode !== null && inode !== this.inode) this.tail.reset();+ this.inode = inode;+ if (size < this.tail.position) this.tail.reset();+ if (size === this.tail.position) return [];+ const length = Math.min(size - this.tail.position, MAX_READ_BYTES);+ const handle = await open(this.path, "r");+ try {+ const buffer = Buffer.alloc(length);+ const { bytesRead } = await handle.read(+ buffer,+ 0,+ length,+ this.tail.position,+ );+ return this.tail+ .consume(buffer.subarray(0, bytesRead))+ .map(toProcessKilledParams)+ .filter((params): params is ProcessKilledParams => params !== null);+ } finally {+ await handle.close();+ }+ }+}++export class CliProcessRegistry {+ private readonly pids = new Set<number>();+ private writes: Promise<void> = Promise.resolve();++ constructor(+ private readonly env: NodeJS.ProcessEnv,+ private readonly pidPath: string = AGENT_CLI_PID_PATH,+ ) {}++ spawned(pid: number): Promise<void> {+ this.pids.add(pid);+ return this.enqueue(async () => {+ await this.writePidFile();+ if (this.env.POSTHOG_SANDBOX_RUNTIME !== "vm") return;+ await writeFile(+ `/proc/${pid}/oom_score_adj`,+ String(VM_CLI_OOM_SCORE_ADJ),+ ).catch(() => undefined);+ });+ }++ exited(pid: number): Promise<void> {+ this.pids.delete(pid);+ return this.enqueue(() => this.writePidFile());+ }++ private enqueue(task: () => Promise<void>): Promise<void> {+ this.writes = this.writes.then(task, task);+ return this.writes;+ }++ private async writePidFile(): Promise<void> {+ const content = [...this.pids].map((pid) => `${pid}\n`).join("");+ await writeFile(this.pidPath, content).catch(() => undefined);+ }+}diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.tsindex 3473969143dc..7bf61eb6b951 100644--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts@@ -584,6 +584,56 @@ describe("buildConversationItems", () => {]);});+ it.each([+ {+ name: "a memory watchdog kill as a status row",+ params: {+ pid: 4242,+ comm: "vitest",+ treeRssBytes: 13.46 * 1024 ** 3,+ memoryCurrentBytes: 15 * 1024 ** 3,+ memoryLimitBytes: 16 * 1024 ** 3,+ signal: "SIGTERM",+ at: "2026-01-01T00:00:00.000Z",+ },+ expected: [+ {+ sessionUpdate: "status",+ status: "process_killed",+ message:+ "The sandbox stopped vitest because it was using 13.5 GiB of the 16.0 GiB available. The agent is still running.",+ },+ ],+ },+ {+ name: "nothing for a kill without sizes",+ params: { comm: "vitest" },+ expected: [],+ },+ ])("renders $name", ({ params, expected }) => {+ const result = buildConversationItems(+ [+ userPromptMsg(1, 1, "hi"),+ {+ type: "acp_message",+ ts: 2,+ message: {+ jsonrpc: "2.0",+ method: "_posthog/process_killed",+ params,+ },+ },+ ],+ null,+ );++ const statusItems = result.items.filter(+ (i): i is Extract<ConversationItem, { type: "session_update" }> =>+ i.type === "session_update" && i.update.sessionUpdate === "status",+ );+ expect(statusItems.map((i) => i.update)).toEqual(expected);+ });+it("marks cloud turns complete from structured turn completion notifications", () => {const result = buildConversationItems([userPromptMsg(10, 42, "hello"), turnCompleteMsg(25)],diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.tsindex f931cbf849c9..cd9204321f00 100644--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts@@ -5,6 +5,7 @@ import type {import {isNotification,POSTHOG_NOTIFICATIONS,+ type ProcessKilledParams,} from "@posthog/agent/acp-extensions";import { extractPromptDisplayContent } from "@posthog/core/sessions/promptContent";import { isSteerPromptParams } from "@posthog/core/sessions/sessionEvents";@@ -772,6 +773,29 @@ function completePromptTurn(}}+const BYTES_PER_GIB = 1024 ** 3;++function formatGib(bytes: number): string {+ return `${(bytes / BYTES_PER_GIB).toFixed(1)} GiB`;+}++export function formatProcessKilledNotice(params: unknown): string | null {+ const { comm, treeRssBytes, memoryLimitBytes } = (params ?? {}) as Partial<+ Record<keyof ProcessKilledParams, unknown>+ >;+ if (+ typeof comm !== "string" ||+ !comm ||+ typeof treeRssBytes !== "number" ||+ !Number.isFinite(treeRssBytes) ||+ typeof memoryLimitBytes !== "number" ||+ !Number.isFinite(memoryLimitBytes)+ ) {+ return null;+ }+ return `The sandbox stopped ${comm} because it was using ${formatGib(treeRssBytes)} of the ${formatGib(memoryLimitBytes)} available. The agent is still running.`;+}+function handleNotification(b: ItemBuilder,msg: { method: string; params?: unknown },@@ -852,6 +876,14 @@ function handleNotification(return;}+ if (isNotification(msg.method, POSTHOG_NOTIFICATIONS.PROCESS_KILLED)) {+ const message = formatProcessKilledNotice(msg.params);+ if (!message) return;+ ensureImplicitTurn(b, ts);+ pushItem(b, { sessionUpdate: "status", status: "process_killed", message });+ return;+ }+if (isNotification(msg.method, POSTHOG_NOTIFICATIONS.CONSOLE)) {const params = msg.params as { level?: string; message?: string };if (!params?.message) return;diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/StatusNotificationView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/StatusNotificationView.tsxindex 7e3ebb074197..e8dd9c5562f3 100644--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/StatusNotificationView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/StatusNotificationView.tsx@@ -1,4 +1,9 @@-import { ArrowsClockwise, ShieldWarning, XCircle } from "@phosphor-icons/react";+import {+ ArrowsClockwise,+ ShieldWarning,+ Warning,+ XCircle,+} from "@phosphor-icons/react";import { ChatMarker, ChatMarkerContent } from "@posthog/quill";import { Spin, Spinner } from "@posthog/ui/primitives/Spinner";import { Box, Callout, Flex, Text } from "@radix-ui/themes";@@ -99,6 +104,24 @@ export function StatusNotificationView({);}+ if (status === "process_killed" && message) {+ if (chatChrome) {+ return (+ <ChatMarker variant="separator">+ <ChatMarkerContent>{message}</ChatMarkerContent>+ </ChatMarker>+ );+ }+ return (+ <div className="my-1 border-orange-6 border-l-2 py-1 pl-3 dark:border-orange-8">+ <div className="flex items-center gap-2">+ <Warning size={14} weight="fill" className="text-orange-9" />+ <span className="text-[13px] text-muted-foreground">{message}</span>+ </div>+ </div>+ );+ }+if (status === "refusal_fallback") {const message =fromModel && toModeldiff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.pyindex 68196e42e3a8..192e6a8f4cfc 100644--- a/products/tasks/backend/agent_proxy_callback.py+++ b/products/tasks/backend/agent_proxy_callback.py@@ -9,8 +9,14 @@ from drf_spectacular.utils import OpenApiResponse, extend_schemafrom jwt import PyJWTErrorfrom products.tasks.backend.facade.api import signal_workflow_completion+from products.tasks.backend.logic.services.process_killed import (+ PROCESS_KILLED_EVENT,+ ProcessKilledNotice,+ process_killed_event_uuid,+)from products.tasks.backend.logic.stream.budget_steer import BudgetSteerCapturefrom products.tasks.backend.logic.stream.event_ingest import _parse_budget_steer_properties+from products.tasks.backend.metrics import observe_sandbox_process_killedfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.presentation.serializers import (AgentProxyCallbackRequestSerializer,@@ -48,7 +54,8 @@ logger = logging.getLogger(__name__)description=("Internal endpoint called by the standalone Node agent-proxy after accepting an ingest event ""that requires a Django-side side effect. Dispatches a Temporal heartbeat, a boot milestone, "- "an awaiting-input mobile push notification, a failed-run completion, or budget-steer analytics "+ "an awaiting-input mobile push notification, a failed-run completion, budget-steer analytics, "+ "or a sandbox memory watchdog kill ""depending on `kind`. ""Authenticated with the forwarded sandbox event ingest JWT plus the X-Agent-Proxy-Secret ""shared secret (required outside local dev/test) — no session or API key involved. "@@ -180,4 +187,26 @@ def agent_proxy_callback(request, run_id: str) -> JsonResponse:logger.exception("agent_proxy_callback.budget_steer_failed", extra={"run_id": run_id})return JsonResponse({"dispatched": False}, status=503)+ elif kind == "process_killed":+ sequence = data.get("sequence")+ killed = data.get("process_killed")+ if sequence is None or killed is None:+ return JsonResponse({"error": "Invalid process kill"}, status=400)+ notice = ProcessKilledNotice(**killed)+ try:+ task_run = TaskRun.objects.select_related("task__created_by", "team").get(+ id=run_id, task_id=task_id, team_id=team_id+ )+ except TaskRun.DoesNotExist:+ logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})+ else:+ dispatched = task_run.capture_event(+ PROCESS_KILLED_EVENT,+ notice.analytics_properties(),+ event_uuid=process_killed_event_uuid(run_id, sequence),+ )+ if not dispatched:+ return JsonResponse({"dispatched": False}, status=503)+ observe_sandbox_process_killed()+return JsonResponse(AgentProxyCallbackResponseSerializer({"dispatched": dispatched}).data)diff --git a/products/tasks/backend/logic/services/process_killed.py b/products/tasks/backend/logic/services/process_killed.pynew file mode 100644index 000000000000..90f2324db231--- /dev/null+++ b/products/tasks/backend/logic/services/process_killed.py@@ -0,0 +1,73 @@+from uuid import NAMESPACE_URL, uuid5++from posthog.dataclasses import frozen++PROCESS_KILLED_METHOD = "_posthog/process_killed"+PROCESS_KILLED_EVENT = "sandbox_process_killed"+_BYTES_PER_GIB = 1024**3+++@frozen+class ProcessKilledNotice:+ comm: str+ signal: str+ tree_rss_bytes: int+ memory_current_bytes: int+ memory_limit_bytes: int++ def analytics_properties(self) -> dict[str, str | int]:+ return {+ "process_comm": self.comm,+ "process_signal": self.signal,+ "process_tree_rss_bytes": self.tree_rss_bytes,+ "memory_current_bytes": self.memory_current_bytes,+ "memory_limit_bytes": self.memory_limit_bytes,+ }+++def _byte_count(value: object) -> int | None:+ if isinstance(value, bool) or not isinstance(value, int | float):+ return None+ return int(value)+++def parse_process_killed(event_data: dict) -> ProcessKilledNotice | None:+ if event_data.get("type") != "notification":+ return None+ notification = event_data.get("notification")+ if not isinstance(notification, dict) or notification.get("method") != PROCESS_KILLED_METHOD:+ return None+ params = notification.get("params")+ if not isinstance(params, dict):+ return None+ comm = params.get("comm")+ signal = params.get("signal")+ tree_rss_bytes = _byte_count(params.get("treeRssBytes"))+ memory_current_bytes = _byte_count(params.get("memoryCurrentBytes"))+ memory_limit_bytes = _byte_count(params.get("memoryLimitBytes"))+ if not isinstance(comm, str) or not isinstance(signal, str):+ return None+ if tree_rss_bytes is None or memory_current_bytes is None or memory_limit_bytes is None:+ return None+ return ProcessKilledNotice(+ comm=comm,+ signal=signal,+ tree_rss_bytes=tree_rss_bytes,+ memory_current_bytes=memory_current_bytes,+ memory_limit_bytes=memory_limit_bytes,+ )+++def process_killed_event_uuid(run_id: str, sequence: int) -> str:+ return str(uuid5(NAMESPACE_URL, f"posthog-task-process-killed:{run_id}:{sequence}"))+++def _format_gib(size_bytes: int) -> str:+ return f"{size_bytes / _BYTES_PER_GIB:.1f} GiB"+++def format_process_killed_message(notice: ProcessKilledNotice) -> str:+ return (+ f"The sandbox stopped {notice.comm} because it was using {_format_gib(notice.tree_rss_bytes)} "+ f"of the {_format_gib(notice.memory_limit_bytes)} available. The agent is still running."+ )diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.pyindex e04e79ae5d55..cbe77136a828 100644--- a/products/tasks/backend/logic/stream/event_ingest.py+++ b/products/tasks/backend/logic/stream/event_ingest.py@@ -23,6 +23,12 @@ from products.tasks.backend.logic.services.connection_token import (SandboxEventIngestTokenPayload,validate_sandbox_event_ingest_token,)+from products.tasks.backend.logic.services.process_killed import (+ PROCESS_KILLED_EVENT,+ ProcessKilledNotice,+ parse_process_killed,+ process_killed_event_uuid,+)from products.tasks.backend.logic.stream.agent_events import is_agent_command_dispatched, is_agent_generation_eventfrom products.tasks.backend.logic.stream.budget_steer import BudgetSteerCapturefrom products.tasks.backend.logic.stream.redis_stream import (@@ -32,7 +38,7 @@ from products.tasks.backend.logic.stream.redis_stream import (TaskRunStreamSequenceGap,get_task_run_stream_key,)-from products.tasks.backend.metrics import observe_stream_write_skipped+from products.tasks.backend.metrics import observe_sandbox_process_killed, observe_stream_write_skippedfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.turn_completed import dispatch_turn_completed@@ -57,6 +63,7 @@ STREAM_COMPLETE_CONTROL_TYPE = "_posthog/stream_complete"RTK_SAVINGS_SIDE_EFFECT = "rtk-savings"RTK_SAVINGS_CAPTURE_LOCK_SECONDS = 60BUDGET_STEER_SIDE_EFFECT = "budget-steer"+PROCESS_KILLED_SIDE_EFFECT = "process-killed"BUDGET_STEER_STAGES = frozenset({"warn", "critical"})BUDGET_STEER_MODES = frozenset({"publish", "wrap_up"})@@ -214,11 +221,14 @@ async def _ingest_event_lines(event = parsed_line.eventrtk_savings_properties = _parse_rtk_savings_properties(claims, event)budget_steer_properties = _parse_budget_steer_properties(claims, event)+ process_killed = parse_process_killed(event)pending_side_effect = Noneif rtk_savings_properties is not None:pending_side_effect = RTK_SAVINGS_SIDE_EFFECTelif budget_steer_properties is not None:pending_side_effect = BUDGET_STEER_SIDE_EFFECT+ elif process_killed is not None:+ pending_side_effect = PROCESS_KILLED_SIDE_EFFECTwrite = await redis_stream.write_event_with_sequence(event, sequence, pending_side_effect=pending_side_effect)@@ -226,6 +236,7 @@ async def _ingest_event_lines(await _capture_budget_steer_if_needed(redis_stream, claims, sequence, budget_steer_properties, event.get("timestamp"))+ await _capture_process_killed_if_needed(redis_stream, claims, sequence, process_killed)if not write.accepted:result.duplicate += 1result.last_accepted_seq = max(result.last_accepted_seq, await redis_stream.get_last_sequence())@@ -308,6 +319,47 @@ async def _capture_budget_steer_if_needed(await redis_stream.complete_pending_side_effect(BUDGET_STEER_SIDE_EFFECT, sequence)+async def _capture_process_killed_if_needed(+ redis_stream: TaskRunRedisStream,+ claims: SandboxEventIngestTokenPayload,+ sequence: int,+ notice: ProcessKilledNotice | None,+) -> None:+ if notice is None:+ return+ capture_claim = await redis_stream.claim_pending_side_effect(+ PROCESS_KILLED_SIDE_EFFECT, sequence, RTK_SAVINGS_CAPTURE_LOCK_SECONDS+ )+ if not capture_claim:+ return+ event_uuid = process_killed_event_uuid(claims.run_id, sequence)+ try:+ captured = await sync_to_async(_capture_process_killed, thread_sensitive=True)(+ claims.run_id, event_uuid, notice+ )+ except Exception:+ captured = False+ if not captured:+ await redis_stream.release_pending_side_effect(PROCESS_KILLED_SIDE_EFFECT, sequence)+ logger.warning("task_run_process_killed_capture_failed", run_id=claims.run_id)+ return+ await redis_stream.complete_pending_side_effect(PROCESS_KILLED_SIDE_EFFECT, sequence)+ observe_sandbox_process_killed()+++def _capture_process_killed(run_id: str, event_uuid: str, notice: ProcessKilledNotice) -> bool:+ if not settings.TEST:+ close_old_connections()++ try:+ task_run = TaskRun.objects.select_related("task__created_by", "team").get(id=run_id)+ except TaskRun.DoesNotExist:+ logger.warning("task_run_event_ingest_process_killed_run_missing", run_id=run_id)+ return True++ return task_run.capture_event(PROCESS_KILLED_EVENT, notice.analytics_properties(), event_uuid=event_uuid)++def _parse_budget_steer_properties(claims: SandboxEventIngestTokenPayload, event: dict) -> dict[str, str | int | float | bool] | None:diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex 8edec4994ecd..af68e3de63e2 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -327,6 +327,11 @@ TASK_RUN_STREAM_WRITE_SKIPPED_TOTAL = Counter(labelnames=["path", "origin_product"],)+TASK_RUN_SANDBOX_PROCESS_KILLED_TOTAL = Counter(+ "posthog_tasks_sandbox_process_killed_notifications_total",+ "Sandbox memory watchdog kills captured from the sequenced event ingest",+)+TASK_RUN_AGENT_FAILURE_TOTAL = Counter("posthog_tasks_agent_turn_failed_total","TaskRun transitions to FAILED via the API facade (agent-server turn failures)",@@ -675,6 +680,10 @@ def observe_stream_write_skipped(path: StreamWriteSkippedPath, origin_product: sTASK_RUN_STREAM_WRITE_SKIPPED_TOTAL.labels(path=path, origin_product=_metric_label(origin_product)).inc()+def observe_sandbox_process_killed() -> None:+ TASK_RUN_SANDBOX_PROCESS_KILLED_TOTAL.inc()++def observe_task_run_failed(properties: dict[str, object]) -> None:TASK_RUN_FAILED_TOTAL.labels(origin_product=_metric_label(properties.get("origin_product")),diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 77f3c5128e49..b1550a09ea68 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -4900,6 +4900,20 @@ class SlackThreadContextResponseSerializer(serializers.Serializer):)+class AgentProxyProcessKilledSerializer(serializers.Serializer):+ comm = serializers.CharField(max_length=64, help_text="Command name of the root process the watchdog stopped.")+ signal = serializers.CharField(+ max_length=16, help_text="Last signal the watchdog sent, such as SIGTERM or SIGKILL."+ )+ tree_rss_bytes = serializers.IntegerField(+ min_value=0, help_text="Resident memory of the stopped process tree, in bytes."+ )+ memory_current_bytes = serializers.IntegerField(+ min_value=0, help_text="Sandbox memory in use when the watchdog acted, in bytes."+ )+ memory_limit_bytes = serializers.IntegerField(min_value=0, help_text="Sandbox memory limit, in bytes.")++class AgentProxyCallbackRequestSerializer(serializers.Serializer):"""Request body for the agent-proxy side-effect callback.@@ -4910,13 +4924,22 @@ class AgentProxyCallbackRequestSerializer(serializers.Serializer):"""kind = serializers.ChoiceField(- choices=["heartbeat", "awaiting_input", "turn_failed", "command_dispatched", "agent_activity", "budget_steer"],+ choices=[+ "heartbeat",+ "awaiting_input",+ "turn_failed",+ "command_dispatched",+ "agent_activity",+ "budget_steer",+ "process_killed",+ ],help_text=("Side effect to dispatch. 'heartbeat' signals the Temporal workflow to reset its ""inactivity timer. 'awaiting_input' fires a mobile push notification when an ""interactive run finishes a turn and is waiting for user input. 'turn_failed' fails ""the run outright when a pi turn ends in a runtime error. 'command_dispatched' "- "and 'agent_activity' record boot milestones. 'budget_steer' captures the agent's budget warning."+ "and 'agent_activity' record boot milestones. 'budget_steer' captures the agent's budget warning. "+ "'process_killed' captures a sandbox memory watchdog kill."),)agent_active = serializers.BooleanField(@@ -4950,7 +4973,9 @@ class AgentProxyCallbackRequestSerializer(serializers.Serializer):help_text="Numeric team (project) ID. Must match the JWT claim.",)sequence = serializers.IntegerField(- required=False, min_value=1, help_text="Event sequence used to deduplicate a budget steer."+ required=False,+ min_value=1,+ help_text="Event sequence used to deduplicate a budget steer or a process kill.",)timestamp = serializers.DateTimeField(required=False, help_text="Original event time, preserved across retries.")stage = serializers.CharField(required=False, help_text="Budget stage: warn or critical.")@@ -4965,6 +4990,9 @@ class AgentProxyCallbackRequestSerializer(serializers.Serializer):)threshold_at = serializers.DateTimeField(required=False, help_text="Time when the budget stage was reached.")delivered_at = serializers.DateTimeField(required=False, help_text="Time when the steer reached the agent.")+ process_killed = AgentProxyProcessKilledSerializer(+ required=False, help_text="The kill the sandbox memory watchdog reported. Required for 'process_killed'."+ )class AgentProxyCallbackResponseSerializer(serializers.Serializer):diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.pyindex af0d82062d9b..417ab744b127 100644--- a/products/tasks/backend/temporal/metrics.py+++ b/products/tasks/backend/temporal/metrics.py@@ -390,6 +390,16 @@ def increment_tool_call_only_heartbeat() -> None:pass+def increment_sandbox_process_killed_notification() -> None:+ try:+ _metric_meter().create_counter(+ "tasks_sandbox_process_killed_notifications",+ "Sandbox memory watchdog kills relayed from the agent server to the run",+ ).add(1)+ except Exception:+ pass++def increment_pr_babysit_decision(decision: str) -> None:try:meter = workflow.metric_meter().with_additional_attributes({"decision": decision})diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex 068bf673b1d5..b789153f855c 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -30,6 +30,12 @@ from products.tasks.backend.logic.services.permission_broker import (parse_permission_request,try_auto_respond_permission_request,)+from products.tasks.backend.logic.services.process_killed import (+ PROCESS_KILLED_EVENT,+ ProcessKilledNotice,+ format_process_killed_message,+ parse_process_killed,+)from products.tasks.backend.logic.services.workflow_step_resume import resume_workflow_step_after_final_messagefrom products.tasks.backend.logic.stream.agent_events import is_agent_command_dispatched, is_agent_generation_eventfrom products.tasks.backend.logic.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key@@ -39,7 +45,11 @@ from products.tasks.backend.models import ()from products.tasks.backend.redis import run_uses_dedicated_streamfrom products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_DEFAULT_SECONDS, resolve_inactivity_timeout-from products.tasks.backend.temporal.metrics import increment_tool_call_only_heartbeat+from products.tasks.backend.temporal.metrics import (+ increment_sandbox_process_killed_notification,+ increment_tool_call_only_heartbeat,+)+from products.tasks.backend.temporal.observability import emit_agent_logfrom products.tasks.backend.temporal.process_task.utils import (get_actor_distinct_id,get_task_run_credential_user,@@ -526,6 +536,10 @@ async def _relay_loop(permission_request = parse_permission_request(event_data)if permission_request is not None:await asyncio.to_thread(_broker_permission_request, task_run, permission_request)+ process_killed = parse_process_killed(event_data)+ if process_killed is not None:+ increment_sandbox_process_killed_notification()+ await asyncio.to_thread(_report_process_killed, run_id, task_run, process_killed)reconnect_count = 0last_event_time[0] = time.monotonic()@@ -994,6 +1008,19 @@ async def _emit_agentsh_events(sandbox_id: str, run_id: str, last_ts_ns: list[inlogger.debug("agentsh_emit_failed", error=str(e))+def _report_process_killed(run_id: str, task_run: TaskRunModel | None, notice: ProcessKilledNotice) -> None:+ if not settings.TEST:+ close_old_connections()+ try:+ emit_agent_log(run_id, "warn", format_process_killed_message(notice))+ if task_run is None:+ return+ task_run.capture_event(PROCESS_KILLED_EVENT, notice.analytics_properties())+ finally:+ if not settings.TEST:+ close_old_connections()++def _is_terminal_event(event_data: dict) -> bool:"""Check if an ACP event signals the agent session has ended."""if event_data.get("type") != "notification":diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex 3687ff0804cb..2c87edbbe095 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -16,6 +16,11 @@ from parameterized import parameterizedfrom prometheus_client import REGISTRYfrom temporalio.exceptions import ApplicationError+from products.tasks.backend.logic.services.process_killed import (+ ProcessKilledNotice,+ format_process_killed_message,+ parse_process_killed,+)from products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_DEFAULT_SECONDSfrom products.tasks.backend.temporal.process_task import workflow as process_task_workflow_module@@ -51,6 +56,23 @@ relay_sandbox_events_module = importlib.import_module("products.tasks.backend.temporal.process_task.activities.relay_sandbox_events")+_GIB = 1024**3+++def _process_killed_event(**overrides: object) -> dict:+ params: dict[str, object] = {+ "pid": 4242,+ "comm": "vitest",+ "command": "node vitest run --token=secret-value",+ "treeRssBytes": 12 * _GIB,+ "memoryCurrentBytes": 14 * _GIB,+ "memoryLimitBytes": 16 * _GIB,+ "signal": "SIGTERM",+ "at": "2026-01-01T00:00:00.000Z",+ **overrides,+ }+ return {"type": "notification", "notification": {"method": "_posthog/process_killed", "params": params}}+class TestIsTurnComplete:@parameterized.expand(@@ -333,6 +355,46 @@ class TestIsKeepaliveEvent:assert _is_keepalive_event(event_data) == expected+class TestParseProcessKilled:+ @parameterized.expand(+ [+ (+ "kill_notification",+ _process_killed_event(),+ ProcessKilledNotice(+ comm="vitest",+ signal="SIGTERM",+ tree_rss_bytes=12 * _GIB,+ memory_current_bytes=14 * _GIB,+ memory_limit_bytes=16 * _GIB,+ ),+ ),+ ("other_method", {"type": "notification", "notification": {"method": "_posthog/error"}}, None),+ ("not_a_notification", {"type": "keepalive"}, None),+ ("missing_size", _process_killed_event(treeRssBytes=None), None),+ ("boolean_size", _process_killed_event(memoryLimitBytes=True), None),+ ("missing_comm", _process_killed_event(comm=None), None),+ ],+ )+ def test_parse_process_killed(self, _name: str, event_data: dict, expected: ProcessKilledNotice | None) -> None:+ assert parse_process_killed(event_data) == expected++ @parameterized.expand(+ [+ ("whole_gib", 12 * _GIB, 16 * _GIB, "using 12.0 GiB of the 16.0 GiB available"),+ ("fractional_gib", int(13.46 * _GIB), int(15.5 * _GIB), "using 13.5 GiB of the 15.5 GiB available"),+ ],+ )+ def test_format_process_killed_message(self, _name: str, tree_rss: int, limit: int, expected: str) -> None:+ notice = ProcessKilledNotice(+ comm="node", signal="SIGKILL", tree_rss_bytes=tree_rss, memory_current_bytes=limit, memory_limit_bytes=limit+ )++ assert format_process_killed_message(notice) == (+ f"The sandbox stopped node because it was {expected}. The agent is still running."+ )++class TestSanitizeHttpxError:def test_redacts_query_string_carrying_the_transport_token(self) -> None:request = httpx.Request("GET", "https://hogland.example/events?token=super-secret-bearer")@@ -768,6 +830,71 @@ class TestRelaySandboxEventsErrorHandling:redis_stream.mark_complete.assert_awaited_once()redis_stream.mark_error.assert_not_awaited()+ async def test_process_killed_is_reported_without_ending_the_relay(self, monkeypatch: pytest.MonkeyPatch) -> None:+ redis_stream = SimpleNamespace(+ write_event=AsyncMock(),+ mark_complete=AsyncMock(),+ mark_error=AsyncMock(),+ )+ killed_event = _process_killed_event()+ terminal_event = {"type": "notification", "notification": {"method": "_posthog/task_complete"}}++ class SuccessfulEventSource:+ response = SimpleNamespace(raise_for_status=lambda: None)++ async def __aenter__(self) -> "SuccessfulEventSource":+ return self++ async def __aexit__(self, *_args: object) -> None:+ return None++ async def aiter_sse(self):+ yield SimpleNamespace(data=json.dumps(killed_event))+ yield SimpleNamespace(data=json.dumps(terminal_event))++ def fake_connect_sse(*_args: object, **_kwargs: object) -> SuccessfulEventSource:+ return SuccessfulEventSource()++ async def fake_background_heartbeat(*_args: object, **_kwargs: object) -> None:+ return None++ emit_agent_log_mock = MagicMock()+ task_run = MagicMock()+ monkeypatch.setattr(relay_sandbox_events_module.httpx_sse, "aconnect_sse", fake_connect_sse)+ monkeypatch.setattr(relay_sandbox_events_module, "_background_heartbeat", fake_background_heartbeat)+ monkeypatch.setattr(relay_sandbox_events_module, "emit_agent_log", emit_agent_log_mock)+ monkeypatch.setattr(relay_sandbox_events_module, "parse_permission_request", lambda _event: None)++ sandbox_gone = await _relay_loop(+ events_url="https://sandbox.example/events",+ headers={"Authorization": "Bearer token"},+ params={},+ redis_stream=cast(TaskRunRedisStream, redis_stream),+ run_id="run-id",+ task_id="task-id",+ task_run=cast(TaskRun, task_run),+ )++ assert sandbox_gone is False+ assert redis_stream.write_event.await_args_list == [call(killed_event), call(terminal_event)]+ emit_agent_log_mock.assert_called_once_with(+ "run-id",+ "warn",+ "The sandbox stopped vitest because it was using 12.0 GiB of the 16.0 GiB available. "+ "The agent is still running.",+ )+ task_run.capture_event.assert_called_once_with(+ "sandbox_process_killed",+ {+ "process_comm": "vitest",+ "process_signal": "SIGTERM",+ "process_tree_rss_bytes": 12 * _GIB,+ "memory_current_bytes": 14 * _GIB,+ "memory_limit_bytes": 16 * _GIB,+ },+ )+ assert "secret-value" not in json.dumps(task_run.capture_event.call_args.args)+async def test_relay_signals_command_and_generated_activity_once(self, monkeypatch: pytest.MonkeyPatch) -> None:redis_stream = SimpleNamespace(write_event=AsyncMock(),diff --git a/products/tasks/backend/tests/test_agent_proxy_callback.py b/products/tasks/backend/tests/test_agent_proxy_callback.pyindex 9358f5fb099c..6e2363cf8206 100644--- a/products/tasks/backend/tests/test_agent_proxy_callback.py+++ b/products/tasks/backend/tests/test_agent_proxy_callback.py@@ -218,6 +218,59 @@ class TestAgentProxyCallback(TestCase):self.assertTrue(retried.json()["dispatched"])self.assertEqual(dispatch.call_args_list[0], dispatch.call_args_list[1])+ @parameterized.expand(+ [+ ("captured", {}, True, 200, 1),+ ("capture_failed", {}, False, 503, 0),+ ("missing_kill", {"process_killed": None}, True, 400, 0),+ ("negative_size", {"process_killed": {"tree_rss_bytes": -1}}, True, 400, 0),+ ]+ )+ def test_process_killed_capture(+ self,+ _name: str,+ overrides: dict[str, Any],+ capture_ok: bool,+ expected_status: int,+ expected_count: int,+ ) -> None:+ killed = {+ "comm": "bash",+ "signal": "SIGTERM",+ "tree_rss_bytes": 12 * 1024**3,+ "memory_current_bytes": 14 * 1024**3,+ "memory_limit_bytes": 16 * 1024**3,+ }+ if isinstance(overrides.get("process_killed"), dict):+ killed.update(overrides["process_killed"])+ body = self._body(kind="process_killed", agent_active=False, sequence=5, process_killed=killed)+ if "process_killed" in overrides and overrides["process_killed"] is None:+ del body["process_killed"]+ counter_before = REGISTRY.get_sample_value("posthog_tasks_sandbox_process_killed_notifications_total") or 0.0++ with patch.object(TaskRun, "capture_event", return_value=capture_ok) as capture:+ response = self._post(body, token=self._token())++ self.assertEqual(response.status_code, expected_status)+ self.assertEqual(+ REGISTRY.get_sample_value("posthog_tasks_sandbox_process_killed_notifications_total"),+ counter_before + expected_count,+ )+ if expected_status == 400:+ capture.assert_not_called()+ return+ capture.assert_called_once_with(+ "sandbox_process_killed",+ {+ "process_comm": "bash",+ "process_signal": "SIGTERM",+ "process_tree_rss_bytes": 12 * 1024**3,+ "memory_current_bytes": 14 * 1024**3,+ "memory_limit_bytes": 16 * 1024**3,+ },+ event_uuid=str(uuid5(NAMESPACE_URL, f"posthog-task-process-killed:{self.task_run.id}:5")),+ )+def test_heartbeat_dispatches_when_active(self) -> None:with patch.object(TaskRun, "heartbeat_workflow") as heartbeat:response = self._post(self._body(kind="heartbeat", agent_active=True), token=self._token())diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.pyindex 8378bd06151a..dd355d3cabb6 100644--- a/products/tasks/backend/tests/test_event_ingest.py+++ b/products/tasks/backend/tests/test_event_ingest.py@@ -45,6 +45,7 @@ from products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEYfrom ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGESKIP_COUNTER_SAMPLE = "posthog_tasks_task_run_stream_write_skipped_total"+PROCESS_KILLED_COUNTER_SAMPLE = "posthog_tasks_sandbox_process_killed_notifications_total"class TestSessionUpdateContract(SimpleTestCase):@@ -466,6 +467,54 @@ class TestTaskRunEventIngest(TestCase):self.assertEqual(capture_rtk_savings.call_count, 2)self.assertEqual(self._read_notification_methods(), ["_posthog/rtk_savings"])+ @parameterized.expand([("captured", None, 1), ("capture_fails", [RuntimeError("capture failed"), None], 2)])+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_process_killed_capture_is_idempotent_and_never_fails_the_batch(+ self, _name: str, capture_side_effect: list[object] | None, expected_captures: int+ ) -> None:+ token = self._create_token()+ event = {+ "seq": 1,+ "event": {+ "type": "notification",+ "notification": {+ "method": "_posthog/process_killed",+ "params": {+ "comm": "node",+ "signal": "SIGTERM",+ "treeRssBytes": 12 * 1024**3,+ "memoryCurrentBytes": 14 * 1024**3,+ "memoryLimitBytes": 16 * 1024**3,+ },+ },+ },+ }+ counter_before = REGISTRY.get_sample_value(PROCESS_KILLED_COUNTER_SAMPLE) or 0.0++ with patch("posthoganalytics.capture", side_effect=capture_side_effect) as capture:+ first_status, first_body = self._call_ingest(token, [event])+ retry_status, retry_body = self._call_ingest(token, [event])++ self.assertEqual((first_status, first_body["accepted"]), (200, 1))+ self.assertEqual((retry_status, retry_body["duplicate"]), (200, 1))+ self.assertEqual(capture.call_count, expected_captures)+ self.assertEqual(capture.call_args.kwargs["event"], "sandbox_process_killed")+ self.assertEqual(+ capture.call_args.kwargs["uuid"],+ str(uuid5(NAMESPACE_URL, f"posthog-task-process-killed:{self.task_run.id}:1")),+ )+ self.assertLessEqual(+ {+ "process_comm": "node",+ "process_signal": "SIGTERM",+ "process_tree_rss_bytes": 12 * 1024**3,+ "memory_limit_bytes": 16 * 1024**3,+ }.items(),+ capture.call_args.kwargs["properties"].items(),+ )+ self.assertEqual(REGISTRY.get_sample_value(PROCESS_KILLED_COUNTER_SAMPLE), counter_before + 1)+ self.assertEqual(self._read_notification_methods(), ["_posthog/process_killed"])+@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_rtk_savings_capture_rejects_fractional_counters(self) -> None:token = self._create_token()diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.tsindex feccf07f2024..fcb058e4e8a6 100644--- a/services/agent-proxy/src/hono/ingest-handler.ts+++ b/services/agent-proxy/src/hono/ingest-handler.ts@@ -27,7 +27,11 @@ import {import { validateSandboxEventIngestToken } from '../lib/jwt.js'import { logger } from '../lib/logging.js'import { TaskRunRedisStream, getStreamKey } from '../lib/redis-stream.js'-import { captureBudgetSteerIfNeeded, heartbeatWorkflowIfNeeded } from '../lib/side-effects.js'+import {+ captureBudgetSteerIfNeeded,+ captureProcessKilledIfNeeded,+ heartbeatWorkflowIfNeeded,+} from '../lib/side-effects.js'import {ClientDisconnected,EventIngestBadRequest,@@ -263,6 +267,7 @@ async function ingestEventLines(result.accepted++result.last_accepted_seq = seq+ captureProcessKilledIfNeeded(claims.runId, seq, event, claims.taskId, claims.teamId, originalToken, config)await heartbeatWorkflowIfNeeded(redisStream,diff --git a/services/agent-proxy/src/lib/side-effects.ts b/services/agent-proxy/src/lib/side-effects.tsindex 1ef5b2495e0b..1bf3e496f5ac 100644--- a/services/agent-proxy/src/lib/side-effects.ts+++ b/services/agent-proxy/src/lib/side-effects.ts@@ -184,7 +184,21 @@ export function isAgentGenerationEvent(event: Record<string, unknown>): booleanconst CALLBACK_TIMEOUT_MS = 10_000const RETRY_DELAY_MS = 1000-const RETRYABLE_KINDS: ReadonlySet<SideEffectKind> = new Set(['awaiting_input', 'turn_failed', 'budget_steer'])+const RETRYABLE_KINDS: ReadonlySet<SideEffectKind> = new Set([+ 'awaiting_input',+ 'turn_failed',+ 'budget_steer',+ 'process_killed',+])+const PROCESS_KILLED_METHOD = '_posthog/process_killed'++interface ProcessKilledPayload {+ comm: string+ signal: string+ tree_rss_bytes: number+ memory_current_bytes: number+ memory_limit_bytes: number+}function fetchErrorCode(err: unknown): string | undefined {if (!(err instanceof Error)) {@@ -235,9 +249,10 @@ function fireCallback(turnCompleted?: booleanturnSucceeded?: booleanbudgetSteer?: { sequence: number; timestamp?: string; params: Record<string, unknown> }+ processKilled?: { sequence: number; payload: ProcessKilledPayload }} = {}): void {- const { releaseClaim, turnCompleted, turnSucceeded, budgetSteer } = options+ const { releaseClaim, turnCompleted, turnSucceeded, budgetSteer, processKilled } = optionsif (!config.djangoCallbackBaseUrl) {// Dev environment without AGENT_PROXY_DJANGO_CALLBACK_URL — skip silently.void releaseMilestoneClaim(releaseClaim, runId, kind)@@ -260,6 +275,7 @@ function fireCallback(delivered_at: budgetSteer.params['delivered_at'],}: {}),+ ...(processKilled ? { sequence: processKilled.sequence, process_killed: processKilled.payload } : {}),kind,agent_active: agentActive,task_id: taskId,@@ -297,8 +313,8 @@ function fireCallback('dispatched' in payload &&payload.dispatched === trueif (!dispatched) {- if (kind === 'budget_steer') {- logger.warn('side_effect:budget_steer_not_captured', { run: runId })+ if (kind === 'budget_steer' || kind === 'process_killed') {+ logger.warn(`side_effect:${kind}_not_captured`, { run: runId })}await releaseMilestoneClaim(releaseClaim, runId, kind)}@@ -339,6 +355,61 @@ export function captureBudgetSteerIfNeeded(})}+function byteCount(value: unknown): number | null {+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : null+}++function parseProcessKilled(event: Record<string, unknown>): ProcessKilledPayload | null {+ if (event['type'] !== ACP_NOTIFICATION_TYPE) {+ return null+ }+ const notification = event['notification']+ if (typeof notification !== 'object' || notification === null || Array.isArray(notification)) {+ return null+ }+ const { method, params } = notification as Record<string, unknown>+ if (method !== PROCESS_KILLED_METHOD || typeof params !== 'object' || params === null || Array.isArray(params)) {+ return null+ }+ const fields = params as Record<string, unknown>+ const comm = fields['comm']+ const signal = fields['signal']+ const treeRssBytes = byteCount(fields['treeRssBytes'])+ const memoryCurrentBytes = byteCount(fields['memoryCurrentBytes'])+ const memoryLimitBytes = byteCount(fields['memoryLimitBytes'])+ if (typeof comm !== 'string' || typeof signal !== 'string') {+ return null+ }+ if (treeRssBytes === null || memoryCurrentBytes === null || memoryLimitBytes === null) {+ return null+ }+ return {+ comm,+ signal,+ tree_rss_bytes: treeRssBytes,+ memory_current_bytes: memoryCurrentBytes,+ memory_limit_bytes: memoryLimitBytes,+ }+}++export function captureProcessKilledIfNeeded(+ runId: string,+ sequence: number,+ event: Record<string, unknown>,+ taskId: string,+ teamId: number,+ originalToken: string,+ config: Config+): void {+ const payload = parseProcessKilled(event)+ if (payload === null) {+ return+ }+ fireCallback(runId, 'process_killed', false, taskId, teamId, originalToken, config, {+ processKilled: { sequence, payload },+ })+}+async function releaseMilestoneClaim(release: (() => Promise<void>) | undefined,runId: string,diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.tsindex a540c8aa478b..b150cb152c2f 100644--- a/services/agent-proxy/src/lib/types.ts+++ b/services/agent-proxy/src/lib/types.ts@@ -178,6 +178,7 @@ export type SideEffectKind =| 'command_dispatched'| 'agent_activity'| 'budget_steer'+ | 'process_killed'// ---------------------------------------------------------------------------// TaskRunRedisStream method interfacediff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.tsindex a79e49442190..29e6e4d1b6e7 100644--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts@@ -651,6 +651,58 @@ describe('ingest-handler', () => {}})+ it('forwards a process kill once, without the command line', async () => {+ const callback = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(new Response(JSON.stringify({ dispatched: true }), { status: 200 }))+ try {+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django.example.com' })+ const event = {+ type: 'notification',+ notification: {+ method: '_posthog/process_killed',+ params: {+ pid: 443,+ comm: 'bash',+ signal: 'SIGTERM',+ treeRssBytes: 12_884_901_888,+ memoryCurrentBytes: 14_698_577_920,+ memoryLimitBytes: 17_179_869_184,+ cmdline: ['bash', '-c', 'deploy --token not-for-analytics'],+ },+ },+ }+ const line = JSON.stringify({ seq: 1, event }) + '\n'+ for (let attempt = 0; attempt < 2; attempt++) {+ const response = await handleIngest(+ makeContext({ body: makeStringBody(line) }),+ fakeRedis as unknown as Redis,+ config,+ [] as CryptoKey[]+ )+ expect(response.status).toBe(200)+ }+ await vi.waitFor(() => expect(callback).toHaveBeenCalledTimes(1))+ const request = callback.mock.calls[0]![1]+ expect(JSON.parse(String(request?.body))).toMatchObject({+ kind: 'process_killed',+ task_id: TASK_ID,+ team_id: TEAM_ID,+ sequence: 1,+ process_killed: {+ comm: 'bash',+ signal: 'SIGTERM',+ tree_rss_bytes: 12_884_901_888,+ memory_current_bytes: 14_698_577_920,+ memory_limit_bytes: 17_179_869_184,+ },+ })+ expect(String(request?.body)).not.toContain('not-for-analytics')+ } finally {+ callback.mockRestore()+ }+ })+it('retries a budget steer callback after a temporary capture failure', async () => {const callback = vi.spyOn(globalThis, 'fetch')