Skip to content

fix(digest): make outlier sessions digestible + stop the pipeline digesting itself - #65

Open
anand-jha-veho wants to merge 3 commits into
mustafa-bharmal-shipveho:mainfrom
anand-jha-veho:main
Open

anand-jha-veho wants to merge 3 commits into
mustafa-bharmal-shipveho:mainfrom
anand-jha-veho:main

Conversation

@anand-jha-veho

@anand-jha-veho anand-jha-veho commented Jul 30, 2026 •

Copy link
Copy Markdown

Three related fixes for the session-digest pipeline. Each was found by the previous one turning out to be insufficient; the comment below has the full investigation trail.

1. Env-overridable per-call timeout

timeout_s=180 was hardcoded; now LLM_TIMEOUT_S = int(os.getenv("DIGEST_LLM_TIMEOUT_S", "180")), applied to all three provider calls (single-pass, per-chunk, merge). In a backfill over 20 sessions, 3 failed with LLM FAIL: claude -p timeout after 180s; 2 of the 3 digest successfully at 900s.

2. Splitting oversized messages

_chunk_messages never split inside a message, so a single huge message became a chunk exceeding the model's input budget — the provider rejected the call before inference (is_error: true, zero token usage). No timeout fixes this. Real case: a 145,357-token (581KB) message inside a 138MB / 4.5M-token session — the 3rd failing session, which the timeout raise alone did not rescue.

  • _split_oversized() slices any message over the chunk target into labeled parts, falling back to the original if it isn't a copyable dataclass.
  • DIGEST_CHUNK_TOKEN_TARGET overrides the derived chunk target, which is pinned to 30K in production by min(CHUNK_TOKEN_TARGET, SINGLE_PASS_TOKEN_LIMIT // 2) despite the 120K constant (see comment).

3. The pipeline was digesting its own LLM calls

Internal claude -p calls persisted transcripts into ~/.claude/projects/, which the next backfill digested — self-reinforcing. One backfill wrote 238 self-transcripts and grew a brain 80 → 121 digests, nearly all noise. Classifying by source_path: 115 of 130 sidecar entries were self-generated. Titles look genuine because a chunk-digest call's content is the user's real transcript.

  • Provider passes --no-session-persistence — internal calls write no transcript (source fix).
  • _is_self_generated() filters pre-existing ones by the SYSTEM:\n…\n\nUSER:\n envelope on the first user turn.

Verification

Before After
Largest chunk (138MB session) 145,357 tok 100,008 tok (100K target; the 8 is per-message rounding)
Chunk count 165 49
Content integrity — 17,956,236 → 17,956,416 chars — delta is exactly the part markers
Self-transcripts written per run 52 (measured) 0 (measured on a live run)
Self-generated digests in brain 115 of 130 0 of 16
  • Filter on 376 local transcripts: 362 filtered, 14 kept, every known real session preserved; borderline files inspected individually.
  • Tests: 38/38 digest suites, 32/32 test_migrate_dispatcher.py (fix 3 also clears its long-standing real-data failure). Full suite at the time of fix 2: 1743 passed, with 2 pre-existing MCP SDK failures that reproduce on a clean checkout.
  • Defaults unchanged: with both env vars unset the values are byte-identical to the previous literals.

Out of scope

Adaptive/per-call timeouts and retry-with-backoff. Also flagged but not changed: internal calls still allow auto-memory writes — a sub-Claude wrote a real digest into ~/.claude/projects/<slug>/memory/digests/ where nothing reads it (details in the comment).

🤖 Generated with Claude Code

anand-jha-veho and others added 2 commits July 30, 2026 22:19
…IMEOUT_S)

Large sessions (100MB+ transcripts) exceeded the hardcoded 180s claude -p
timeout even after chunking, failing 3 of 20 sessions during a laptop-
migration backfill. Default stays 180s; override per run, e.g.:

    DIGEST_LLM_TIMEOUT_S=900 digest_cli.py backfill --source claude

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…sted

_chunk_messages never split inside a message, so a single huge message
became a chunk larger than the model's input budget. The provider then
rejected the call outright — `claude -p` returned is_error with zero token
usage — which no timeout increase can fix. Real case: a 145K-token (581KB)
tool result inside a 138MB / 4.5M-token session.

- _split_oversized() slices any message exceeding the chunk target into
  labeled parts; falls back to the original message if it isn't a copyable
  dataclass, so unexpected types degrade instead of raising.
- DIGEST_CHUNK_TOKEN_TARGET overrides the derived chunk target. The
  documented 120K target was unreachable in production because
  min(CHUNK_TOKEN_TARGET, SINGLE_PASS_TOKEN_LIMIT // 2) pins it to 30K —
  the very "hours of wall time" problem the 120K constant was raised to
  avoid. Unset keeps the derived value, so default and test behavior are
  unchanged.

Verified on the 138MB session: largest chunk 145,357 → 100,008 tokens,
chunk count 165 → 49, and no content lost (17,956,236 → 17,956,416 chars,
delta = part markers only). Full suite: 1743 passed, 3 pre-existing
failures that reproduce identically on a clean checkout (2 MCP SDK API
drift, 1 real-data dispatcher check).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@anand-jha-veho anand-jha-veho changed the title feat(digest): make per-call LLM timeout env-overridable (DIGEST_LLM_TIMEOUT_S) fix(digest): make outlier sessions digestible (timeout + oversized-message chunking) Jul 30, 2026
@anand-jha-veho

anand-jha-veho commented Jul 30, 2026 •

Copy link
Copy Markdown
Author

Follow-up: pushed two more commits. The timeout raise turned out to be necessary but not sufficient, and investigating why surfaced a second, larger problem.

(Edited: I first reported the self-digestion scale as "12 of 80 digests" based on title matching. That was wrong — classifying by source_path shows 115 of 130. Corrected throughout below, and it is now fixed in this PR rather than filed as an observation.)

The timeout raise was necessary but not sufficient

Re-running the 3 previously-failing sessions at DIGEST_LLM_TIMEOUT_S=900: 2 recovered, but the largest (138MB, 4.5M est. tokens, 17,999 messages) failed with a different error — claude -p exit=1, is_error: true, zero token usage, stop_reason: stop_sequence. Rejected before inference began, so no timeout value reaches it.

Measuring the normalized session found the cause: one message estimates at 145,357 tokens (581KB), and _chunk_messages never splits inside a message, so that chunk alone exceeded the input budget. Hence _split_oversized().

The documented 120K chunk target is unreachable in production

chunk_target = min(CHUNK_TOKEN_TARGET, max(1, SINGLE_PASS_TOKEN_LIMIT // 2))

With CHUNK_TOKEN_TARGET = 120_000 and SINGLE_PASS_TOKEN_LIMIT = 60_000 this always yields 30K, so the constant's own comment ("Originally 30K, which made the 14MB outlier need ~120 chunks → cumulative wall time hours") describes behavior still in effect: 165 chunks at 30K vs 49 at 100K for this session.

I added DIGEST_CHUNK_TOKEN_TARGET as an override rather than touching the min(), since the derived value looks deliberate for tests that monkeypatch SINGLE_PASS_TOKEN_LIMIT lower. Happy to drop the env var and fix the min() directly if you'd prefer — that's a call on intent, which is yours.

The pipeline was digesting its own LLM calls

Every internal claude -p call persisted a transcript into ~/.claude/projects/, which the next backfill discovered and digested. Self-reinforcing: one backfill wrote 238 self-transcripts and grew this brain 80 → 121 digests with ~none of the growth being real sessions.

It is hard to see by eye, which is why my first estimate was 10x low. A chunk-digest call's content is the user's real transcript, so the digests get plausible titles — "wire cerbos shadow descriptors 6 domains", "fix CI snapshot failures from macOS esbuild platform variance" — and only the obvious query-expansion ones look synthetic. Classifying by source_path instead of title: 115 of 130 sidecar entries were self-generated, including 6 transcripts restored from an old machine that were never real sessions.

Two-layer fix:

  • Source: the provider now passes --no-session-persistence, so internal calls write no transcript. Verified on a live run — zero new transcripts, versus 52 in the previous run.
  • Existing data: _is_self_generated() filters transcripts already on disk, keyed on the SYSTEM:\n…\n\nUSER:\n envelope as the first user turn. Two earlier signatures failed and were discarded rather than assumed correct: startswith("Session id: ") matched 0 (the envelope wraps it), and requiring a single user turn matched 5 (schema-enforced calls add structured-output turns).

On 376 local transcripts: 362 filtered, 14 kept, every known real session preserved (145MB session plus 13 others); each borderline file inspected individually.

Side effects worth knowing

  • tests/test_migrate_dispatcher.py::test_real_data_dry_run_all_claude_dirs was failing on NoAdapterError for a memory/ subdir inside one of those self-created project dirs. Root cause: a sub-Claude's auto-memory wrote a real digest into ~/.claude/projects/<slug>/memory/digests/, where nothing reads it. Recovered it to the brain and the test now passes 32/32. Worth considering whether internal calls should run with auto-memory disabled too — --no-session-persistence stops transcripts but evidently not memory writes.
  • Purging on my side removed 115 digests across all three stores (markdown, _imported.jsonl, AGENT_LEARNINGS.jsonl), matched by source_path. Recall quality is unchanged afterward.

🤖 Generated with Claude Code

Every internal `claude -p` call persisted a transcript into
~/.claude/projects/, which the next backfill then discovered and digested.
The brain filled with digests of its own digest calls, and each run made
the next one worse: one backfill wrote 238 self-transcripts and grew this
brain from 80 to 121 digests with ~none of the growth being real sessions.

The noise is hard to spot by eye because a chunk-digest call's *content* is
the user's real transcript, so the resulting digests carry plausible titles
like "wire cerbos shadow descriptors 6 domains" rather than anything
obviously machine-generated. Classifying by source_path found 115 of 130
sidecar entries were self-generated.

- claude_code provider passes --no-session-persistence, so internal calls
  write no transcript at all. Fixes it at the source.
- _is_self_generated() filters transcripts already on disk from before
  that, keyed on the `SYSTEM:\n...\n\nUSER:\n` envelope appearing as the
  first user turn. Detection is by prompt shape, not project directory:
  calls inherit the runner's cwd, which may also hold real sessions, and
  the digests themselves look genuine. Later turns are not required to
  match — schema-enforced calls add structured-output turns, so these are
  not single-turn despite being one-shot runs.

Verified on 376 local transcripts: 362 filtered, 14 kept, with every known
real session preserved (a 145MB session plus 13 others). Each flagged
borderline file was inspected individually; e.g. one 24KB "session" was a
query-expansion call. Tests: 32/32 in test_migrate_dispatcher.py (this also
clears its real-data check), 38/38 across the digest suites.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@anand-jha-veho anand-jha-veho changed the title fix(digest): make outlier sessions digestible (timeout + oversized-message chunking) fix(digest): make outlier sessions digestible + stop the pipeline digesting itself Jul 30, 2026
@anand-jha-veho

Copy link
Copy Markdown
Author

Final verification: the 138MB session now digests successfully

The session that motivated this PR — 138MB, 4.5M est. tokens, 17,999 messages, which failed first on the 180s timeout and then on the oversized-message rejection — completed in ~9 minutes:

discovered: 14    written: 3    skipped (sha): 11    failed: 0

Output is a well-formed 5.4KB digest (salience: 9, correct domain tags, started_at → ended_at spanning the full two-month arc of the session) and recall returns it as the 1.0 top hit for its topic.

Before/after on the same machine and the same data:

Before After
Largest session 2h25m grinding → hard failure ~9 min, success
Backfill result 19/20 sessions, 1 permanent failure 14/14 real sessions, 0 failures
Self-transcripts written per run 52 in the first 25 min 0
Brain composition 115 of 130 digests self-generated 0 of 19

Two notes for anyone reading the numbers:

  • The discovery count dropping from 20 to 14 is not lost data. Six of the original "sessions" were internal LLM calls (restored from an old machine alongside real transcripts), which fix 3 now correctly excludes. Every genuine session is still digested.
  • The sidecar correctly detected changed sessions. Two transcripts were resumed and extended between runs, and the content-SHA check re-digested the one whose digest was stale rather than skipping it.

Both open questions from the earlier comment still stand and are yours to decide: whether to drop DIGEST_CHUNK_TOKEN_TARGET in favor of fixing the min() directly, and whether internal calls should disable auto-memory as well as session persistence.

🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant