: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(desktop): keep retrying session log flushes instead of dropping them (#99213)
Alessandro Pogliaghiee9839e9c5a9
diff --git a/products/desktop/packages/agent/src/agent.ts b/products/desktop/packages/agent/src/agent.tsindex 9658583056b7..3cc4460a0e8a 100644--- a/products/desktop/packages/agent/src/agent.ts+++ b/products/desktop/packages/agent/src/agent.ts@@ -309,7 +309,10 @@ export class Agent {async cleanup(): Promise<void> {if (this.sessionLogWriter && this.taskRunId) {- await this.sessionLogWriter.flush(this.taskRunId, { coalesce: true });+ await this.sessionLogWriter.flush(this.taskRunId, {+ coalesce: true,+ retry: true,+ });}await this.acpConnection?.cleanup();}diff --git a/products/desktop/packages/agent/src/posthog-api.ts b/products/desktop/packages/agent/src/posthog-api.tsindex d0ea2ba080d1..b852dd87ee38 100644--- a/products/desktop/packages/agent/src/posthog-api.ts+++ b/products/desktop/packages/agent/src/posthog-api.ts@@ -117,6 +117,24 @@ export type TaskRunUpdate = Partial<state_append?: Record<string, unknown>;};+export class PostHogAPIError extends Error {+ constructor(+ message: string,+ readonly status: number,+ readonly credentialsRefreshable: boolean = false,+ ) {+ super(message);+ this.name = "PostHogAPIError";+ }++ get retryable(): boolean {+ if (this.status === 401) {+ return this.credentialsRefreshable;+ }+ return this.status >= 500 || this.status === 408 || this.status === 429;+ }+}+export class PostHogAPIClient {private config: PostHogAPIConfig;private userNode: string | null | undefined;@@ -204,7 +222,11 @@ export class PostHogAPIClient {} catch {errorMessage = `Failed request: [${response.status}] ${response.statusText}`;}- throw new Error(errorMessage);+ throw new PostHogAPIError(+ errorMessage,+ response.status,+ Boolean(this.config.refreshApiKey),+ );}return response.json();diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex ae3bcd802c49..fd1d41dc0cf0 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -5858,6 +5858,7 @@ ${commonInstructions}try {await this.session.logWriter.flush(this.session.payload.run_id, {coalesce: true,+ retry: true,});} catch (error) {this.logger.error("Failed to flush session logs", error);diff --git a/products/desktop/packages/agent/src/session-log-writer.test.ts b/products/desktop/packages/agent/src/session-log-writer.test.tsindex 57549f5fbffb..50683569b095 100644--- a/products/desktop/packages/agent/src/session-log-writer.test.ts+++ b/products/desktop/packages/agent/src/session-log-writer.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { PostHogAPIClient } from "./posthog-api";+import { type PostHogAPIClient, PostHogAPIError } from "./posthog-api";import { SessionLogWriter } from "./session-log-writer";import type { StoredNotification } from "./types";@@ -144,26 +144,153 @@ describe("SessionLogWriter", () => {expect(retriedEntries[0].notification.method).toBe("test");});- it("drops entries after max retries", async () => {+ it("keeps retrying past ten failures and delivers once persistence recovers", async () => {const sessionId = "s1";logWriter.register(sessionId, { taskId: "t1", runId: sessionId });mockAppendLog.mockRejectedValue(new Error("persistent failure"));-logWriter.appendRawLine(sessionId, JSON.stringify({ method: "test" }));- // Flush 10 times (MAX_FLUSH_RETRIES) — entries should be dropped on the 10th- for (let i = 0; i < 10; i++) {+ for (let i = 0; i < 12; i++) {await logWriter.flush(sessionId);}+ expect(mockAppendLog).toHaveBeenCalledTimes(12);- expect(mockAppendLog).toHaveBeenCalledTimes(10);-- // After max retries the entries are dropped, so an 11th flush has nothing- mockAppendLog.mockClear();+ mockAppendLog.mockResolvedValue(undefined);await logWriter.flush(sessionId);- expect(mockAppendLog).not.toHaveBeenCalled();++ expect(mockAppendLog).toHaveBeenCalledTimes(13);+ const delivered: StoredNotification[] = mockAppendLog.mock.calls[12][2];+ expect(delivered.map((entry) => entry.notification.method)).toEqual([+ "test",+ ]);});++ it.each([+ ["a 404", 404, ["later"]],+ ["a 401", 401, ["later"]],+ ["a 503", 503, ["test", "later"]],+ ])(+ "after %s the next flush sends %j",+ async (_label, status, expectedMethods) => {+ const sessionId = "s1";+ logWriter.register(sessionId, { taskId: "t1", runId: sessionId });+ mockAppendLog.mockRejectedValueOnce(+ new PostHogAPIError(`Failed request: [${status}]`, status),+ );++ logWriter.appendRawLine(sessionId, JSON.stringify({ method: "test" }));+ await logWriter.flush(sessionId);+ logWriter.appendRawLine(sessionId, JSON.stringify({ method: "later" }));+ await logWriter.flush(sessionId);++ expect(mockAppendLog).toHaveBeenCalledTimes(2);+ const sent: StoredNotification[] = mockAppendLog.mock.calls[1][2];+ expect(sent.map((entry) => entry.notification.method)).toEqual(+ expectedMethods,+ );+ },+ );++ it("retries on schedule while new entries keep arriving during an outage", async () => {+ vi.useFakeTimers();+ try {+ const sessionId = "s1";+ logWriter.register(sessionId, { taskId: "t1", runId: sessionId });+ mockAppendLog.mockRejectedValue(new Error("network error"));++ logWriter.appendRawLine(sessionId, JSON.stringify({ method: "test" }));+ await logWriter.flush(sessionId);+ expect(mockAppendLog).toHaveBeenCalledTimes(1);++ for (let i = 0; i < 5; i++) {+ await vi.advanceTimersByTimeAsync(300);+ logWriter.appendRawLine(+ sessionId,+ JSON.stringify({ method: "test" }),+ );+ }++ expect(mockAppendLog).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it("flush with retry re-sends the batch after a transient failure", async () => {+ vi.useFakeTimers();+ try {+ const sessionId = "s1";+ logWriter.register(sessionId, { taskId: "t1", runId: sessionId });+ mockAppendLog+ .mockRejectedValueOnce(new Error("network error"))+ .mockResolvedValueOnce(undefined);++ logWriter.appendRawLine(sessionId, JSON.stringify({ method: "test" }));+ const flushed = logWriter.flush(sessionId, { retry: true });+ await vi.advanceTimersByTimeAsync(1000);+ await flushed;++ expect(mockAppendLog).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it("stops flushing once a retrying flush exhausts its attempts", async () => {+ vi.useFakeTimers();+ try {+ const sessionId = "s1";+ logWriter.register(sessionId, { taskId: "t1", runId: sessionId });+ mockAppendLog.mockRejectedValue(new Error("network error"));++ logWriter.appendRawLine(sessionId, JSON.stringify({ method: "test" }));+ const flushed = logWriter.flush(sessionId, { retry: true });+ await vi.advanceTimersByTimeAsync(5000);+ await flushed;++ mockAppendLog.mockClear();+ await vi.advanceTimersByTimeAsync(60_000);++ expect(mockAppendLog).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it.each([+ ["a small log", 10, 1],+ ["a log past 4 MiB", 5 * 1024 * 1024, 0],+ ])(+ "flushes a burst 6s after the last flush for %s",+ async (_label, textBytes, expectedFlushes) => {+ vi.useFakeTimers();+ try {+ const sessionId = "s1";+ logWriter.register(sessionId, { taskId: "t1", runId: sessionId });+ logWriter.appendRawLine(+ sessionId,+ JSON.stringify({+ method: "test",+ params: { text: "x".repeat(textBytes) },+ }),+ );+ await logWriter.flush(sessionId);+ mockAppendLog.mockClear();++ vi.advanceTimersByTime(6000);+ logWriter.appendRawLine(+ sessionId,+ JSON.stringify({ method: "test" }),+ );+ await vi.advanceTimersByTimeAsync(0);++ expect(mockAppendLog).toHaveBeenCalledTimes(expectedFlushes);+ } finally {+ vi.useRealTimers();+ }+ },+ );});describe("sinks", () => {diff --git a/products/desktop/packages/agent/src/session-log-writer.ts b/products/desktop/packages/agent/src/session-log-writer.tsindex ad1402ec1140..e072391f7655 100644--- a/products/desktop/packages/agent/src/session-log-writer.ts+++ b/products/desktop/packages/agent/src/session-log-writer.ts@@ -5,7 +5,7 @@ import {isTranscriptNeutralNotificationMethod,serializeError,} from "@posthog/shared";-import type { PostHogAPIClient } from "./posthog-api";+import { type PostHogAPIClient, PostHogAPIError } from "./posthog-api";import type { StoredNotification } from "./types";import { isEmptyContentBlock } from "./utils/acp-content";import { Logger } from "./utils/logger";@@ -92,7 +92,10 @@ export class SessionLogWriter {private static readonly TOOL_UPDATE_MAX_HOLD_MS = 2000;private static readonly FLUSH_DEBOUNCE_MS = 500;private static readonly FLUSH_MAX_INTERVAL_MS = 5000;- private static readonly MAX_FLUSH_RETRIES = 10;+ private static readonly FLUSH_MAX_INTERVAL_LARGE_LOG_MS = 10_000;+ private static readonly LARGE_LOG_BYTES = 4 * 1024 * 1024;+ private static readonly FLUSH_FAILURE_LOG_EVERY = 10;+ private static readonly SHUTDOWN_FLUSH_ATTEMPTS = 3;private static readonly MAX_RETRY_DELAY_MS = 30_000;private static readonly SESSIONS_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;@@ -101,6 +104,7 @@ export class SessionLogWriter {private flushTimeouts: Map<string, NodeJS.Timeout> = new Map();private lastFlushAttemptTime: Map<string, number> = new Map();private retryCounts: Map<string, number> = new Map();+ private flushedBytes: Map<string, number> = new Map();private sessions: Map<string, SessionState> = new Map();private flushQueues: Map<string, Promise<void>> = new Map();private sinks: SessionLogSink[];@@ -122,14 +126,47 @@ export class SessionLogWriter {// Coalesce any in-progress chunk buffers before the final flush// During normal operation, chunks are coalesced when the next non-chunk// event arrives, but on shutdown there may be no subsequent event- const flushPromises: Promise<void>[] = [];for (const [sessionId, session] of this.sessions) {this.emitCoalescedMessage(sessionId, session);this.flushToolUpdateCache(sessionId, session);this.drainRawInputSnapshots(sessionId, session);- flushPromises.push(this.flush(sessionId));}- await Promise.all(flushPromises);+ await this.flushWithRetries([...this.sessions.keys()]);+ }++ private async flushWithRetries(sessionIds: string[]): Promise<void> {+ const unflushed = () =>+ sessionIds.filter(+ (sessionId) => this.pendingEntries.get(sessionId)?.length,+ );+ for (+ let attempt = 0;+ attempt < SessionLogWriter.SHUTDOWN_FLUSH_ATTEMPTS;+ attempt+++ ) {+ if (attempt > 0) {+ await new Promise((resolve) => setTimeout(resolve, 1000));+ }+ await Promise.all(sessionIds.map((sessionId) => this._flush(sessionId)));+ if (!unflushed().length) {+ return;+ }+ }+ for (const sessionId of unflushed()) {+ const pending = this.pendingEntries.get(sessionId) ?? [];+ const timeout = this.flushTimeouts.get(sessionId);+ if (timeout) {+ clearTimeout(timeout);+ this.flushTimeouts.delete(sessionId);+ }+ this.logger.error("Session log entries not persisted at shutdown", {+ taskId: this.sessions.get(sessionId)?.context.taskId,+ runId: this.sessions.get(sessionId)?.context.runId,+ count: pending.length,+ firstEventId: pending[0].first_event_id ?? pending[0].event_id,+ lastEventId: pending[pending.length - 1].event_id,+ });+ }}register(sessionId: string, context: SessionContext): void {@@ -339,7 +376,10 @@ export class SessionLogWriter {async flush(sessionId: string,- { coalesce = false }: { coalesce?: boolean } = {},+ {+ coalesce = false,+ retry = false,+ }: { coalesce?: boolean; retry?: boolean } = {},): Promise<void> {if (coalesce) {const session = this.sessions.get(sessionId);@@ -349,6 +389,10 @@ export class SessionLogWriter {}}+ return retry ? this.flushWithRetries([sessionId]) : this._flush(sessionId);+ }++ private _flush(sessionId: string): Promise<void> {// Serialize flushes per sessionconst prev = this.flushQueues.get(sessionId) ?? Promise.resolve();const next = prev.catch(() => {}).then(() => this._doFlush(sessionId));@@ -389,39 +433,55 @@ export class SessionLogWriter {pending,);this.retryCounts.set(sessionId, 0);+ this.flushedBytes.set(+ sessionId,+ (this.flushedBytes.get(sessionId) ?? 0) ++ Buffer.byteLength(JSON.stringify(pending)),+ );} catch (error) {+ if (error instanceof PostHogAPIError && !error.retryable) {+ this.retryCounts.set(sessionId, 0);+ this.logger.error("Session log batch rejected, dropping it", {+ taskId: session.context.taskId,+ runId: session.context.runId,+ status: error.status,+ count: pending.length,+ firstEventId: pending[0].first_event_id ?? pending[0].event_id,+ lastEventId: pending[pending.length - 1].event_id,+ });+ return;+ }const retryCount = (this.retryCounts.get(sessionId) ?? 0) + 1;this.retryCounts.set(sessionId, retryCount);-- if (retryCount >= SessionLogWriter.MAX_FLUSH_RETRIES) {- this.logger.error(- `Dropping ${pending.length} session log entries after ${retryCount} failed flush attempts`,- {- taskId: session.context.taskId,- runId: session.context.runId,- maxRetries: SessionLogWriter.MAX_FLUSH_RETRIES,- errorDetail: serializeError(error),- },- );- this.retryCounts.set(sessionId, 0);- } else {- if (retryCount === 1) {- this.logger.warn(- `Failed to persist session logs, will retry (up to ${SessionLogWriter.MAX_FLUSH_RETRIES} attempts)`,- {- taskId: session.context.taskId,- runId: session.context.runId,- error: error instanceof Error ? error.message : String(error),- },- );- }- const currentPending = this.pendingEntries.get(sessionId) ?? [];- this.pendingEntries.set(sessionId, [...pending, ...currentPending]);- this.scheduleFlush(sessionId);+ const currentPending = this.pendingEntries.get(sessionId) ?? [];+ this.pendingEntries.set(sessionId, [...pending, ...currentPending]);++ if (retryCount === 1) {+ this.logger.warn("Failed to persist session logs, will retry", {+ taskId: session.context.taskId,+ runId: session.context.runId,+ error: error instanceof Error ? error.message : String(error),+ });+ } else if (retryCount % SessionLogWriter.FLUSH_FAILURE_LOG_EVERY === 0) {+ this.logger.error("Session logs still failing to persist", {+ taskId: session.context.taskId,+ runId: session.context.runId,+ attempts: retryCount,+ pendingEntries: pending.length + currentPending.length,+ errorDetail: serializeError(error),+ });}+ this.scheduleFlush(sessionId);}}+ private flushMaxIntervalMs(sessionId: string): number {+ return (this.flushedBytes.get(sessionId) ?? 0) >=+ SessionLogWriter.LARGE_LOG_BYTES+ ? SessionLogWriter.FLUSH_MAX_INTERVAL_LARGE_LOG_MS+ : SessionLogWriter.FLUSH_MAX_INTERVAL_MS;+ }+private emitToSinks(sessionId: string, entry: StoredNotification): void {for (const sink of this.sinks) {try {@@ -697,11 +757,14 @@ export class SessionLogWriter {let delay: number;if (retryCount > 0) {// Exponential backoff on retries: FLUSH_DEBOUNCE_MS * 2^retryCount, capped- delay = Math.min(- SessionLogWriter.FLUSH_DEBOUNCE_MS * 2 ** retryCount,- SessionLogWriter.MAX_RETRY_DELAY_MS,+ delay = Math.max(+ Math.min(+ SessionLogWriter.FLUSH_DEBOUNCE_MS * 2 ** retryCount,+ SessionLogWriter.MAX_RETRY_DELAY_MS,+ ) - elapsed,+ 0,);- } else if (elapsed >= SessionLogWriter.FLUSH_MAX_INTERVAL_MS) {+ } else if (elapsed >= this.flushMaxIntervalMs(sessionId)) {// If we've been accumulating for longer than the max interval, flush immediatelydelay = 0;} else {