Files
paperclip/packages/db/scripts/clean-poisoned-claude-sessions.test.ts
T
Danial Jawaid 8ee3987d12 adapter-claude-local: recover from poisoned previous_message_id 400 (detect + clearSession) (#5972)
## Thinking Path

> - Paperclip's `claude_local` adapter persists Claude Code session
jsonls under `~/.claude/projects/…/{sessionId}.jsonl` and resumes them
on the next heartbeat
> - When Claude Code injects `<synthetic>` placeholder assistant
messages (after rate-limit, max-turn exhaustion, or transient-upstream
failures) those placeholders get UUID-format `message.id`s rather than
`msg_…`-format ids
> - On the next `--resume`, Claude Code passes that UUID as
`previous_message_id` and Anthropic's API rejects it with a 400:
``diagnostics.previous_message_id: must be the `id` from a prior
/v1/messages response (starts with `msg_`)``
> - The adapter had a session-rotation fallback only for "unknown
session" errors, so the poisoned session was `--resume`-d indefinitely
and the agent flipped between `idle` and `error` every heartbeat
> - Even worse, the *result* event of the failing run still carried a
`session_id`, and the adapter was persisting that id into the
issue-scoped session store (`agentTaskSessions`). So even after we
detected the 400, every subsequent continuation re-loaded the same
poisoned id and hit the same 400 again — the issue was permanently
stranded
> - We observed this on multiple agents in our deployment; the only
manual fix was to rename the `.jsonl`, which is not a viable long-term
workaround
> - This PR detects the 400, runs the same session-rotation fallback the
unknown-session path uses **and** stops persisting the poisoned id, so
the next attempt starts genuinely fresh

## Linked Issues or Issue Description

No external GitHub issue is linked. Describing the problem inline
following the bug-report template:

**What happened:** `claude_local` agents flipped between `idle` and
`error` on every heartbeat because the persisted session jsonl carried a
synthetic UUID `previous_message_id` (from `<synthetic>` assistant
placeholders injected after rate-limit/max-turn/upstream errors).
Anthropic's API rejected every `--resume` with a 400:
``diagnostics.previous_message_id: must be the `id` from a prior
/v1/messages response (starts with `msg_`)``.

**Expected behavior:** When the persisted session is poisoned and
unrecoverable, the adapter should rotate to a fresh session — the same
fallback path already used for unknown-session errors — and stop
re-persisting the poisoned `session_id`.

**Actual behavior:** The session-rotation fallback only matched the
"unknown session" pattern, so the poisoned session was `--resume`-d
forever. The result event of the failing run still carried `session_id`,
which was being persisted into `agentTaskSessions`, so every subsequent
continuation reloaded the same poisoned id and hit the same 400.

**Reproduction:** Inject any flow that causes Claude Code to emit a
`<synthetic>` placeholder (rate-limit, max-turn exhaustion, transient
upstream failure). The next `--resume` will fail with the 400 and the
agent will not self-recover.

**Scope of fix:** Add a `previous_message_id` 400 detector; route it
through the existing unknown-session fallback; drop the poisoned
`sessionId` and emit `clearSession: true` so the heartbeat service wipes
the persisted row; best-effort delete the local poisoned `.jsonl`.

## What Changed

Two commits:

1. **`adapter-claude-local: auto-rotate session on previous_message_id
400 (synthetic-msg poisoning)`** — detector + execute-time rotation
2. **`adapter-claude-local: guard against persisting poisoned
sessionId`** — validate-before-persist + `clearSession`

Combined diff:

- `parse.ts`: new `isClaudePoisonedPreviousMessageIdError(parsed)`
matching ``/diagnostics\.previous_message_id.*starts with `msg_`/i``
against `parsed.result` and `extractClaudeErrorMessages(parsed)`
- `parse.ts`: `isClaudeTransientUpstreamError()` excludes the new error
from transient classification so it isn't masked as retryable upstream
noise
- `execute.ts`: expand the resume-fallback branch so it triggers on both
`isClaudeUnknownSessionError` and the new
`isClaudePoisonedPreviousMessageIdError`, with a distinct log line
(`"returned a poisoned message-id"` vs `"is unavailable"`)
- `execute.ts`: for local (non-remote) execution targets, best-effort
delete the poisoned `~/.claude/projects/.../{sessionId}.jsonl` before
retrying so the file can't be accidentally resumed by an out-of-band
caller. The `fs.unlink` and follow-up log call are in separate try/catch
blocks so a closed log stream cannot mask a successful unlink (and vice
versa)
- `execute.ts` / `toAdapterResult`: when a result carries the poisoned
400, **drop** `sessionId`/`sessionParams`/`sessionDisplayId` (return
`null`) and emit `clearSession: true` so the heartbeat service's
`resolveNextSessionState` wipes the persisted row. The result also
surfaces `errorCode: "claude_poisoned_previous_message_id"` for
observability
- `docs/adapters/claude-local.md`: runbook entry — symptom,
auto-recovery flow, on-call checklist
- Tests:
- 4 new `parse.test.ts` cases covering positive detection in `result`
and `errors[]`, negative cases, and non-transient classification
- 3 new `claude-local-execute.test.ts` cases: (a) fresh run reports the
poisoned error → sessionId dropped + `clearSession: true`; (b) recovery
retry also reports the poisoned error → same guards apply; (c)
session-rotation success on retry

## Verification

```bash
pnpm --filter @paperclipai/adapter-claude-local exec vitest run src/server/parse.test.ts
pnpm --filter @paperclipai/server exec vitest run src/__tests__/claude-local-execute.test.ts
```

Both suites green locally. This patch is also currently running as a
hot-patch over the published `2026.513.0` adapter on the reporting
deployment — sessions that previously looped indefinitely now
self-recover on the first heartbeat after the 400 surfaces.

## Risks

- Low risk. The detector is conservative (regex over `result` +
`errors[]` only) and the rotation reuses the existing unknown-session
fallback path
- The local-only `fs.unlink` of the poisoned `.jsonl` is wrapped in
`try/catch` and ignored on failure — strictly an optimization; the
server-side session clear is the authoritative reset
- Remote execution targets (`executionTargetIsRemote`) skip the disk
cleanup because the file lives on a remote host that we can't safely
reach from the adapter
- The `clearSession: true` + nulled session fields path is a no-op on
healthy runs; it only fires when the new detector matches, so existing
successful continuations are unaffected
- No DB schema changes, no public API changes, no new dependencies

## Model Used

- Provider: Anthropic Claude
- Model: `claude-opus-4-7` (Opus 4.7)
- Context window: 1M
- Capabilities: extended reasoning, tool use, code execution
- Role: implemented the detector, expanded the fallback branch, added
the persist-guard + `clearSession`, wrote the unit + integration tests,
validated locally, and applied the equivalent hot-patch to the deployed
`2026.513.0` install while this PR is in review

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for similar or duplicate PRs and linked
them — closed #2295, #2361, #3572, #5438 as duplicates of this canonical
fix; complementary fixes #4838 (heartbeat_timer reset) and #4932 (gemini
context-overflow rotation) target different code paths
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots — N/A, adapter-only change
- [x] I have updated relevant documentation
(`docs/adapters/claude-local.md` runbook entry)
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Danial Jawaid <danial.jawaid@gmail.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Devin Foley <devin@paperclip.ing>
2026-06-09 15:45:47 -07:00

167 lines
5.5 KiB
TypeScript

import path from "node:path";
import { describe, expect, it } from "vitest";
import {
classifyJsonlText,
classifyRow,
encodeClaudeCwd,
jsonlPathFor,
resolveClaudeConfigDir,
} from "./clean-poisoned-claude-sessions.js";
describe("classifyJsonlText", () => {
it("returns healthy when the last assistant message.id starts with msg_", () => {
const text = [
JSON.stringify({ type: "user" }),
JSON.stringify({ type: "assistant", message: { id: "msg_first" } }),
JSON.stringify({ type: "user" }),
JSON.stringify({ type: "assistant", message: { id: "msg_last" } }),
].join("\n");
const result = classifyJsonlText(text);
expect(result).toEqual({ kind: "healthy", lastAssistantId: "msg_last" });
});
it("returns poisoned when the last assistant message.id is a synthetic UUID", () => {
const text = [
JSON.stringify({ type: "user" }),
JSON.stringify({ type: "assistant", message: { id: "msg_real" } }),
JSON.stringify({
type: "assistant",
message: { id: "f649efd6-1837-4c52-981f-b81fdc0c2ddb" },
}),
].join("\n");
const result = classifyJsonlText(text);
expect(result).toEqual({
kind: "poisoned",
lastAssistantId: "f649efd6-1837-4c52-981f-b81fdc0c2ddb",
});
});
it("ignores trailing whitespace, blank lines, and malformed JSON", () => {
const text = [
"",
" ",
"this-is-not-json",
JSON.stringify({ type: "assistant", message: { id: "msg_only" } }),
"",
].join("\n");
expect(classifyJsonlText(text)).toEqual({
kind: "healthy",
lastAssistantId: "msg_only",
});
});
it("returns no_assistant_entries when the transcript has no assistant rows", () => {
const text = [
JSON.stringify({ type: "user" }),
JSON.stringify({ type: "attachment" }),
JSON.stringify({ type: "last-prompt", lastPrompt: "x" }),
].join("\n");
expect(classifyJsonlText(text)).toEqual({ kind: "no_assistant_entries" });
});
it("treats a CRLF-encoded transcript the same as LF", () => {
const text = [
JSON.stringify({ type: "assistant", message: { id: "msg_first" } }),
JSON.stringify({ type: "assistant", message: { id: "synthetic-uuid" } }),
].join("\r\n");
expect(classifyJsonlText(text)).toEqual({
kind: "poisoned",
lastAssistantId: "synthetic-uuid",
});
});
});
describe("encodeClaudeCwd", () => {
it("mirrors the claude-local adapter encoding rule", () => {
expect(encodeClaudeCwd("/Users/dj/.paperclip/instances/default/workspaces/abc")).toBe(
"-Users-dj--paperclip-instances-default-workspaces-abc",
);
});
});
describe("jsonlPathFor", () => {
it("returns <root>/projects/<encoded-cwd>/<sessionId>.jsonl", () => {
const result = jsonlPathFor({
claudeConfigDir: "/tmp/.claude",
cwd: "/Users/dj/work",
sessionId: "abc-123",
});
expect(result).toBe(path.join("/tmp/.claude", "projects", "-Users-dj-work", "abc-123.jsonl"));
});
});
describe("resolveClaudeConfigDir", () => {
it("prefers the explicit override", () => {
expect(resolveClaudeConfigDir({}, "/tmp/custom")).toBe(path.resolve("/tmp/custom"));
});
it("uses CLAUDE_CONFIG_DIR when no override is given", () => {
expect(resolveClaudeConfigDir({ CLAUDE_CONFIG_DIR: "/tmp/from-env" } as NodeJS.ProcessEnv)).toBe(
path.resolve("/tmp/from-env"),
);
});
it("falls back to ~/.claude when no override and no env var", () => {
const result = resolveClaudeConfigDir({} as NodeJS.ProcessEnv);
expect(result.endsWith(`${path.sep}.claude`)).toBe(true);
});
});
describe("classifyRow", () => {
const claudeConfigDir = "/tmp/.claude";
const cwd = "/Users/dj/work";
const sessionId = "session-1";
const expectedJsonl = jsonlPathFor({ claudeConfigDir, cwd, sessionId });
it("returns skipped_no_session_id when sessionId is null", () => {
const result = classifyRow(
{ sessionId: null, cwd, isRemote: false },
{ claudeConfigDir, readJsonl: () => null },
);
expect(result.kind).toBe("skipped_no_session_id");
});
it("returns skipped_remote when the row has remoteExecution params", () => {
const result = classifyRow(
{ sessionId, cwd, isRemote: true },
{ claudeConfigDir, readJsonl: () => null },
);
expect(result.kind).toBe("skipped_remote");
});
it("returns missing_jsonl with the expected path when the file does not exist", () => {
const result = classifyRow(
{ sessionId, cwd, isRemote: false },
{ claudeConfigDir, readJsonl: () => null },
);
expect(result.kind).toBe("missing_jsonl");
if (result.kind === "missing_jsonl") {
expect(result.jsonlPath).toBe(expectedJsonl);
}
});
it("flags rows whose JSONL last assistant id is non-msg_", () => {
const jsonl = [
JSON.stringify({ type: "assistant", message: { id: "msg_first" } }),
JSON.stringify({ type: "assistant", message: { id: "synthetic-uuid" } }),
].join("\n");
const result = classifyRow(
{ sessionId, cwd, isRemote: false },
{ claudeConfigDir, readJsonl: () => jsonl },
);
expect(result.kind).toBe("poisoned");
if (result.kind === "poisoned") {
expect(result.lastAssistantId).toBe("synthetic-uuid");
}
});
it("leaves valid msg_-prefixed sessions classified as healthy", () => {
const jsonl = [
JSON.stringify({ type: "assistant", message: { id: "msg_only" } }),
].join("\n");
const result = classifyRow(
{ sessionId, cwd, isRemote: false },
{ claudeConfigDir, readJsonl: () => jsonl },
);
expect(result.kind).toBe("healthy");
});
});