Skip to content

fix: prevent silent raw materialization gaps - #2321

Merged
Sinity merged 3 commits into
masterfrom
feature/feat/workflow-control-plane-batch
Jun 23, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/feat/workflow-control-plane-batch

Conversation

@Sinity

@Sinity Sinity commented Jun 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

This PR turns the acquired-but-not-materialized raw-session failure mode into an explicit ingest invariant. JSONL stream detection now handles drive-cache filenames such as *.jsonl.txt.json, session artifacts that parse to zero sessions are quarantined instead of stamped clean, reparse removes stale same-raw sessions in the same batch transaction, and raw-materialization debt recognizes duplicate raw aliases whose source filenames encode an already-materialized native session id.

Problem

Live archive evidence showed raw acquisition could be marked clean while user-visible sessions/messages were absent or wrong. The concrete production case was AI Studio Drive cache files that were actually Claude Code JSONL streams behind a trailing .json suffix; they had materialized as zero-message aistudio-drive:* sessions instead of real Claude Code sessions. Treating this as manual repair would leave the same class of bug available to recur.

Solution

  • Route embedded .jsonl. / .ndjson. filenames through the stream parser in both the ingest worker and shared JSON decoder.
  • Reject session parser outputs that contain zero sessions, so raw rows cannot become parse-success/no-session artifacts silently.
  • Delete stale sessions for the same raw_id before writing replacement parse results, inside the ingest batch transaction.
  • Suppress raw-materialization debt for parsed duplicate aliases whose source filename maps to an existing native session for the same origin, including split suffixes such as _1.
  • Count detection-warning-only raw-state updates as real updates.

Live production replay with this source tree:

  • Replayed 15 affected AI Studio JSONL-cache raw rows.
  • Wrote 15 changed sessions and 6,418 messages with 0 parse failures.
  • Replayed one missing ac49922f... raw row and restored 782 messages.
  • Source-tree raw-materialization debt after replay: 0 rows.
  • FTS coverage after replay: messages_fts_docsize=3,987,982, indexable blocks 3,987,982.

Verification

Focused tests:

devtools test \
  tests/unit/operations/test_archive_debt.py::test_archive_debt_raw_materialization_ignores_source_path_native_aliases \
  tests/unit/operations/test_archive_debt.py::test_archive_debt_raw_materialization_ignores_native_id_matches \
  tests/unit/pipeline/test_ingest_batch.py::test_process_ingest_batch_sync_replaces_stale_sessions_for_same_raw_id \
  tests/unit/pipeline/test_ingest_batch.py::test_persist_batch_raw_state_updates_uses_one_typed_update_per_raw \
  tests/unit/pipeline/test_resilience.py::test_jsonl_stream_shape_beats_drive_cache_json_suffix \
  tests/unit/pipeline/test_resilience.py::test_ingest_worker_quarantines_session_artifact_with_no_sessions
# 6 passed

Static/generated quick gate:

devtools verify --quick
# ruff format/check, mypy, render all, topology, layering, closure-matrix,
# schema roundtrip, manifests, ci-workflows, doc-commands,
# test-infra-currency, test-clock-hygiene all ok

Push hook reran devtools verify --quick at 33c998c57 and passed.

Default devtools verify was not run because this fresh worktree has no pytest-testmon seed and the command exits with guidance to run devtools verify --seed-testmon first.

Follow-up

Targeted replay performance is not acceptable: a 2.2 MiB / 782-message single-row replay spent ~459s in commit/FTS work. That is now live-measured evidence for the dogfooding performance lane.

Ref #2308

Summary by CodeRabbit

  • Improvements

    • Session deduplication now automatically removes outdated entries when processing updated batches
    • JSONL file format detection improved to recognize additional naming patterns beyond standard extensions
    • Raw-materialization debt tracking now correctly handles native-alias source path mappings
  • Bug Fixes

    • Added error handling for parse operations that produce no materializable sessions

Raw session artifacts that parse to no sessions now quarantine instead of being stamped as clean, and JSONL stream detection handles drive-cache names such as *.jsonl.txt.json through both the worker and shared decoder paths. Reparse also removes stale sessions for the same raw_id inside the batch transaction so provider redetection does not leave ghost rows.\n\nRaw-materialization debt now recognizes duplicate parsed aliases when the source filename encodes a native session id already materialized for the same origin, including split suffixes like _1. Detection warnings also count as explicit raw-state updates.\n\nVerified with focused pipeline/debt tests and devtools verify --quick. Live production replay materialized 15 affected AI Studio JSONL-cache rows into 6,418 messages and restored FTS exact coverage.\n\nRef #2308
@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

More reviews will be available in 48 minutes and 41 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

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 credits.

🚦 How do rate limits work?

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

For paid Pro and Pro+ PR reviews, CodeRabbit uses rolling per-developer review limits. Reviews become available again as older review attempts age out of the rolling limit window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e960166b-a87e-4610-af7f-41faac7c64d1

📥 Commits

Reviewing files that changed from the base of the PR and between 33c998c and 75d0c89.

📒 Files selected for processing (6)
  • polylogue/operations/archive_debt.py
  • polylogue/pipeline/services/ingest_batch/_core.py
  • polylogue/storage/repository/raw/repository_raw.py
  • tests/unit/operations/test_archive_debt.py
  • tests/unit/pipeline/test_ingest_batch.py
  • tests/unit/storage/test_repository_insight_runtime.py
📝 Walkthrough

Walkthrough

The PR makes three ingestion-pipeline correctness changes: JSONL/NDJSON source-path detection is broadened to match embedded markers (not just suffixes) in both decoder_json.py and ingest_worker.py; _materialize_parsed_sessions short-circuits on empty session lists; _drain_ready_session_entries deletes stale sessions before writing; and archive_debt now filters out debt rows whose source_path filename resolves to an already-materialized native-ID alias.

Changes

Ingestion Pipeline Correctness

Layer / File(s) Summary
JSONL detection broadening and empty-sessions guard
polylogue/sources/decoder_json.py, polylogue/pipeline/services/ingest_worker.py, polylogue/storage/raw/models.py, tests/unit/pipeline/test_resilience.py
JSONL/NDJSON routing in iter_json_stream_with and _is_jsonl_source_path now also matches paths containing .jsonl. or .ndjson. anywhere after lowercasing. _materialize_parsed_sessions returns a parse-error result when parsed_sessions is empty. detection_warnings is added to RawSessionStateUpdate.has_values. Tests cover trailing-suffix JSONL ingestion, dispatch success assertions, and the no-sessions quarantine path.
Pre-write stale session deletion per raw_id
polylogue/pipeline/services/ingest_batch/_core.py, tests/unit/pipeline/test_ingest_batch.py
New _delete_stale_sessions_for_raw_entries helper issues DELETE FROM sessions WHERE raw_id = ? AND session_id NOT IN (...) for each raw_id in the incoming batch before the write loop. _drain_ready_session_entries calls this cleanup first. Test seeds a stale session, runs _process_ingest_batch_sync with force_write=True, and asserts only the replacement session remains.
Archive debt native-ID alias filtering
polylogue/operations/archive_debt.py, tests/unit/operations/test_archive_debt.py
Two new helpers infer candidate native_id values from a row's source_path stem (stripping extensions and trailing _digits patterns) and query index_tier.sessions to detect existing materialization. SQL query output is now captured as candidate_rows and filtered through this check to produce missing_rows. Test asserts no debt is raised for an alias-matched session while an unrelated codex-session blob debt remains.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

type:test, area:pipeline, area:parser

Poem

🐇 A rabbit once filed debts by name,
But aliases had muddled the game.
Now stems get stripped, suffixes checked,
And stale session rows get correctly wrecked—
The JSONL path glows wide and bright,
No empty parse slips through the night! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: prevent silent raw materialization gaps' accurately and concisely summarizes the main objective of the PR, which is to address silent failures in raw session materialization.
Description check ✅ Passed The description comprehensively covers all required template sections: Summary, Problem, Solution (with detailed implementation details), Verification (with specific test commands and results), Changelog (appropriately marked as needing CHANGELOG.md update), and Follow-ups (identifying performance concerns).
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/workflow-control-plane-batch

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.

@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: 33c998c57f

ℹ️ 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".

Comment thread polylogue/operations/archive_debt.py Resolved
Sinity added 2 commits June 23, 2026 09:08
Problem: the acquisition cursor writer persisted source stat fields into ops.db.ingest_cursor, but RepositoryRawMixin still queried the removed live_cursor table and swallowed the failure. That made known_cursors empty and allowed restart catch-up to keep touching unchanged large source files.

What changed: route get_known_source_cursors through the shared cursor query helper so the reader consumes the same ingest_cursor ledger as the writer. Extend the repository mixin regression test to assert the cursor query is forwarded.

Verification: devtools test tests/unit/storage/test_repository_insight_runtime.py::test_repository_raw_forwards_query_and_mutation_calls tests/unit/storage/test_archive_tiers_ops_write.py::test_ops_upsert_ingest_cursor_updates_single_row tests/unit/sources/test_live_watcher.py::test_cursor_creates_table_if_missing; devtools verify --quick.
Problem: review found two invariant gaps in the raw-materialization replay patch. Source-path alias suppression could hide parse/blob failures, and stale same-raw session deletion could leave child rows behind when bulk ingest has foreign keys disabled.

What changed: limit source-path alias suppression to clean parsed-without-session duplicates. When removing stale same-raw sessions, derive session FK actions from SQLite and manually apply CASCADE/SET NULL semantics before deleting the session row.

Verification: devtools test tests/unit/operations/test_archive_debt.py::test_archive_debt_source_path_aliases_do_not_hide_parse_failures tests/unit/pipeline/test_ingest_batch.py::test_process_ingest_batch_sync_replaces_stale_sessions_for_same_raw_id; devtools verify --quick.
@Sinity

Sinity commented Jun 23, 2026

Copy link
Copy Markdown
Owner Author

Addressed the two Codex inline findings in commit 75d0c89:\n\n- Alias suppression is now limited to clean parsed-without-session duplicate rows; parse failures, missing blobs, and pending parses remain visible debt. Added test: tests/unit/operations/test_archive_debt.py::test_archive_debt_source_path_aliases_do_not_hide_parse_failures.\n- Stale same-raw session deletion now manually applies the schema's sessions FK actions while bulk ingest has FK enforcement suspended. Added child-row coverage and PRAGMA foreign_key_check assertion in tests/unit/pipeline/test_ingest_batch.py::test_process_ingest_batch_sync_replaces_stale_sessions_for_same_raw_id.\n\nVerification after the fixes:\n- devtools test tests/unit/operations/test_archive_debt.py::test_archive_debt_source_path_aliases_do_not_hide_parse_failures tests/unit/pipeline/test_ingest_batch.py::test_process_ingest_batch_sync_replaces_stale_sessions_for_same_raw_id\n- devtools verify --quick

@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.

  • 69.F051 / P2: fixed-already at the checked revision: polylogue/operations/archive_debt.py:284-289 excludes non-retryable parse errors from alias reconciliation. Even an aliasable missing-blob case remains reported as RAW_ALIAS_BLOB_MISSING_CATEGORY at lines 295-299 instead of disappearing behind a matching native/source-path session.
  • 69.F093 / P2: fixed-already at the checked revision: polylogue/pipeline/services/ingest_batch/_core.py:2301 invokes _delete_sessions_without_fk_cascade before removing the stale session row. Its helper applies dependent delete and SET NULL actions explicitly, including compound message-owned children, so disabled foreign keys do not leave the cited stale subtree behind.

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