Spaces:
Sleeping
feat(upload-extract): Tier-2 content-hash cache — same PDF, no re-extraction
Browse filesWhen a user re-uploads the same PDF (same sha256 of bytes), look up
any prior persisted upload's extracted JSON and reuse it. Saves:
- 30-60s of LLM call time
- one Gemini API call (rate-limit pressure, cost)
- guarantees deterministic same-extraction-for-same-content
How it works:
- meta.json already records sha256 of pdf_bytes per upload
- _find_cached_extraction() iterates UPLOADED_DOCS_DIR/*/meta.json,
finds another policy_id with the same sha but different policy_id
- if rag/extracted/<other_pid>.json exists for that hash, copy it to
this policy's path
- marks status=complete + bumps the marketplace grade cache
- returns immediately, never enters the LLM retry loop
Fail-closed: any lookup error → cache miss → falls through to fresh
LLM extraction.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- backend/uploaded_docs.py +106 -0
|
@@ -770,6 +770,49 @@ def get_extraction_status(policy_id: str) -> Optional[dict]:
|
|
| 770 |
return _UPLOAD_EXTRACTION_STATUS.get(policy_id)
|
| 771 |
|
| 772 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 773 |
async def extract_one_for_upload(
|
| 774 |
policy_id: str,
|
| 775 |
pdf_path: Path,
|
|
@@ -785,6 +828,11 @@ async def extract_one_for_upload(
|
|
| 785 |
Status is mirrored to `_UPLOAD_EXTRACTION_STATUS[policy_id]` at every
|
| 786 |
phase change so the frontend's poll loop sees progress in real time.
|
| 787 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 788 |
Returns True iff a HealthPolicy was successfully extracted and written.
|
| 789 |
Swallows all errors (returns False) — a failed LLM pass must NEVER
|
| 790 |
affect the upload's HTTP response, which has already returned.
|
|
@@ -801,6 +849,64 @@ async def extract_one_for_upload(
|
|
| 801 |
overall_grade=None,
|
| 802 |
error=None,
|
| 803 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 804 |
try:
|
| 805 |
# Lazy imports — these touch the LLM client + DuckDB; we don't
|
| 806 |
# want to pay that cost at module import time.
|
|
|
|
| 770 |
return _UPLOAD_EXTRACTION_STATUS.get(policy_id)
|
| 771 |
|
| 772 |
|
| 773 |
+
# ---------------------------------------------------------------------------
|
| 774 |
+
# Tier-2 optimisations (ADR-044, 2026-05-27):
|
| 775 |
+
# - Content-hash cache: same sha256(pdf_bytes) → reuse prior extraction
|
| 776 |
+
# instead of re-running the LLM.
|
| 777 |
+
# - (Per-section extraction is deferred to a future iteration — full
|
| 778 |
+
# implementation requires schema partitioning + retryable merge, and
|
| 779 |
+
# the bigger immediate win for parity is the hash cache + the Tier-1
|
| 780 |
+
# stability fixes that just landed.)
|
| 781 |
+
# ---------------------------------------------------------------------------
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
def _find_cached_extraction(content_sha: str, current_policy_id: str) -> Optional[Path]:
|
| 785 |
+
"""Look for a prior successful extraction of the same content (sha256
|
| 786 |
+
match) under a DIFFERENT policy_id. Returns the path to the existing
|
| 787 |
+
rag/extracted/<other_pid>.json if found, else None.
|
| 788 |
+
|
| 789 |
+
This handles the legitimate "user uploads the same PDF twice (maybe
|
| 790 |
+
in two browser tabs / two sessions)" case — the second upload should
|
| 791 |
+
get the identical extracted JSON without paying the LLM cost again.
|
| 792 |
+
Fail-closed: any I/O error → None (caller runs a fresh extraction).
|
| 793 |
+
"""
|
| 794 |
+
if not content_sha:
|
| 795 |
+
return None
|
| 796 |
+
try:
|
| 797 |
+
from backend.config import settings as _settings
|
| 798 |
+
for meta_path in uploaded_docs_dir().glob("*/meta.json"):
|
| 799 |
+
try:
|
| 800 |
+
meta = json.loads(meta_path.read_text())
|
| 801 |
+
except Exception:
|
| 802 |
+
continue
|
| 803 |
+
if meta.get("sha256") != content_sha:
|
| 804 |
+
continue
|
| 805 |
+
other_pid = meta.get("policy_id") or meta_path.parent.name
|
| 806 |
+
if other_pid == current_policy_id:
|
| 807 |
+
continue # ignore our own meta if it's already written
|
| 808 |
+
cached = _settings.EXTRACTED_DIR / f"{other_pid}.json"
|
| 809 |
+
if cached.exists():
|
| 810 |
+
return cached
|
| 811 |
+
except Exception: # noqa: BLE001
|
| 812 |
+
pass
|
| 813 |
+
return None
|
| 814 |
+
|
| 815 |
+
|
| 816 |
async def extract_one_for_upload(
|
| 817 |
policy_id: str,
|
| 818 |
pdf_path: Path,
|
|
|
|
| 828 |
Status is mirrored to `_UPLOAD_EXTRACTION_STATUS[policy_id]` at every
|
| 829 |
phase change so the frontend's poll loop sees progress in real time.
|
| 830 |
|
| 831 |
+
Hash-cache short-circuit (Tier-2 ADR-044): if a prior upload with the
|
| 832 |
+
same `sha256(pdf_bytes)` already has a successful `rag/extracted/
|
| 833 |
+
<other_pid>.json`, that file is COPIED to this policy's path without
|
| 834 |
+
re-running the LLM. Same content, same extraction — guaranteed.
|
| 835 |
+
|
| 836 |
Returns True iff a HealthPolicy was successfully extracted and written.
|
| 837 |
Swallows all errors (returns False) — a failed LLM pass must NEVER
|
| 838 |
affect the upload's HTTP response, which has already returned.
|
|
|
|
| 849 |
overall_grade=None,
|
| 850 |
error=None,
|
| 851 |
)
|
| 852 |
+
|
| 853 |
+
# ─── Tier-2 hash-cache short-circuit (ADR-044) ─────────────────
|
| 854 |
+
# If we've previously extracted a PDF with the same content hash,
|
| 855 |
+
# reuse that extraction. Same content → same fields by construction.
|
| 856 |
+
# Saves 30-60s + a Gemini call.
|
| 857 |
+
try:
|
| 858 |
+
meta_path = _doc_dir(policy_id) / "meta.json"
|
| 859 |
+
if meta_path.exists():
|
| 860 |
+
meta = json.loads(meta_path.read_text())
|
| 861 |
+
content_sha = meta.get("sha256") or ""
|
| 862 |
+
if content_sha:
|
| 863 |
+
cached_path = _find_cached_extraction(content_sha, policy_id)
|
| 864 |
+
if cached_path is not None:
|
| 865 |
+
_log.info(
|
| 866 |
+
"[upload-extract] hash-cache HIT for %s "
|
| 867 |
+
"(reusing %s) — skipping LLM",
|
| 868 |
+
policy_id, cached_path.name,
|
| 869 |
+
)
|
| 870 |
+
# Copy the prior extraction to this policy's path so
|
| 871 |
+
# /api/policies/{id}/scorecard finds it under the
|
| 872 |
+
# right id.
|
| 873 |
+
from backend.config import settings as _settings_a
|
| 874 |
+
_settings_a.EXTRACTED_DIR.mkdir(parents=True, exist_ok=True)
|
| 875 |
+
dest = _settings_a.EXTRACTED_DIR / f"{policy_id}.json"
|
| 876 |
+
dest.write_text(cached_path.read_text())
|
| 877 |
+
# Mark status complete with whatever completeness the
|
| 878 |
+
# marketplace scorecard now computes.
|
| 879 |
+
_final_comp = None
|
| 880 |
+
_final_grade = None
|
| 881 |
+
try:
|
| 882 |
+
from rag.schema import HealthPolicy
|
| 883 |
+
from backend.scorecard import build_scorecard as _bs
|
| 884 |
+
_doc = json.loads(dest.read_text())
|
| 885 |
+
_sc = _bs(_doc, profile=None)
|
| 886 |
+
if _sc is not None:
|
| 887 |
+
_final_comp = float(_sc.data_completeness_pct)
|
| 888 |
+
_final_grade = _sc.overall_grade
|
| 889 |
+
except Exception:
|
| 890 |
+
pass
|
| 891 |
+
# Bust the #40 grade cache so /api/policies/all
|
| 892 |
+
# picks up the new card.
|
| 893 |
+
try:
|
| 894 |
+
import backend.main as _bm
|
| 895 |
+
with _bm._MG_LOCK:
|
| 896 |
+
_bm._MG_CACHE["sig"] = None
|
| 897 |
+
_bm._MG_CACHE["index"] = None
|
| 898 |
+
except Exception:
|
| 899 |
+
pass
|
| 900 |
+
await _set_extraction_status(
|
| 901 |
+
policy_id, status="complete",
|
| 902 |
+
completed_at=_now(),
|
| 903 |
+
completeness_pct=_final_comp,
|
| 904 |
+
overall_grade=_final_grade,
|
| 905 |
+
)
|
| 906 |
+
return True
|
| 907 |
+
except Exception as e: # noqa: BLE001 — cache miss is fine, run fresh
|
| 908 |
+
_log.debug("[upload-extract] hash-cache lookup failed: %s", e)
|
| 909 |
+
|
| 910 |
try:
|
| 911 |
# Lazy imports — these touch the LLM client + DuckDB; we don't
|
| 912 |
# want to pay that cost at module import time.
|