Repository navigation
fix(live): eliminate read storm by trusting cursor on mtime drift (#1003 follow-on) - #1010
Conversation
Adds a read-counter infrastructure and three scenarios that pin the steady-state contract for the live ingest path: - ``S1`` active-append: a Claude Code session appended to once per batch must not call fingerprint_file or full-stream the blob. Covered with both sessionId-bearing and tool_result-only (no sessionId) appends. - ``S2`` mtime-drift catch-up: a single-file mtime drift must NOT trigger a full-file rehash at the watcher stage. - ``S3`` subagent append: a subagent file with provider_conversation_id = parent:agent-id and a path stem that differs from the conversation id must still take the append path. - ``S4`` 50-file catch-up: every file's mtime drifted; restart catch-up must not rehash any of them. The counter wraps fingerprint_file, last_complete_newline_from_tail, and BlobStore.write_from_path so the test can assert exact amplification ratios (``bytes_read_from_source / bytes_appended``). Before the production fix in the next commit, S2 and S4 both produced a fingerprint_file call per drifted file at the watcher stage — that was the read storm root cause. Ref #1003 follow-on. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…#1003 follow-on) Observed on sinnix-prime: polylogued sustained ~65 MB/s reads (12k IOPS, 9.5 KB/op) attributed to its PID during normal Claude Code activity with one active session. The metadata-heavy small-read pattern pointed at ``fingerprint_file`` calls on many small files. Static trace identified the watcher's ``_needs_work_from_state`` slowpath as the candidate: when a file's (dev, ino, size) matched the cursor but mtime had drifted, the watcher rehashed the entire file to distinguish "touched but unchanged" from "in-place rewrite." The regression test added in the previous commit confirmed empirically that mtime-only drift triggered a full-file fingerprint, and that a 50-file catch-up with universal mtime drift rehashed every file. Mtime drift alone is not a reliable content-change signal: - Filesystem touch operations advance mtime without changing content - Hardlink and rename-replace ops that preserve inode often advance mtime - fsync rounding produces nanosecond differences across batches - atime mount options on some filesystems update mtime as a side-effect The fix: trust the (dev, ino, size, content_fingerprint) tuple. If all four agree with the cursor, the file is the file we ingested — the mtime is irrelevant. Cost: same-size in-place content rewrites (rare: vim with backupcopy=yes, manual ``echo > file``, restore from same-size backup) are no longer auto-detected. Operators must explicitly ``polylogue ingest <path>`` or ``polylogue reset`` to re-pick those up. Tail-hash chunk check would restore the capability without the storm cost; tracked at #1009. The pre-existing ``test_same_size_rewrite_triggers_reingest`` is renamed to ``test_same_size_rewrite_is_not_auto_detected`` and rewritten to document the new contract and cross-reference #1003 / #1009. File-size budget exception added for the now-1517-line ``tests/unit/sources/test_live_watcher.py`` — kitchen-sink test file that should be split into per-subject suites; split candidate noted in ``docs/plans/file-size-budgets.yaml``. Closes #1003 (follow-on). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughThe PR implements mtime-drift tolerance in the live watcher's file-state check, allowing stored content fingerprints to be trusted when device, inode, and size match—regardless of modification time changes—and adds comprehensive read-amplification test coverage via new measurement infrastructure and five integration test scenarios. ChangesLive Watcher mtime-drift tolerance and read-amplification verification
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/infra/io_counter.py`:
- Around line 104-118: The harness misses instrumentation for small-file uploads
because BlobStore.write_from_bytes is not wrapped, so regressions that trigger
the path.read_bytes → blob_store.write_from_bytes flow won't be counted; add a
counted_write_from_bytes wrapper (parallel to counted_write_from_path) and
include patch.object(blob_store_mod.BlobStore, "write_from_bytes",
counted_write_from_bytes) in the same with(...) context that currently patches
BlobStore.write_from_path and the fingerprint/tail functions so all write paths
are accounted for during the test.
In `@tests/integration/test_live_read_amplification.py`:
- Around line 84-115: The processor fixture is creating real DB state and
seeding via raw CursorStore/SimpleNamespace instead of using the repo test
helpers; change it to accept and use the workspace_env fixture (use
workspace_env.archive_root and workspace_env.db_path) to create the environment
and replace the manual CursorStore and SimpleNamespace setup with the
workspace_env-provided paths, and seed conversations using ConversationBuilder
from tests/infra/storage_records.py (instead of raw SQL) before instantiating
LiveBatchProcessor (keep the same WatchSource args and the patch of
polylogue.sources.live.batch._process_ingest_batch_sync to return fake_summary);
ensure the fixture still yields (proc, source_root, source_file_path_factory).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 71d7539b-b9e2-45da-9fd6-e9423c9fd760
📒 Files selected for processing (5)
docs/plans/file-size-budgets.yamlpolylogue/sources/live/watcher.pytests/infra/io_counter.pytests/integration/test_live_read_amplification.pytests/unit/sources/test_live_watcher.py
| # ----- Wrap Path.read_bytes globally (only when used by batch.py) ---- | ||
| # We don't monkeypatch Path.read_bytes itself (way too broad). Instead, | ||
| # the test's expectation is: in normal append-only steady state, | ||
| # `_ingest_full_paths_sync` shouldn't be called at all. If the suite | ||
| # observes a `fingerprint_file` or `write_from_path` call after the | ||
| # first ingest, the suite has its evidence. | ||
|
|
||
| with ( | ||
| patch.object(batch_support, "fingerprint_file", counted_fingerprint), | ||
| patch.object(live_batch, "fingerprint_file", counted_fingerprint), | ||
| patch.object(live_watcher, "fingerprint_file", counted_fingerprint), | ||
| patch.object(batch_support, "last_complete_newline_from_tail", counted_tail), | ||
| patch.object(live_batch, "last_complete_newline_from_tail", counted_tail), | ||
| patch.object(blob_store_mod.BlobStore, "write_from_path", counted_write_from_path), | ||
| ): |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C3 'def _ingest_full_paths_sync|_STREAMING_FULL_INGEST_BYTES|read_bytes\(|write_from_bytes\(|write_from_path\(' \
polylogue/sources/live/batch.py \
polylogue/storage/blob_store.py \
tests/unit/sources/test_live_watcher.pyRepository: Sinity/polylogue
Length of output: 10125
🏁 Script executed:
find tests -name "*test_live_read_amplification*" -type fRepository: Sinity/polylogue
Length of output: 110
🏁 Script executed:
rg -n "_STREAMING_FULL_INGEST_BYTES\s*=" polylogue/sources/live/batch_support.pyRepository: Sinity/polylogue
Length of output: 110
🏁 Script executed:
head -100 tests/integration/test_live_read_amplification.py | grep -E "def test_|small|append|write_from"Repository: Sinity/polylogue
Length of output: 433
🏁 Script executed:
cat -n tests/integration/test_live_read_amplification.py | head -200Repository: Sinity/polylogue
Length of output: 9129
🏁 Script executed:
sed -n '1,103p' tests/infra/io_counter.pyRepository: Sinity/polylogue
Length of output: 3967
🏁 Script executed:
sed -n '165,230p' tests/integration/test_live_read_amplification.pyRepository: Sinity/polylogue
Length of output: 2863
Close the small-file instrumentation gap in the counter harness.
The test files in test_live_read_amplification.py are small (~500 bytes), well below the _STREAMING_FULL_INGEST_BYTES = 8 MB threshold. For files this small, batch.py uses the path.read_bytes() → blob_store.write_from_bytes() path (lines 736–740, 781–790), not write_from_path.
The harness currently wraps write_from_path but not write_from_bytes, so a regression that causes the full file to be re-read via write_from_bytes would not be counted. The test assertion counter.total_bytes <= max_allowed would still pass because only the tail scan and append payload contribute to the count.
Add a counted_write_from_bytes wrapper alongside counted_write_from_path:
Suggested fix
real_write_from_path = blob_store_mod.BlobStore.write_from_path
+ real_write_from_bytes = blob_store_mod.BlobStore.write_from_bytes
def counted_write_from_path(self, source, *, heartbeat=None): # type: ignore[no-untyped-def]
hash_hex, size = real_write_from_path(self, source, heartbeat=heartbeat)
counter.record("blob_store.write_from_path", size)
return hash_hex, size
+ def counted_write_from_bytes(self, data: bytes) -> tuple[str, int]: # type: ignore[no-untyped-def]
+ hash_hex, size = real_write_from_bytes(self, data)
+ counter.record("blob_store.write_from_bytes", len(data))
+ return hash_hex, size
with (
patch.object(batch_support, "fingerprint_file", counted_fingerprint),
patch.object(live_batch, "fingerprint_file", counted_fingerprint),
patch.object(live_watcher, "fingerprint_file", counted_fingerprint),
patch.object(batch_support, "last_complete_newline_from_tail", counted_tail),
patch.object(live_batch, "last_complete_newline_from_tail", counted_tail),
patch.object(blob_store_mod.BlobStore, "write_from_path", counted_write_from_path),
+ patch.object(blob_store_mod.BlobStore, "write_from_bytes", counted_write_from_bytes),🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/infra/io_counter.py` around lines 104 - 118, The harness misses
instrumentation for small-file uploads because BlobStore.write_from_bytes is not
wrapped, so regressions that trigger the path.read_bytes →
blob_store.write_from_bytes flow won't be counted; add a
counted_write_from_bytes wrapper (parallel to counted_write_from_path) and
include patch.object(blob_store_mod.BlobStore, "write_from_bytes",
counted_write_from_bytes) in the same with(...) context that currently patches
BlobStore.write_from_path and the fingerprint/tail functions so all write paths
are accounted for during the test.
| @pytest.fixture | ||
| def processor(tmp_path: Path) -> Iterator[tuple[LiveBatchProcessor, Path, Path]]: | ||
| """Real ``LiveBatchProcessor`` with mocked heavyweight ingest. | ||
|
|
||
| Returns ``(processor, source_root, source_file_path_factory)``. | ||
| The factory is a directory the caller can write JSONL files into. | ||
| """ | ||
| root = tmp_path / "projects" | ||
| root.mkdir() | ||
| db_path = tmp_path / "polylogue.db" | ||
| cursor = CursorStore(db_path) | ||
| polylogue = SimpleNamespace(archive_root=tmp_path, backend=SimpleNamespace(db_path=db_path), config=None) | ||
| proc = LiveBatchProcessor( | ||
| cast(Any, polylogue), | ||
| (WatchSource(name="claude-code", root=root),), | ||
| cursor=cursor, | ||
| parser_fingerprint=live_watcher._PARSER_FINGERPRINT, | ||
| ) | ||
|
|
||
| # Mock the heavyweight ingest to a no-op success. File reads BEFORE this | ||
| # call (the ones we're measuring) still happen against the real FS. | ||
| fake_summary = SimpleNamespace( | ||
| failed_raw_ids=[], | ||
| parse_failures=0, | ||
| worker_count=1, | ||
| worker_progress_total=0, | ||
| worker_progress_in_flight=0, | ||
| worker_progress_completed=0, | ||
| ) | ||
| with patch("polylogue.sources.live.batch._process_ingest_batch_sync", return_value=fake_summary): | ||
| yield proc, root, root | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Use the repo’s storage test fixtures/builders for this harness.
These tests create real cursor/database state and seed conversations with raw SQL, but they bypass workspace_env and ConversationBuilder. That makes the regression suite more brittle to XDG/archive-path and schema changes than the rest of the storage/pipeline tests.
As per coding guidelines, "tests/**/*.py: Use workspace_env fixture for tests that touch storage or pipeline. It provides isolated XDG paths and archive root in tmp_path. Use ConversationBuilder from tests/infra/storage_records.py for populating test databases with a fluent builder pattern."
Also applies to: 117-157
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/integration/test_live_read_amplification.py` around lines 84 - 115, The
processor fixture is creating real DB state and seeding via raw
CursorStore/SimpleNamespace instead of using the repo test helpers; change it to
accept and use the workspace_env fixture (use workspace_env.archive_root and
workspace_env.db_path) to create the environment and replace the manual
CursorStore and SimpleNamespace setup with the workspace_env-provided paths, and
seed conversations using ConversationBuilder from tests/infra/storage_records.py
(instead of raw SQL) before instantiating LiveBatchProcessor (keep the same
WatchSource args and the patch of
polylogue.sources.live.batch._process_ingest_batch_sync to return fake_summary);
ensure the fixture still yields (proc, source_root, source_file_path_factory).
Summary
Eliminates the read-amplification storm that produced ~65 MB/s sustained reads attributed to
polyloguedduring a single active Claude Code session. The watcher's_needs_work_from_stateslowpath was rehashing the entire file on every mtime drift, even when (dev, ino, size, content_fingerprint) all agreed with the cursor.The fix is one branch in one function: trust the cursor when those four fields agree, regardless of mtime. The investigation was evidence-driven — see "Adversarial-loop methodology" below.
Refs #1003 (follow-on; #1003 itself closed the schema-preflight loop).
Problem
Symptom (on sinnix-prime, NixOS, btrfs):
~/.claude/projects/lives)stat+openat+ smallreadrather than sequential scanning)/proc/pressure/iopeaked at avg10=73.6%Investigation
Traced every source-file read site in
polylogue/sources/live/:fingerprint_filein_needs_work_from_statefingerprint_filein_record_failed_cursorfingerprint_filein_cursor_state_after_full_ingest_latest_raw_fingerprintreturns None toopath.read_bytesin_ingest_full_paths_syncblob_store.write_from_path_append_planopen+seek+readTwo hypotheses fit the symptom:
Per the prompt's instruction to fix what data implicates, I built a regression harness (
tests/integration/test_live_read_amplification.py) that wraps every read site with a counter and runs four scenarios. Result:fingerprint_filecall of 690 bytes. A 50-file catch-up with universal mtime drift produced 50 calls.The user's prompt hypothesis #4 ("Tighten append-fallback condition") is wrong for this codebase as-is — that path already handles benign rotation correctly. H1 was the storm.
Solution
One-line semantic change in
polylogue/sources/live/watcher.py:_needs_work_from_state: dropcursor.mtime_ns == stat.st_mtime_nsfrom the early-return AND-condition. Trust(dev, ino, size, content_fingerprint)as authoritative.Mtime drift alone is not a reliable content-change signal — filesystem touches, hardlink ops, fsync rounding, nanosecond-resolution drift all advance mtime without changing content.
Cost and tracked follow-up
Same-size in-place content rewrites (rare:
echo 'new' > file.jsonlwhere new content happens to be the same length as old) are no longer auto-detected. Realistic production cases:backupcopy=yes— uncommon defaultOperators can force re-ingest with
polylogue ingest <path>orpolylogue reset.The pre-existing test
test_same_size_rewrite_triggers_reingestis renamed totest_same_size_rewrite_is_not_auto_detectedand rewritten to document the new contract.Tail-hash chunk check would restore auto-detection without the storm cost; tracked at #1009.
Acceptance criteria
Verbatim from the original prompt:
bytes_read ≤ 8 × bytes_appended + 64 KBper batch; in practice ≪ 1 because only the tail-newline scan happens.fingerprint_filecalls. Behaviour is per-file; 50 = 1000 here._needs_work_from_statereturns True forcursor is None.test_live_read_amplification.pyplus the renamed contract-pin intest_live_watcher.py.test_year_old_file_resumed_triggers_reingest(test_live_watcher.py:1210) still passes — dormant resumption producessize > cursor.byte_offset→ True via the fast path, regardless of mtime drift during dormancy.Files changed
polylogue/sources/live/watcher.py: the surgical fix (-3 / +5 lines).tests/integration/test_live_read_amplification.py: NEW; five regression scenarios.tests/infra/io_counter.py: NEW; read-counter infrastructure wrapping the production read sites.tests/unit/sources/test_live_watcher.py: renamestest_same_size_rewrite_triggers_reingest→test_same_size_rewrite_is_not_auto_detectedwith documented contract.docs/plans/file-size-budgets.yaml: exception for the kitchen-sink test file (1517 > 1500), with split candidate noted.Verification
Before/after for the read-counter scenarios:
fingerprint_file, 0 full-streamfingerprint_file(690 B)fingerprint_file(~35 KB)On a ~1000-session archive (the user's), the same fix eliminates ~1000
fingerprint_filecalls per drifted-mtime event.Adversarial review notes
Loop ran 2 iterations, both clean.
Iteration 1: independent reviewer walked through inverting the fix mentally — re-adding the mtime check would make test S2 (line 314-316) fail loud on the zero-fingerprint assertion. AC4 ("dormant resumption still ingests") confirmed via existing
test_year_old_file_resumed_triggers_reingestattest_live_watcher.py:1210. Verdict: "No legitimate gaps found across all ACs after iteration 1 review."Iteration 2: independent reviewer specifically attacked: inode-rotation edge case (atomic-write-rename), cursor non-advance loops, test S1's ×8 multiplier, convergence path indirect reads. All dismissed with evidence: Claude Code is append-only (no inode rotation in primary use case), partial batch failure path uses
_record_failed_cursor(no infinite loops), ×8 is generous because append reads delta+tail only, convergence stages are pure DB. Verdict: "No legitimate gaps found across all ACs after iteration 2 review."What I decided NOT to fix and why
fingerprint_filerepeats from_cursor_state_after_full_ingest_latest_raw_fingerprintALSO returns None, which requires no raw_conversations row for the path. In steady state, the row exists from first ingest._latest_raw_fingerprintalready prevents repeat fingerprinting after first full ingest.polylogue/daemon/convergence_stages.py: all stages are pure DB operations. No file or blob reads._append_payload_for_providerreturns None too oftenLIMIT 1on indexedsource_path.stop_requested/is_degradedbusy-loop_full_parse_progress_groups, not in a tight loop.Follow-up
🤖 Generated with Claude Code