Skip to content

fix(sources): classify Claude Code message_type from TEXT blocks only - #3525

Merged
Sinity merged 4 commits into
masterfrom
fix/parsers/claude-code-message-type-text-blocks-only
Aug 1, 2026
Merged

Sinity merged 4 commits into
masterfrom
fix/parsers/claude-code-message-type-text-blocks-only

Conversation

@Sinity

@Sinity Sinity commented Aug 1, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes a genuine ingest-time/backfill-time classification divergence in the Claude Code parser that was silently producing new message_type drift on every ingest, discovered via bd polylogue-c831's live-archive scan (1,919 candidate rows).

Problem

storage/message_type_backfill.py's _message_text_by_id_sql() reconstructs a message's classify_text_message_type input from only persisted TEXT-type blocks rows (message_prose_sql(block_types=("text",))), deliberately excluding thinking/tool_use/tool_result content.

The Claude Code ingest path built a different, wider input for the same classifier call: extract_message_text/extract_text_from_segments (polylogue/sources/parsers/claude/common.py) folds THINKING (wrapped <thinking>...</thinking>) and TOOL_USE/TOOL_RESULT (JSON-dumped) segment content into one combined string — even though those segments are split into their own separate ParsedContentBlock rows before persistence via content_blocks_from_segments.

Whenever a THINKING/TOOL_USE segment happened to contain a classifier marker (e.g. a <file path= line) that the message's own TEXT block did not carry, ingest-time classification and a later backfill re-run over the persisted TEXT-only blocks silently disagreed. This is a real code-path divergence, not a dated classifier-semantics change — I checked git log on polylogue/archive/message/artifacts.py and there's no post-materialization semantic change that would explain the drift; the two paths have simply always used different reconstructions of "text". Codex (extract_codex_text pulls only text/input_text/output_text fields) and ChatGPT parsers were checked and do not exhibit this pattern.

Solution

  • Added text_blocks_prose() (polylogue/sources/parsers/base_support.py, re-exported via base.py) — the parse-time twin of message_prose_sql(block_types=("text",)): joins only TEXT-type block text, in position order, with \n.
  • Changed code_parser.py's _message_type_from_code_record call site to classify from text_blocks_prose(content_blocks) (the message's own already-split TEXT blocks) instead of the combined extract_message_text string.
  • Added a regression test (tests/unit/sources/test_parsers_claude_code_artifacts.py::test_parse_code_classifies_message_type_from_text_blocks_only) with a THINKING block carrying a <file path= marker plus a plain TEXT reply block. Verified by temporarily reverting the fix: the test fails (MessageType.CONTEXT != MessageType.MESSAGE) without it, and passes with it.

Explicitly not in scope:

  • classify_material_origin's text=text argument in code_parser.py still receives the combined multi-segment string, which has the same latent-divergence shape for OPERATOR_COMMAND/GENERATED_*_PACK markers. Left unchanged since the bead's 1,919-row evidence scan was message_type-specific, not material_origin-specific.
  • Retiring the manual message_type_backfill maintenance target. The 1,919 already-materialized rows still need one operational backfill run (or the pending polylogue ops reset --index && polylogued run reindex) to converge; this PR only stops new drift from accumulating on future Claude Code ingests.

Verification

  • devtools test tests/unit/sources/test_parsers_claude_code_artifacts.py — 30 passed (including the new regression test).
  • devtools test tests/unit/sources/ tests/unit/pipeline/test_message_type_backfill.py — 2222 passed; 7 failures reproduced identically via git stash on the pre-change tree (pre-existing/unrelated, none touching code_parser.py/base_support.py/base.py).
  • devtools verify --quick — format + lint + mypy + render-all-check + layering + lab policies, exit_code: 0 (also ran again automatically via the pre-push hook).

Ref polylogue-c831

Summary by CodeRabbit

  • Bug Fixes

    • Improved Claude Code message classification by evaluating visible text content only, excluding thinking and tool-related content.
    • Prevented messages from being incorrectly categorized based on hidden processing content.
  • Tests

    • Added coverage to verify classification remains accurate when thinking content includes misleading context markers.

Sinity and others added 2 commits August 1, 2026 19:26
Problem: a live-archive scan (bd polylogue-c831) found 1,919 message_type='message'
rows that storage/message_type_backfill.py's classifier would reclassify to
context/protocol if re-run today, even though ingest is supposed to be the
single source of truth for message_type. That backfill reconstructs a
message's classification input from only persisted TEXT-type `blocks` rows
(message_prose_sql(block_types=("text",))), deliberately excluding
thinking/tool_use/tool_result content.

The Claude Code ingest path built a different, wider input for the same
classifier: extract_message_text/extract_text_from_segments folds
THINKING (wrapped `<thinking>...</thinking>`) and TOOL_USE/TOOL_RESULT
(JSON-dumped) segment content into one combined string, even though those
segments are split into their own separate ParsedContentBlock rows before
being persisted. Whenever a THINKING/TOOL_USE segment happened to contain
a classifier marker (e.g. a `<file path=` line) that the message's own
TEXT block did not carry, ingest-time classification and a later backfill
re-run over the persisted TEXT-only blocks silently disagreed -- a real
code-path divergence, not a dated classifier-semantics change (Codex and
ChatGPT parsers were checked and do not exhibit this pattern).

Solution: add `text_blocks_prose()` (polylogue/sources/parsers/base_support.py,
re-exported via base.py) as the parse-time twin of
`message_prose_sql(block_types=("text",))`, and change
code_parser.py's `_message_type_from_code_record` call site to classify
from `text_blocks_prose(content_blocks)` -- the message's own
already-split TEXT blocks -- instead of the combined
`extract_message_text` string. Added a regression test with a THINKING
block carrying a `<file path=` marker plus a plain TEXT reply; verified
it fails (misclassifies CONTEXT) without the fix and passes with it.

Not in scope: `classify_material_origin`'s `text=text` argument in
code_parser.py still receives the combined string (same latent-divergence
shape), left unchanged since the bead's evidence was message_type-specific.
Also not in scope: retiring the manual `message_type_backfill` maintenance
target -- the 1,919 already-materialized rows still need one operational
backfill run to converge; this only stops new drift from accumulating.

Verification: devtools test tests/unit/sources/test_parsers_claude_code_artifacts.py
(30 passed, including the new regression test -- confirmed it fails
without the fix); devtools test tests/unit/sources/ tests/unit/pipeline/test_message_type_backfill.py
(2222 passed, 7 pre-existing/unrelated failures reproduced identically on
master via git stash, none touching code_parser.py/base_support.py/base.py);
devtools verify --quick (format+lint+mypy+render-all-check+layering+lab
policies, exit 0).

Ref polylogue-c831

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 43 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: c98414cf-dde9-4c2a-a1e2-4a40374db568

📥 Commits

Reviewing files that changed from the base of the PR and between e336e19 and d1c08a3.

📒 Files selected for processing (3)
  • .beads/issues.jsonl
  • polylogue/storage/embeddings/materialization.py
  • tests/unit/pipeline/test_message_type_backfill.py
📝 Walkthrough

Walkthrough

The parser now classifies Claude Code messages from persisted TEXT blocks only. A shared prose-extraction helper is exported, regression coverage excludes THINKING content, and investigation records document related findings.

Changes

Claude message classification

Layer / File(s) Summary
TEXT-block prose extraction
polylogue/sources/parsers/base_support.py, polylogue/sources/parsers/base.py
Added and exported text_blocks_prose, which joins non-empty TEXT blocks and returns None when no prose exists.
Claude classification and regression coverage
polylogue/sources/parsers/claude/code_parser.py, tests/unit/sources/test_parsers_claude_code_artifacts.py, .beads/issues.jsonl
Claude Code classification now uses TEXT-block prose. The regression test confirms THINKING content does not affect classification. Investigation records document related findings.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: Claude Code message_type classification now uses TEXT blocks only.
Description check ✅ Passed The description covers the problem, solution, verification commands, scope boundaries, risks, and follow-ups in the required structure.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/parsers/claude-code-message-type-text-blocks-only

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Ref polylogue-c831

Co-Authored-By: Claude <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e336e19b9f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Problem: message_prose_sql wrapped GROUP_CONCAT around a correlated
scalar subquery. Every real caller LEFT JOINs blocks to filter/order by
block columns, fanning a multi-TEXT-block message out into one outer
row per block; the scalar subquery was evaluated once per fanned-out
row and returned the same single (first) block's text every time, so
GROUP_CONCAT never saw the other blocks. Flagged by the CodeRabbit-
equivalent bot review on PR #3525 as a P2 finding that undermines this
PR's own goal of eliminating ingest/backfill classification drift for
multi-block messages.

Solution: make message_prose_sql self-contained -- GROUP_CONCAT now
runs inside its own scalar subquery, over a pre-sorted derived table,
so it produces the correct concatenation independent of how the outer
query joins/groups.

Verification: new regression test proves the previous behavior
(git-stash-verified to fail: returned "first block" instead of "first
block\nsecond block"); tests/unit/pipeline/test_message_type_backfill.py
tests/unit/storage/test_embedding_contracts.py tests/unit/storage/test_embedding_dedup.py
tests/unit/cli/test_embed.py tests/unit/sources/test_parsers_claude_code_artifacts.py
tests/unit/demo/ (145 passed); devtools verify --quick (exit 0).

Co-Authored-By: Claude <[email protected]>
@Sinity

Sinity commented Aug 1, 2026

Copy link
Copy Markdown
Owner Author

Fixed in d1c08a3: message_prose_sql now runs its own GROUP_CONCAT inside a self-contained scalar subquery over a pre-sorted derived table, instead of wrapping GROUP_CONCAT around a correlated scalar subquery that every real caller's LEFT JOIN blocks fanned out into one row per block (so the scalar only ever returned the first TEXT block). New regression test confirmed to fail on the unmodified code and pass with the fix.

@Sinity
Sinity merged commit 2b91fea into master Aug 1, 2026
3 checks passed
@Sinity
Sinity deleted the fix/parsers/claude-code-message-type-text-blocks-only branch August 1, 2026 18:00
Sinity added a commit that referenced this pull request Aug 3, 2026
…3629)

## Summary

Regresses bd polylogue-c831's classification-drift bug shape with a
fixture, and completes the bead's remaining operational scope by running
the actual production backfill against the live archive.

## Problem

polylogue-c831's original evidence: a read-only scan against the live
`index.db` found 1,919 rows still persisted as `message_type='message'`
that the current classifier would flip to `context`/`protocol` -- a
divergence between ingest-time classification and the backfill's own
re-derivation.

The root cause was found and fixed in PR #3525 (merged):
`classify_text_message_type` matches most markers with an anchored
`str.startswith` check, but pre-#3525 Claude Code ingest classified from
a *combined* THINKING+TOOL_RESULT+TEXT string. A marker that starts a
message's own TEXT block does not start the combined string once
non-empty THINKING/TOOL_RESULT segments are concatenated ahead of it, so
the anchored check silently misses it at ingest time. That PR stopped
new drift from accumulating but explicitly left two things open: a
regression test for the backfill side of the divergence, and the
operational backfill run over the already-materialized drifted rows.

## Solution

- Added
`test_backfill_reclassifies_drifted_row_ignoring_other_block_types`
(`tests/unit/pipeline/test_message_type_backfill.py`) with a new fixture
(`_make_db_with_drifted_mixed_block_message`) that reproduces the exact
drift shape directly: a `message_type='message'` row whose persisted
TEXT block alone starts with a protocol marker (`<bash-input>`),
alongside marker-free THINKING/TOOL_RESULT blocks, asserting the
backfill flips it to `protocol` from the TEXT block content alone --
proving the existing `message_type_backfill` machinery
(`storage/message_type_backfill.py`, unchanged by this PR) correctly
converges this class of drifted row regardless of other block types on
the message.
- Confirmed the live candidate count with the production
`count_unclassified_message_type_sync` function (not a
reimplementation): 1,901 candidates as of 2026-08-03 (down slightly from
the bead's original 1,919, consistent with #3525 having stopped new
accumulation and ordinary archive churn since).
- Ran the actual production backfill against the live archive
(`/realm/db/polylogue/index.db`) using the existing, unmodified
`_backfill_pass`/`count_messages_by_type_sync` functions, opened via the
production `open_connection` helper (the same code path `polylogue
doctor --repair --target message_type_backfill` exercises). This only
touches the `messages.message_type` column on the `index.db` tier, which
is the rebuildable-by-design tier in the five-tier durability model --
no durable-tier or DDL change involved.
- Before: `message=1,230,456, context=19,600, protocol=40,245` (1,901
candidates)
  - Updated: 1,901 rows
- After: `message=1,228,555, context=19,603, protocol=42,143` (0
candidates)
  - Re-confirmed 0 candidates in a fresh read-only pass after the write.
- No change to `polylogue/` production code in this PR -- the
classifier/backfill logic was already correct (delivered by #3525); this
PR is the test-coverage + operational-convergence half of the bead's
remaining scope.

## Verification

- `devtools test tests/unit/pipeline/test_message_type_backfill.py` -- 8
passed (7 pre-existing + 1 new).
- `devtools verify --quick` -- exit 0, 23/23 steps green, on the rebased
branch.
- Live production backfill apply + before/after/re-confirm counts as
above (`polylogued` daemon remained healthy throughout; its
pre-existing, unrelated schema-version health warning --
`source.db:20!=18, index.db:46!=56`, part of the separate in-flight
differential-reindex program -- was unchanged before and after this
write).

## Scope notes

Ref polylogue-c831. Not addressed here (out of scope, no evidence of
drift found): `classify_material_origin`'s combined-text argument in
`code_parser.py` has the same latent divergence shape for
OPERATOR_COMMAND/GENERATED_*_PACK markers, per PR #3525's own notes -- a
follow-up would need its own drift measurement first.
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 71.F085 / P2: fixed-already at the checked revision: message_prose_sql now aggregates inside a scalar subquery over the complete ordered block relation. polylogue/storage/embeddings/materialization.py:252 performs GROUP_CONCAT over prose_block, whose rows are ordered by block position at line 259, so a marker in the second TEXT block is not replaced by repeated copies of the first block.

Only the rows listed above are dispositioned. Held findings remain open.

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