Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): reset the verification streaks when a baseline is re-recorded (#7014)

Ziyang Guodfee455d1a33
diff --git a/changelog.d/+reset-stale-integrity-streaks.bugfix.md b/changelog.d/+reset-stale-integrity-streaks.bugfix.md
new file mode 100644
index 0000000000..0f79a5eff0
--- /dev/null
+++ b/changelog.d/+reset-stale-integrity-streaks.bugfix.md
@@ -0,0 +1 @@
+Re-recording a file's integrity baseline (`FileIntegrityManager.record_file`) now clears the verification streaks accumulated against the previous baseline. Before, `consecutive_failures` and `consecutive_successes` survived the re-record and were attributed to the new bytes: a RAG index rebuilt after a quarantine-and-recovery cycle started life still counted as the index that had just been thrown away, so the statistics reported for the fresh baseline (`get_file_stats`) described bytes it had never seen. The two counters are reset together — `_update_stats` maintains them as a mutually exclusive pair — while the historical counters `total_verifications`, `last_verified_at` and `last_verification_passed`, and the retained `FileVerificationFailure` audit rows, are preserved. Implements the follow-up noted in `_quarantine_corrupt_index` (#4197).
diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.py
index 8c2b5aecda..c929c4b4c8 100644
--- a/src/local_deep_research/research_library/services/library_rag_service.py
+++ b/src/local_deep_research/research_library/services/library_rag_service.py
@@ -966,15 +966,17 @@ class LibraryRAGService:
loading the index into a ``VectorIndex``/faiss raised) where the
on-disk bytes may still be usable by a human.
+ The rebuilt index is re-recorded by the caller (``_record``
+ through ``FileIntegrityManager.record_file``), which resets the
+ path's verification streaks (``consecutive_failures`` /
+ ``consecutive_successes``) — the streak accumulated against the
+ quarantined bytes must not be charged to the new ones.
+
Raises ``OSError`` on rename failure (disk full, read-only fs,
permission denied). Re-raising prevents silent data loss: if we
swallowed the error, the next ``persist()``/``faiss.write_index``
would overwrite the corrupt bytes anyway. Caller paths log the
exception via the broader try/except around their indexer call.
-
- # TODO(#4197-followup): FileIntegrityRecord.consecutive_failures
- # is not reset by the next record_file call, leaking failure
- # counts across recovery cycles. Orthogonal to this fix.
"""
ns = time.time_ns()
pkl_path = index_path.with_suffix(".pkl")
diff --git a/src/local_deep_research/security/file_integrity/integrity_manager.py b/src/local_deep_research/security/file_integrity/integrity_manager.py
index 8e1eb71f58..e3d4cbd70b 100644
--- a/src/local_deep_research/security/file_integrity/integrity_manager.py
+++ b/src/local_deep_research/security/file_integrity/integrity_manager.py
@@ -201,6 +201,25 @@ class FileIntegrityManager:
record.file_mtime = file_stat.st_mtime
record.algorithm = verifier.get_algorithm()
record.updated_at = datetime.now(UTC)
+ # Re-recording installs a NEW baseline, so both
+ # verification streaks -- accumulated against the
+ # PREVIOUS checksum -- describe a file that no
+ # longer exists. Left in place they are charged to
+ # the new bytes: an index rebuilt after a
+ # quarantine started out still counted as the one
+ # that had just been thrown away, and
+ # get_file_stats reported statistics about a
+ # baseline the new one had never been verified
+ # against. consecutive_successes is reset alongside
+ # -- the two are a mutually exclusive pair in
+ # _update_stats, so resetting only one would leave
+ # the other crediting (or charging) the new
+ # baseline with verifications it never had.
+ # total_verifications / last_verified_at /
+ # last_verification_passed stay: they are history
+ # about the path, not about one baseline.
+ record.consecutive_failures = 0
+ record.consecutive_successes = 0
logger.info(
f"[FILE_INTEGRITY] Updated record for: {file_path}"
)
@@ -331,6 +350,14 @@ class FileIntegrityManager:
Use this when you know a file was legitimately modified
and want to update the baseline checksum.
+ Like ``record_file``, this installs a NEW baseline, so the same
+ argument applies to the verification streaks: the pair left in
+ place would describe the checksum that has just been replaced.
+ ``record_file`` owns that invariant and resets them (see the
+ comment there); this method currently has no production callers,
+ and the parity fix is tracked in #7019 rather than shipped
+ untested here.
+
Args:
file_path: Path to file
diff --git a/tests/security/file_integrity/test_integrity_manager.py b/tests/security/file_integrity/test_integrity_manager.py
index 80e03d6513..4bbc616b81 100644
--- a/tests/security/file_integrity/test_integrity_manager.py
+++ b/tests/security/file_integrity/test_integrity_manager.py
@@ -717,6 +717,80 @@ class TestRecordFile:
assert existing.checksum == "newchecksum"
mock_ctx.commit.assert_called()
+ def test_resets_stale_verification_streaks(self, tmp_path):
+ """Re-recording clears the streaks left by the previous baseline.
+
+ record_file installs the file's CURRENT checksum as the new
+ baseline, so the pass/fail streaks accumulated against the old
+ checksum describe a file that no longer exists. Kept, they are
+ charged to the new bytes: an index rebuilt after a quarantine
+ still reports the failure count of the one that was thrown away
+ (#4197 follow-up). Nothing in the codebase evaluates those
+ streaks against a threshold -- the only reader is get_file_stats,
+ which no production caller uses -- so the claim here is about
+ statistics describing the right bytes, not about a guard that
+ trips.
+
+ Only the streak pair is reset — total_verifications,
+ last_verified_at and last_verification_passed are history about
+ the path and must survive.
+ """
+ from local_deep_research.security.file_integrity.integrity_manager import (
+ FileIntegrityManager,
+ )
+ from local_deep_research.security.file_integrity.base_verifier import (
+ BaseFileVerifier,
+ FileType,
+ )
+
+ class StubVerifier(BaseFileVerifier):
+ def should_verify(self, fp):
+ return True
+
+ def get_file_type(self):
+ return FileType.PDF
+
+ def allows_modifications(self):
+ return False
+
+ f = tmp_path / "recovered.bin"
+ f.write_text("rebuilt content")
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session"
+ ) as mock_gs:
+ mock_ctx = MagicMock()
+ mock_gs.return_value.__enter__ = Mock(return_value=mock_ctx)
+ mock_gs.return_value.__exit__ = Mock(return_value=False)
+ mock_ctx.query.return_value.count.return_value = 0
+ mgr = FileIntegrityManager("user", "pass")
+
+ v = StubVerifier()
+ v.calculate_checksum = Mock(return_value="freshchecksum")
+ mgr.register_verifier(v)
+
+ # The quarantined index had failed three verifications (and,
+ # before that, verified clean twice) against the OLD checksum;
+ # both streaks are stale once the bytes are rebuilt, while the
+ # historical columns keep describing the path.
+ existing = Mock()
+ existing.checksum = "corruptchecksum"
+ existing.consecutive_failures = 3
+ existing.consecutive_successes = 2
+ existing.total_verifications = 9
+ existing.last_verified_at = "sentinel-last-verified"
+ existing.last_verification_passed = False
+ mock_ctx.query.return_value.filter_by.return_value.first.return_value = existing
+
+ mgr.record_file(f)
+
+ assert existing.checksum == "freshchecksum"
+ assert existing.consecutive_failures == 0
+ assert existing.consecutive_successes == 0
+ assert existing.total_verifications == 9
+ assert existing.last_verified_at == "sentinel-last-verified"
+ assert existing.last_verification_passed is False
+
def test_raises_file_not_found(self, tmp_path):
"""Missing file raises FileNotFoundError."""
mgr = _make_manager()