From 31da0558d1115828b048a3512428c521faae1cf2 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 6 Oct 2026 11:12:17 -0500 Subject: [PATCH] fix: preserve Grok session metadata when history exceeds retention limits Co-Authored-By: Paperclip --- doc/connections/AI-CONNECTIONS.md | 5 +++- server/src/__tests__/ai-connections.test.ts | 30 ++++++++++++++++++++- server/src/services/grok-session-history.ts | 17 ++++++++---- server/src/services/heartbeat.ts | 11 +++++++- 4 files changed, 55 insertions(+), 8 deletions(-) diff --git a/doc/connections/AI-CONNECTIONS.md b/doc/connections/AI-CONNECTIONS.md index a02f40218e0..ec9f26d5b5b 100644 --- a/doc/connections/AI-CONNECTIONS.md +++ b/doc/connections/AI-CONNECTIONS.md @@ -582,7 +582,10 @@ The archive is scoped to the company, agent, task, and selected account identity The server restores only that archive into a disposable private runtime home. It excludes credentials, symlinks, and hard links and limits archive size and entry count. Runtime homes do not link to a shared plaintext history directory. A bounded -history lookup can start a fresh session rather than fail the task. +history lookup can start a fresh session rather than fail the task. If a checkpoint +exceeds 16 MiB or 5,000 entries, the server still saves the provider session metadata. +It records a warning and marks the transcript unavailable. The next run starts a +fresh session with the task handoff instead of restoring a partial archive. Runtime projection clears alternate provider credentials and routing overrides, uses disposable homes, and never falls back to host authentication. Codex probes diff --git a/server/src/__tests__/ai-connections.test.ts b/server/src/__tests__/ai-connections.test.ts index 86549afead0..a56a4a6eae6 100644 --- a/server/src/__tests__/ai-connections.test.ts +++ b/server/src/__tests__/ai-connections.test.ts @@ -5,7 +5,7 @@ import { localAiLoginService } from "../services/local-ai-login.js"; import * as localCredentials from "../services/local-ai-credentials.js"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { randomUUID } from "node:crypto"; -import { mkdtemp, realpath, rm, access, readFile, writeFile, stat, readdir, symlink } from "node:fs/promises"; +import { mkdtemp, realpath, rm, access, readFile, writeFile, stat, readdir, symlink, truncate } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { and, eq, sql } from "drizzle-orm"; @@ -114,6 +114,34 @@ describe("managed AI connections", () => { await expect(access(path.join(String(resumed.config.env.GROK_HOME), "auth.json"))).rejects.toThrow(); } finally { await Promise.all([resumed.cleanup(), otherAgent.cleanup(), otherAccount.cleanup(), otherTask.cleanup()]); } }); + it.each(["bytes", "entries"])("keeps the Grok provider checkpoint when history exceeds its %s limit", async (limit) => { + const account = await service.save(companyId, "alice", { provider: "xai", method: "api_key", ownership: "personal", name: `History limit ${limit}`, agentIds: [], allAgents: true }, "fixture-key"); + const taskKey = `grok-limit-${randomUUID()}`; + await db.insert(agentTaskSessions).values({ companyId, agentId, adapterType: "grok_local", taskKey, sessionParamsJson: {} }); + const runInput = { ...input, taskKey, adapterType: "grok_local", responsibleUserId: "alice", config: {}, binding: { provider: "xai", method: "api_key", mode: "connection", connectionId: account.connectionId, grantId: account.grantId } as const }; + const runtime = await prepareManagedAiRuntime(db, runInput); + try { + const sessions = path.join(String(runtime.config.env.GROK_HOME), "sessions"); + if (limit === "bytes") { + const file = path.join(sessions, "oversized.json"); + await writeFile(file, ""); + await truncate(file, 17 * 1024 * 1024); + } else { + for (let start = 0; start < 5001; start += 100) { + await Promise.all(Array.from({ length: Math.min(100, 5001 - start) }, (_, i) => writeFile(path.join(sessions, `${start + i}.json`), ""))); + } + } + const checkpoint = await runtime.checkpointSessionHistory!(); + expect(checkpoint).toEqual({ paperclipGrokHistory: null, paperclipGrokHistoryStatus: "fresh_session_required" }); + // This is the same merge persisted by heartbeat before releasing ownership. + await db.update(agentTaskSessions).set({ sessionParamsJson: { sessionId: "provider-session", cwd: "/workspace", ...checkpoint } }).where(eq(agentTaskSessions.taskKey, taskKey)); + } finally { await runtime.cleanup(); } + const [stored] = await db.select().from(agentTaskSessions).where(eq(agentTaskSessions.taskKey, taskKey)); + expect(stored.sessionParamsJson).toMatchObject({ sessionId: "provider-session", cwd: "/workspace", paperclipGrokHistory: null }); + const resumed = await prepareManagedAiRuntime(db, runInput); + try { expect(await readdir(path.join(String(resumed.config.env.GROK_HOME), "sessions"))).toEqual([]); } + finally { await resumed.cleanup(); } + }); it("authenticates local Gemini probes and runs with the saved key in an isolated home", async () => { const root = await mkdtemp(path.join(home, "gemini-auth-")); const command = path.join(root, "gemini"); diff --git a/server/src/services/grok-session-history.ts b/server/src/services/grok-session-history.ts index 113ff683553..0a69f05e68c 100644 --- a/server/src/services/grok-session-history.ts +++ b/server/src/services/grok-session-history.ts @@ -10,6 +10,7 @@ import type { StoredSecretVersionMaterial } from "../secrets/types.js"; const MAX_BYTES = 16 * 1024 * 1024; const MAX_ENTRIES = 5000; const FIELD = "paperclipGrokHistory"; +class GrokHistoryLimitError extends Error {} type Entry = { name: string; bytes: string }; function validName(name: string) { @@ -59,7 +60,7 @@ export async function prepareGrokSessionHistory(db: Db, input: { let count = 0; async function collect(relative = "") { for (const entry of await readdir(path.join(root, relative), { withFileTypes: true })) { - if (++count > MAX_ENTRIES) throw new Error("Grok history exceeds its entry bound"); + if (++count > MAX_ENTRIES) throw new GrokHistoryLimitError("Grok history exceeds its entry bound"); const name = relative ? `${relative}/${entry.name}` : entry.name; if (!validName(name) || entry.isSymbolicLink()) continue; const source = path.join(root, name); @@ -69,19 +70,25 @@ export async function prepareGrokSessionHistory(db: Db, input: { try { const stat = await file.stat(); if (!stat.isFile() || stat.nlink !== 1) continue; - if (size + stat.size > MAX_BYTES) throw new Error("Grok history exceeds its storage bound"); + if (size + stat.size > MAX_BYTES) throw new GrokHistoryLimitError("Grok history exceeds its storage bound"); const bytes = await file.readFile(); size += bytes.length; - if (size > MAX_BYTES) throw new Error("Grok history exceeds its storage bound"); + if (size > MAX_BYTES) throw new GrokHistoryLimitError("Grok history exceeds its storage bound"); entries.push({ name, bytes: bytes.toString("base64") }); } finally { await file.close(); } } } - await collect(); + try { await collect(); } + catch (error) { + if (!(error instanceof GrokHistoryLimitError)) throw error; + // Save provider metadata normally, but explicitly discard the unusable + // transcript. The adapter starts with a fresh task handoff next time. + return { [FIELD]: null, paperclipGrokHistoryStatus: "fresh_session_required" }; + } if (entries.length === 0) return; const prepared = await localEncryptedProvider.createVersion({ value: JSON.stringify({ scope, entries }) }); // The heartbeat writes this with the provider session's checkpoint before // releasing execution ownership. Cleanup must not race a subsequent resume. - return { [FIELD]: { scope, material: prepared.material } }; + return { [FIELD]: { scope, material: prepared.material }, paperclipGrokHistoryStatus: "retained" }; }; } diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 7fdbb74f15f..ed4835bca99 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -26064,6 +26064,7 @@ export function heartbeatService( expectedRunId: finalizedRun.id, }); } else { + const historyCheckpoint = await managedAiRuntime?.checkpointSessionHistory?.(); await upsertTaskSession({ companyId: agent.companyId, agentId: agent.id, @@ -26075,12 +26076,20 @@ export function heartbeatService( configuredModel, sessionConfigMetadata, ), - ...await managedAiRuntime?.checkpointSessionHistory?.(), + ...historyCheckpoint, }, sessionDisplayId: nextSessionState.displayId, lastRunId: finalizedRun.id, lastError: runErrorMessage, }); + if (historyCheckpoint?.paperclipGrokHistoryStatus === "fresh_session_required") { + await appendRunEvent(finalizedRun, { + eventType: "session_history_limit", + stream: "system", + level: "warn", + message: "Grok history exceeded its retention limit. The next run will start a fresh session with the task handoff.", + }).catch((error) => logger.warn({ error, runId: finalizedRun.id }, "Could not record Grok history limit")); + } } } }