Files
legal-ai/mcp-server/tests/test_storage_mirror.py
Chaim 0d8cc31a2b
All checks were successful
G12 Leak-Guard / leak-guard (pull_request) Successful in 5s
feat(storage): seal INV-STG1 write path — 15 dual-write seals + CI leak-guard + tripwire
אחרי ה-cutover ל-s3-only, אודיט מצא 15 אתרי-כתיבת-בלוב שעוקפים את storage.py (uploads/
finalize/exports/training/research-backup/precedents/bulletins/draft) — קובץ ינחת
בתיקיות-הישנות אך **לא** ב-MinIO → יאבד בניקוי, לא מוגש, לא מגובה. ה-pipeline (ingest/
extract) עדיין קורא לפי file_path מהדיסק, אז ביטול-מוחלט של כתיבה-לדיסק דורש read-wiring
מלא (Phase 2, משימה נפרדת). תיקון בטוח עכשיו = **dual-write seal**.

- storage.py: `mirror`/`mirror_file` (+ sync) — best-effort persist ל-S3 כשה-backend
  s3/dual (no-op ב-filesystem; כשל S3 נרשם, לא שובר request — DualBackend philosophy).
- web/app.py: helpers `_seal_blob`/`_seal_blob_file` + 14 אתרים אטומים (storage.mirror
  אחרי כתיבת-הדיסק; הדיסק נשאר ל-pipeline). block_writer.py: draft אטום (async).
- **CI leak-guard** (test_storage_write_leak_guard): נכשל על כל כתיבת-בלוב-לדיסק
  (write_bytes/write_text/shutil.copy*/open(wb)) ב-web/+services ללא מרקר `# noqa: STG1`.
  כל ה-benign (fallbacks/tmp/staging/git-metadata/flag/state) מסומנים עם נימוק. storage.py
  מוחרג (הוא המימוש).
- **tripwire** (scripts/storage_leak_tripwire.py): ניטור-ריצה — בלובים בדיסק שלא ב-MinIO
  (json-key match, bucket per-file). אומת חי: 0 דליפות.

invariants: INV-STG1 (כל I/O דרך storage / ממורר אליו) · INV-STG6 · feedback_silent_swallow
(mirror רושם warning, לא bare-except). Phase 2 (read-wire ה-pipeline → להפיל את עותק-הדיסק)
= follow-up. tests: 4 mirror + 1 leak-guard + 6 serve_blob + 18 storage קיימות עוברות.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-11 19:57:12 +00:00

75 lines
2.3 KiB
Python

"""Tests for storage.mirror — the INV-STG1 dual-write seal.
mirror() must: be a no-op under the filesystem backend (the disk write is
canonical), persist to the S3 sub-backend under s3/dual, and never raise (an S3
failure is logged, the request proceeds on the disk copy). Offline.
"""
from __future__ import annotations
import asyncio
import pytest
from legal_mcp.services import storage
class _FakeS3:
def __init__(self, fail: bool = False) -> None:
self.fail = fail
self.puts: list[tuple] = []
async def put_bytes(self, key, data, *, bucket, content_type=None, metadata=None):
if self.fail:
raise RuntimeError("s3 down")
self.puts.append((key, bytes(data), bucket))
return f"s3://{bucket}/{key}"
class _FakeFilesystem:
name = "filesystem"
class _FakeDual:
name = "dual"
def __init__(self, s3: _FakeS3) -> None:
self.s3 = s3
def _run(coro):
loop = asyncio.new_event_loop()
try:
return loop.run_until_complete(coro)
finally:
loop.close()
def test_mirror_noop_under_filesystem(monkeypatch):
monkeypatch.setattr(storage, "get_storage", lambda: _FakeFilesystem())
# must not raise and must not attempt any S3 work
_run(storage.mirror("cases/x/y.pdf", b"data", bucket=storage.Bucket.DOCUMENTS))
def test_mirror_persists_under_dual(monkeypatch):
s3 = _FakeS3()
monkeypatch.setattr(storage, "get_storage", lambda: _FakeDual(s3))
_run(storage.mirror("cases/x/y.pdf", b"data", bucket=storage.Bucket.DOCUMENTS))
assert s3.puts == [("cases/x/y.pdf", b"data", storage.Bucket.DOCUMENTS)]
def test_mirror_best_effort_never_raises(monkeypatch):
s3 = _FakeS3(fail=True)
monkeypatch.setattr(storage, "get_storage", lambda: _FakeDual(s3))
# S3 failure must be swallowed-with-log, never propagate (disk copy holds)
_run(storage.mirror("cases/x/y.pdf", b"data", bucket=storage.Bucket.DOCUMENTS))
def test_mirror_uses_backend_itself_when_no_s3_attr(monkeypatch):
# a pure s3 backend has no .s3 sub-attr → getattr falls back to the backend
s3 = _FakeS3()
s3.name = "s3"
monkeypatch.setattr(storage, "get_storage", lambda: s3)
_run(storage.mirror("k", b"d", bucket=storage.Bucket.DERIVED))
assert s3.puts == [("k", b"d", storage.Bucket.DERIVED)]