M2: extraction quality — fallback extractors, thin-content detection, result cache

- extractor: trafilatura (precision) -> trafilatura (recall) -> readability-lxml
  fallback chain; longest result wins; 'thin' flag below 200 chars
- orchestrator: Redis-backed scrape-result cache keyed by URL (cache hit skips
  render entirely); thin/empty results are never cached
- /health reports orchestrator Redis reachability

Verified: HN + synthetic thin/empty/boilerplate pages; cache hit path via fakeredis.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
User 2026-07-05 22:05:04 -07:00
parent e2b329b2bb
commit 56e7fa16dd
8 changed files with 156 additions and 32 deletions

View file

@ -0,0 +1,46 @@
"""Redis-backed result cache; degrades to no-op when Redis is unavailable."""
import json
import logging
import redis.asyncio as aioredis
log = logging.getLogger("orchestrator")
class Cache:
def __init__(self, redis_url: str | None):
self._redis = None
if redis_url:
self._redis = aioredis.from_url(redis_url, socket_timeout=2, socket_connect_timeout=2)
else:
log.warning("no REDIS_URL configured; orchestrator result cache disabled")
async def get_json(self, key: str) -> dict | None:
if not self._redis:
return None
try:
raw = await self._redis.get(key)
return json.loads(raw) if raw else None
except Exception:
return None
async def set_json(self, key: str, value: dict, ttl: int) -> None:
if not self._redis:
return
try:
await self._redis.set(key, json.dumps(value), ex=ttl)
except Exception:
pass
async def is_ready(self) -> bool:
if not self._redis:
return False
try:
return await self._redis.ping()
except Exception:
return False
async def close(self) -> None:
if self._redis:
await self._redis.aclose()

View file

@ -5,3 +5,6 @@ EXTRACTOR_URL = os.environ.get("EXTRACTOR_URL", "http://localhost:8003")
SEARCHER_URL = os.environ.get("SEARCHER_URL", "http://localhost:8001")
STAGE_TIMEOUT_S = float(os.environ.get("STAGE_TIMEOUT_S", "60"))
REDIS_URL = os.environ.get("REDIS_URL", "")
EXTRACT_CACHE_TTL = int(os.environ.get("EXTRACT_CACHE_TTL", "3600"))

View file

@ -7,6 +7,7 @@ from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from . import config, pipeline
from .cache import Cache
from .logging_setup import setup
log = setup()
@ -15,7 +16,9 @@ log = setup()
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.client = httpx.AsyncClient()
app.state.cache = Cache(config.REDIS_URL)
yield
await app.state.cache.close()
await app.state.client.aclose()
@ -38,7 +41,12 @@ async def health() -> dict:
except httpx.HTTPError:
services[name] = {"status": "unreachable"}
overall = "ok" if all(s.get("status") == "ok" for s in services.values()) else "degraded"
return {"status": overall, "service": "orchestrator", "services": services}
return {
"status": overall,
"service": "orchestrator",
"redis": await app.state.cache.is_ready(),
"services": services,
}
@app.post("/scrape")
@ -46,7 +54,7 @@ async def scrape(req: ScrapeRequest) -> dict:
if not req.url.startswith(("http://", "https://")):
raise HTTPException(status_code=400, detail="url must be http(s)")
try:
result = await pipeline.scrape_url(app.state.client, req.url)
result = await pipeline.scrape_url(app.state.client, req.url, app.state.cache)
except pipeline.StageError as exc:
log.error("scrape failed at %s: %s", exc.stage, exc.detail)
raise HTTPException(status_code=502, detail={"stage": exc.stage, "error": exc.detail}) from exc

View file

@ -6,6 +6,7 @@ from typing import Any
import httpx
from . import config
from .cache import Cache
class Trace:
@ -68,12 +69,23 @@ async def extract(client: httpx.AsyncClient, html: str, url: str, trace: Trace)
return result
async def scrape_url(client: httpx.AsyncClient, url: str) -> dict:
"""render -> extract for one URL. Raises StageError on hard failure."""
async def scrape_url(client: httpx.AsyncClient, url: str, cache: Cache | None = None) -> dict:
"""render -> extract for one URL. Raises StageError on hard failure.
The extracted result is cached by URL; a hit skips render entirely.
"""
trace = Trace()
cache_key = f"scrape:{url}"
if cache:
start = time.monotonic()
cached = await cache.get_json(cache_key)
if cached:
trace.record("scrape_cache", (time.monotonic() - start) * 1000, cache="hit")
return {**cached, "trace": trace.as_dict()}
rendered = await render(client, url, trace)
extracted = await extract(client, rendered["html"], rendered.get("final_url") or url, trace)
return {
result = {
"url": url,
"final_url": rendered.get("final_url"),
"status": rendered.get("status"),
@ -81,5 +93,8 @@ async def scrape_url(client: httpx.AsyncClient, url: str) -> dict:
"content": extracted.get("text", ""),
"metadata": extracted.get("metadata", {}),
"extractor_used": extracted.get("extractor_used"),
"trace": trace.as_dict(),
"thin": extracted.get("thin", False),
}
if cache and result["content"] and not result["thin"]:
await cache.set_json(cache_key, result, config.EXTRACT_CACHE_TTL)
return {**result, "trace": trace.as_dict()}

View file

@ -2,3 +2,4 @@ fastapi>=0.115
uvicorn[standard]>=0.32
httpx>=0.27
mcp>=1.2
redis>=5.0