Spaces:
Running
Running
Merge pull request #52 from siddhm11/feat/figures-everywhere
Browse filesfeat(figures): background warm-up on arXiv's 15 s lane, and search thumbnails
- app/config.py +13 -3
- app/figure_prewarm.py +124 -29
- app/paper_source_svc.py +47 -7
- app/routers/figures.py +25 -12
- app/routers/recommendations.py +4 -1
- app/routers/search.py +8 -1
- app/static/app.js +6 -5
- app/static/styles.css +14 -0
- app/templates/partials/paper_card.html +19 -0
- docs/CURRENT-STATE.md +3 -2
- docs/research/06-Deep-Research-Verdict.md +30 -0
- scripts/seed_e2e.py +7 -1
- tests/test_e2e_search.py +85 -0
- tests/test_features.py +14 -0
- tests/test_paper_source_svc.py +49 -0
- tests/test_search_figures.py +81 -0
- tests/test_wide_feed.py +90 -1
app/config.py
CHANGED
|
@@ -21,7 +21,18 @@ QDRANT_COLLECTION = os.getenv("QDRANT_COLLECTION", "arxiv_bgem3_dense")
|
|
| 21 |
DB_PATH = os.getenv("DB_PATH", "interactions.db")
|
| 22 |
|
| 23 |
# ββ arXiv API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
ARXIV_MAX_RESULTS = 10 # results per search page
|
| 26 |
METADATA_CACHE_TTL_DAYS = 30 # re-fetch metadata after this many days
|
| 27 |
|
|
@@ -42,8 +53,7 @@ FULL_ABSTRACTS_DAILY_CAP = int(os.getenv("FULL_ABSTRACTS_DAILY_CAP", "3000"))
|
|
| 42 |
# only be changed when RESEARCHIT_ENV=test, for browser tests against a local
|
| 43 |
# stand-in; production always reads arxiv.org.
|
| 44 |
RESEARCHIT_ENV = os.getenv("RESEARCHIT_ENV", "").strip().lower()
|
| 45 |
-
ARXIV_HTML_BASE = (
|
| 46 |
-
if RESEARCHIT_ENV == "test" else "") or "https://arxiv.org/html"
|
| 47 |
# Parsed full text kept locally for this many most recently used papers. Each is
|
| 48 |
# roughly 50-150 KB of text; measure the database before raising it.
|
| 49 |
FULLTEXT_MAX_PAPERS = int(os.getenv("FULLTEXT_MAX_PAPERS", "5000"))
|
|
|
|
| 21 |
DB_PATH = os.getenv("DB_PATH", "interactions.db")
|
| 22 |
|
| 23 |
# ββ arXiv API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 24 |
+
def _test_override(name: str, default: str) -> str:
|
| 25 |
+
"""An arXiv address the browser tests may point at a local stand-in.
|
| 26 |
+
|
| 27 |
+
Honoured only when RESEARCHIT_ENV=test, so production always talks to
|
| 28 |
+
arXiv itself and the tests' world never does.
|
| 29 |
+
"""
|
| 30 |
+
if os.getenv("RESEARCHIT_ENV", "").strip().lower() == "test":
|
| 31 |
+
return os.getenv(name, "").strip().rstrip("/") or default
|
| 32 |
+
return default
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
ARXIV_API_URL = _test_override("ARXIV_API_URL", "https://export.arxiv.org/api/query")
|
| 36 |
ARXIV_MAX_RESULTS = 10 # results per search page
|
| 37 |
METADATA_CACHE_TTL_DAYS = 30 # re-fetch metadata after this many days
|
| 38 |
|
|
|
|
| 53 |
# only be changed when RESEARCHIT_ENV=test, for browser tests against a local
|
| 54 |
# stand-in; production always reads arxiv.org.
|
| 55 |
RESEARCHIT_ENV = os.getenv("RESEARCHIT_ENV", "").strip().lower()
|
| 56 |
+
ARXIV_HTML_BASE = _test_override("ARXIV_HTML_BASE", "https://arxiv.org/html")
|
|
|
|
| 57 |
# Parsed full text kept locally for this many most recently used papers. Each is
|
| 58 |
# roughly 50-150 KB of text; measure the database before raising it.
|
| 59 |
FULLTEXT_MAX_PAPERS = int(os.getenv("FULLTEXT_MAX_PAPERS", "5000"))
|
app/figure_prewarm.py
CHANGED
|
@@ -1,17 +1,25 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
"""
|
| 16 |
from __future__ import annotations
|
| 17 |
|
|
@@ -19,20 +27,80 @@ import asyncio
|
|
| 19 |
import fcntl
|
| 20 |
import os
|
| 21 |
import time
|
|
|
|
| 22 |
from pathlib import Path
|
| 23 |
|
| 24 |
from app import config, errors, features, licences, paper_source_svc
|
| 25 |
|
| 26 |
SWITCH = "FIGURE_PREWARM"
|
| 27 |
INTERVAL_S = int(os.getenv("FIGURE_PREWARM_INTERVAL_S", "21600"))
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
FIRST_RUN_DELAY_S = int(os.getenv("FIGURE_PREWARM_FIRST_DELAY_S", "120"))
|
| 30 |
LOCK_PATH = Path(os.getenv("FIGURE_PREWARM_LOCK", "/tmp/researchit-figure-prewarm.lock"))
|
| 31 |
|
| 32 |
_state: dict = {"scheduler": "off", "last_run": None, "next_run": None,
|
| 33 |
"done": 0, "skipped": 0, "failed": 0, "stopped_by_breaker": False}
|
| 34 |
_task: asyncio.Task | None = None
|
|
|
|
| 35 |
_lock_handle = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
async def recent_ids(days: int = 2) -> list[tuple[str, str]]:
|
|
@@ -56,7 +124,7 @@ async def _thumbnail(source) -> bool:
|
|
| 56 |
from app.routers import figures
|
| 57 |
for n in range(len(source.figures)):
|
| 58 |
if figures.figure_url(source, n):
|
| 59 |
-
return await figures.prepare(source, n)
|
| 60 |
return False
|
| 61 |
|
| 62 |
|
|
@@ -74,17 +142,36 @@ async def run_once(limit: int | None = None) -> dict:
|
|
| 74 |
if paper_source_svc.breaker_open():
|
| 75 |
counts["stopped_by_breaker"] = True
|
| 76 |
break
|
|
|
|
|
|
|
| 77 |
try:
|
| 78 |
-
|
| 79 |
-
if
|
| 80 |
-
await _thumbnail(source)
|
| 81 |
-
counts["done" if source is not None else "failed"] += 1
|
| 82 |
except Exception as e: # one paper never stops the run
|
| 83 |
counts["failed"] += 1
|
| 84 |
errors.report("figure_prewarm", f"warming {arxiv_id} failed", e)
|
| 85 |
return counts
|
| 86 |
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
async def _loop() -> None:
|
| 89 |
await asyncio.sleep(FIRST_RUN_DELAY_S)
|
| 90 |
while True:
|
|
@@ -113,25 +200,30 @@ def _take_lock() -> bool:
|
|
| 113 |
|
| 114 |
|
| 115 |
async def start() -> None:
|
| 116 |
-
global _task
|
| 117 |
if features.mode(SWITCH) != "on" or _task is not None:
|
| 118 |
return
|
| 119 |
if not _take_lock():
|
| 120 |
_state["scheduler"] = "blocked: another runner holds the lock"
|
| 121 |
return
|
| 122 |
_state["scheduler"] = "starting"
|
|
|
|
|
|
|
|
|
|
| 123 |
_task = asyncio.create_task(_loop(), name="figure-prewarm")
|
|
|
|
| 124 |
|
| 125 |
|
| 126 |
async def stop() -> None:
|
| 127 |
-
global _task, _lock_handle
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
| 135 |
if _lock_handle is not None:
|
| 136 |
try:
|
| 137 |
fcntl.flock(_lock_handle, fcntl.LOCK_UN)
|
|
@@ -143,4 +235,7 @@ async def stop() -> None:
|
|
| 143 |
|
| 144 |
|
| 145 |
def status() -> dict:
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
Read papers and prepare a figure before anyone opens them (switch FIGURE_PREWARM).
|
| 3 |
+
|
| 4 |
+
Two sources of papers, both read the same way (paper_source_svc.ensure, then
|
| 5 |
+
the first figure that may be shown):
|
| 6 |
+
|
| 7 |
+
shown papers people were just shown: every feed page and the top
|
| 8 |
+
SEARCH_TOP search results call enqueue(). Feed cards and search
|
| 9 |
+
thumbnails only use what is already saved, so a paper read now
|
| 10 |
+
shows its figure the next time it appears.
|
| 11 |
+
recent every few hours, papers Turso dates in the last two days, so new
|
| 12 |
+
papers have a figure the first time anyone sees them. It runs
|
| 13 |
+
INSIDE the Space on purpose: turso_sync only pushes after boot, so
|
| 14 |
+
rows a GitHub Action wrote to Turso would never reach a running
|
| 15 |
+
Space (trap T2 in docs/redesign/03-start-here-agent-handoff.md).
|
| 16 |
+
|
| 17 |
+
Polite by construction, because nobody is waiting for any of it: every
|
| 18 |
+
request takes paper_source_svc's background lane, one request per 15 s at
|
| 19 |
+
most (arXiv's robots.txt Crawl-delay), on top of the pacer readers share.
|
| 20 |
+
Work stops while the breaker is open and at DAILY_MAX papers a day. A file
|
| 21 |
+
lock keeps it to one runner per container. Owned by the app lifespan, like
|
| 22 |
+
DiscoveryRuntime.
|
| 23 |
"""
|
| 24 |
from __future__ import annotations
|
| 25 |
|
|
|
|
| 27 |
import fcntl
|
| 28 |
import os
|
| 29 |
import time
|
| 30 |
+
from collections import deque
|
| 31 |
from pathlib import Path
|
| 32 |
|
| 33 |
from app import config, errors, features, licences, paper_source_svc
|
| 34 |
|
| 35 |
SWITCH = "FIGURE_PREWARM"
|
| 36 |
INTERVAL_S = int(os.getenv("FIGURE_PREWARM_INTERVAL_S", "21600"))
|
| 37 |
+
# At two requests a paper and one per 15 s, 300 papers take about 2.5 hours.
|
| 38 |
+
BATCH = int(os.getenv("FIGURE_PREWARM_BATCH", "300"))
|
| 39 |
+
DAILY_MAX = int(os.getenv("FIGURE_PREWARM_DAILY", "800"))
|
| 40 |
+
QUEUE_MAX = 300
|
| 41 |
+
SEARCH_TOP = 5
|
| 42 |
FIRST_RUN_DELAY_S = int(os.getenv("FIGURE_PREWARM_FIRST_DELAY_S", "120"))
|
| 43 |
LOCK_PATH = Path(os.getenv("FIGURE_PREWARM_LOCK", "/tmp/researchit-figure-prewarm.lock"))
|
| 44 |
|
| 45 |
_state: dict = {"scheduler": "off", "last_run": None, "next_run": None,
|
| 46 |
"done": 0, "skipped": 0, "failed": 0, "stopped_by_breaker": False}
|
| 47 |
_task: asyncio.Task | None = None
|
| 48 |
+
_drain_task: asyncio.Task | None = None
|
| 49 |
_lock_handle = None
|
| 50 |
+
_queue: deque[str] = deque()
|
| 51 |
+
_queued: set[str] = set()
|
| 52 |
+
_wake: asyncio.Event | None = None
|
| 53 |
+
_day = {"date": "", "read": 0, "shown_done": 0}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _today() -> str:
|
| 57 |
+
return time.strftime("%Y-%m-%d", time.gmtime())
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _budget_left() -> bool:
|
| 61 |
+
if _day["date"] != _today():
|
| 62 |
+
_day.update(date=_today(), read=0, shown_done=0)
|
| 63 |
+
return _day["read"] < DAILY_MAX
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def enqueue(arxiv_ids: list[str]) -> int:
|
| 67 |
+
"""Queue papers people were just shown, for reading in the background.
|
| 68 |
+
|
| 69 |
+
Cheap and synchronous, safe to call from a request handler. Papers already
|
| 70 |
+
queued are skipped; past QUEUE_MAX the oldest are dropped, since the newest
|
| 71 |
+
are the likeliest to be shown again. Returns how many were added.
|
| 72 |
+
"""
|
| 73 |
+
if features.mode(SWITCH) != "on":
|
| 74 |
+
return 0
|
| 75 |
+
added = 0
|
| 76 |
+
for aid in arxiv_ids:
|
| 77 |
+
if not paper_source_svc.ID_PATTERN.match(aid or "") or aid in _queued:
|
| 78 |
+
continue
|
| 79 |
+
if len(_queue) >= QUEUE_MAX:
|
| 80 |
+
_queued.discard(_queue.popleft())
|
| 81 |
+
_queue.append(aid)
|
| 82 |
+
_queued.add(aid)
|
| 83 |
+
added += 1
|
| 84 |
+
if added and _wake is not None:
|
| 85 |
+
_wake.set()
|
| 86 |
+
return added
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
async def warm(arxiv_id: str) -> str:
|
| 90 |
+
"""Read one paper and prepare its first figure: done, skipped or failed."""
|
| 91 |
+
saved = await paper_source_svc.get(arxiv_id)
|
| 92 |
+
if paper_source_svc.needs_fetch(saved):
|
| 93 |
+
if not _budget_left():
|
| 94 |
+
return "skipped"
|
| 95 |
+
_day["read"] += 1
|
| 96 |
+
source = await paper_source_svc.ensure(arxiv_id, background=True)
|
| 97 |
+
else:
|
| 98 |
+
source = saved
|
| 99 |
+
if source is None or not source.ok:
|
| 100 |
+
return "failed" if source is None else "skipped"
|
| 101 |
+
if features.active("FIGURES"):
|
| 102 |
+
await _thumbnail(source)
|
| 103 |
+
return "done"
|
| 104 |
|
| 105 |
|
| 106 |
async def recent_ids(days: int = 2) -> list[tuple[str, str]]:
|
|
|
|
| 124 |
from app.routers import figures
|
| 125 |
for n in range(len(source.figures)):
|
| 126 |
if figures.figure_url(source, n):
|
| 127 |
+
return await figures.prepare(source, n, background=True)
|
| 128 |
return False
|
| 129 |
|
| 130 |
|
|
|
|
| 142 |
if paper_source_svc.breaker_open():
|
| 143 |
counts["stopped_by_breaker"] = True
|
| 144 |
break
|
| 145 |
+
if not _budget_left():
|
| 146 |
+
break
|
| 147 |
try:
|
| 148 |
+
result = await warm(arxiv_id)
|
| 149 |
+
counts["done" if result == "done" else "failed" if result == "failed" else "skipped"] += 1
|
|
|
|
|
|
|
| 150 |
except Exception as e: # one paper never stops the run
|
| 151 |
counts["failed"] += 1
|
| 152 |
errors.report("figure_prewarm", f"warming {arxiv_id} failed", e)
|
| 153 |
return counts
|
| 154 |
|
| 155 |
|
| 156 |
+
async def _drain() -> None:
|
| 157 |
+
"""Read queued papers one at a time, for as long as the app runs."""
|
| 158 |
+
while True:
|
| 159 |
+
if not _queue:
|
| 160 |
+
_wake.clear()
|
| 161 |
+
await _wake.wait()
|
| 162 |
+
continue
|
| 163 |
+
if paper_source_svc.breaker_open() or not _budget_left():
|
| 164 |
+
await asyncio.sleep(60)
|
| 165 |
+
continue
|
| 166 |
+
arxiv_id = _queue.popleft()
|
| 167 |
+
_queued.discard(arxiv_id)
|
| 168 |
+
try:
|
| 169 |
+
if await warm(arxiv_id) == "done":
|
| 170 |
+
_day["shown_done"] += 1
|
| 171 |
+
except Exception as e: # one paper never stops the queue
|
| 172 |
+
errors.report("figure_prewarm", f"warming {arxiv_id} failed", e)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
async def _loop() -> None:
|
| 176 |
await asyncio.sleep(FIRST_RUN_DELAY_S)
|
| 177 |
while True:
|
|
|
|
| 200 |
|
| 201 |
|
| 202 |
async def start() -> None:
|
| 203 |
+
global _task, _drain_task, _wake
|
| 204 |
if features.mode(SWITCH) != "on" or _task is not None:
|
| 205 |
return
|
| 206 |
if not _take_lock():
|
| 207 |
_state["scheduler"] = "blocked: another runner holds the lock"
|
| 208 |
return
|
| 209 |
_state["scheduler"] = "starting"
|
| 210 |
+
_wake = asyncio.Event()
|
| 211 |
+
if _queue:
|
| 212 |
+
_wake.set()
|
| 213 |
_task = asyncio.create_task(_loop(), name="figure-prewarm")
|
| 214 |
+
_drain_task = asyncio.create_task(_drain(), name="figure-prewarm-shown")
|
| 215 |
|
| 216 |
|
| 217 |
async def stop() -> None:
|
| 218 |
+
global _task, _drain_task, _lock_handle, _wake
|
| 219 |
+
for task in (_task, _drain_task):
|
| 220 |
+
if task is not None:
|
| 221 |
+
task.cancel()
|
| 222 |
+
try:
|
| 223 |
+
await task
|
| 224 |
+
except (asyncio.CancelledError, Exception):
|
| 225 |
+
pass
|
| 226 |
+
_task = _drain_task = _wake = None
|
| 227 |
if _lock_handle is not None:
|
| 228 |
try:
|
| 229 |
fcntl.flock(_lock_handle, fcntl.LOCK_UN)
|
|
|
|
| 235 |
|
| 236 |
|
| 237 |
def status() -> dict:
|
| 238 |
+
_budget_left()
|
| 239 |
+
return {"switch": features.mode(SWITCH), "interval_s": INTERVAL_S, "batch": BATCH, **_state,
|
| 240 |
+
"background_every_s": paper_source_svc.BACKGROUND_INTERVAL_S, "queued": len(_queue),
|
| 241 |
+
"read_today": _day["read"], "daily_max": DAILY_MAX, "shown_warmed_today": _day["shown_done"]}
|
app/paper_source_svc.py
CHANGED
|
@@ -57,6 +57,11 @@ PRUNE_EVERY_S = 24 * 3600
|
|
| 57 |
|
| 58 |
PACE_INTERVAL_S = 2.0
|
| 59 |
PACE_BURST = 3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
SOFT_BLOCK = (403, 406, 429, 503)
|
| 61 |
BREAKER_THRESHOLD = 3
|
| 62 |
BREAKER_WINDOW_S = 600.0
|
|
@@ -182,6 +187,8 @@ class _State:
|
|
| 182 |
self.pace_lock = asyncio.Lock()
|
| 183 |
self.tokens = float(PACE_BURST)
|
| 184 |
self.token_time = _now()
|
|
|
|
|
|
|
| 185 |
self.soft_blocks: deque[float] = deque()
|
| 186 |
self.breaker_until = 0.0
|
| 187 |
self.tasks: set[asyncio.Task] = set()
|
|
@@ -205,9 +212,26 @@ def breaker_open() -> bool:
|
|
| 205 |
return bool(st and st.breaker_until > _now())
|
| 206 |
|
| 207 |
|
| 208 |
-
async def pace() -> bool:
|
| 209 |
-
"""Wait for a turn to call arXiv. False when the breaker is open.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
st = _get_state()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
async with st.pace_lock:
|
| 212 |
if st.breaker_until > _now():
|
| 213 |
return False
|
|
@@ -352,9 +376,9 @@ async def _save_status(arxiv_id: str, status: str, error: str, keep: Source | No
|
|
| 352 |
await conn.commit()
|
| 353 |
|
| 354 |
|
| 355 |
-
async def _fetch_and_save(arxiv_id: str, existing: Source | None) -> Source | None:
|
| 356 |
st = _get_state()
|
| 357 |
-
if not await pace():
|
| 358 |
runtime_stats.count("paper_source_breaker_skip")
|
| 359 |
return existing
|
| 360 |
t0 = time.perf_counter()
|
|
@@ -392,11 +416,18 @@ async def _fetch_and_save(arxiv_id: str, existing: Source | None) -> Source | No
|
|
| 392 |
return await get(arxiv_id)
|
| 393 |
|
| 394 |
|
| 395 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
"""The saved source, fetching it first if needed. Never raises.
|
| 397 |
|
| 398 |
Callers pass ids they found in our metadata; anything that isn't a
|
| 399 |
-
new-style arXiv id is refused before any request.
|
|
|
|
|
|
|
| 400 |
"""
|
| 401 |
if not ID_PATTERN.match(arxiv_id or ""):
|
| 402 |
return None
|
|
@@ -405,13 +436,22 @@ async def ensure(arxiv_id: str, *, force: bool = False) -> Source | None:
|
|
| 405 |
if not force and _fresh(existing, time.time()):
|
| 406 |
return existing
|
| 407 |
st = _get_state()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
fut = st.in_flight.get(arxiv_id)
|
| 409 |
if fut is not None:
|
| 410 |
return await asyncio.shield(fut)
|
| 411 |
fut = st.loop.create_future()
|
| 412 |
st.in_flight[arxiv_id] = fut
|
| 413 |
try:
|
| 414 |
-
result = await _fetch_and_save(arxiv_id, existing)
|
| 415 |
except Exception as e:
|
| 416 |
errors.report("paper_source_svc", f"fetching {arxiv_id} failed", e)
|
| 417 |
result = existing
|
|
|
|
| 57 |
|
| 58 |
PACE_INTERVAL_S = 2.0
|
| 59 |
PACE_BURST = 3
|
| 60 |
+
# Work nobody is waiting for (the figure warm-up) also waits this long after
|
| 61 |
+
# the previous background request: arXiv's robots.txt asks automated clients
|
| 62 |
+
# for "Crawl-delay: 15", and its bulk-data page puts interactive use by people
|
| 63 |
+
# first. Reader-triggered fetches stand in for that reader's own browser.
|
| 64 |
+
BACKGROUND_INTERVAL_S = 15.0
|
| 65 |
SOFT_BLOCK = (403, 406, 429, 503)
|
| 66 |
BREAKER_THRESHOLD = 3
|
| 67 |
BREAKER_WINDOW_S = 600.0
|
|
|
|
| 187 |
self.pace_lock = asyncio.Lock()
|
| 188 |
self.tokens = float(PACE_BURST)
|
| 189 |
self.token_time = _now()
|
| 190 |
+
self.background_lock = asyncio.Lock()
|
| 191 |
+
self.background_at = float("-inf")
|
| 192 |
self.soft_blocks: deque[float] = deque()
|
| 193 |
self.breaker_until = 0.0
|
| 194 |
self.tasks: set[asyncio.Task] = set()
|
|
|
|
| 212 |
return bool(st and st.breaker_until > _now())
|
| 213 |
|
| 214 |
|
| 215 |
+
async def pace(background: bool = False) -> bool:
|
| 216 |
+
"""Wait for a turn to call arXiv. False when the breaker is open.
|
| 217 |
+
|
| 218 |
+
Every request takes a token from one bucket (PACE_BURST, refilling one per
|
| 219 |
+
PACE_INTERVAL_S). A background request first waits for its own slot,
|
| 220 |
+
BACKGROUND_INTERVAL_S after the previous one, so background work can never
|
| 221 |
+
use more than one request in 15 seconds, however much is queued.
|
| 222 |
+
"""
|
| 223 |
st = _get_state()
|
| 224 |
+
if background:
|
| 225 |
+
async with st.background_lock:
|
| 226 |
+
wait = st.background_at + BACKGROUND_INTERVAL_S - _now()
|
| 227 |
+
if wait > 0:
|
| 228 |
+
await _sleep(wait)
|
| 229 |
+
st.background_at = _now()
|
| 230 |
+
return await _token(st)
|
| 231 |
+
return await _token(st)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
async def _token(st: _State) -> bool:
|
| 235 |
async with st.pace_lock:
|
| 236 |
if st.breaker_until > _now():
|
| 237 |
return False
|
|
|
|
| 376 |
await conn.commit()
|
| 377 |
|
| 378 |
|
| 379 |
+
async def _fetch_and_save(arxiv_id: str, existing: Source | None, paced: bool = False) -> Source | None:
|
| 380 |
st = _get_state()
|
| 381 |
+
if not paced and not await pace():
|
| 382 |
runtime_stats.count("paper_source_breaker_skip")
|
| 383 |
return existing
|
| 384 |
t0 = time.perf_counter()
|
|
|
|
| 416 |
return await get(arxiv_id)
|
| 417 |
|
| 418 |
|
| 419 |
+
def needs_fetch(src: Source | None) -> bool:
|
| 420 |
+
"""True when ensure() would go to arXiv for this saved row (or its absence)."""
|
| 421 |
+
return not _fresh(src, time.time())
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
async def ensure(arxiv_id: str, *, force: bool = False, background: bool = False) -> Source | None:
|
| 425 |
"""The saved source, fetching it first if needed. Never raises.
|
| 426 |
|
| 427 |
Callers pass ids they found in our metadata; anything that isn't a
|
| 428 |
+
new-style arXiv id is refused before any request. With background=True the
|
| 429 |
+
fetch waits for a background slot (pace) before it claims the paper, so a
|
| 430 |
+
reader opening the same paper meanwhile is never queued behind it.
|
| 431 |
"""
|
| 432 |
if not ID_PATTERN.match(arxiv_id or ""):
|
| 433 |
return None
|
|
|
|
| 436 |
if not force and _fresh(existing, time.time()):
|
| 437 |
return existing
|
| 438 |
st = _get_state()
|
| 439 |
+
if background:
|
| 440 |
+
if st.in_flight.get(arxiv_id) is not None:
|
| 441 |
+
return existing # a reader is already fetching it
|
| 442 |
+
if not await pace(background=True):
|
| 443 |
+
runtime_stats.count("paper_source_breaker_skip")
|
| 444 |
+
return existing
|
| 445 |
+
existing = await get(arxiv_id) # a reader may have fetched it while we waited
|
| 446 |
+
if (not force and _fresh(existing, time.time())) or st.in_flight.get(arxiv_id) is not None:
|
| 447 |
+
return existing
|
| 448 |
fut = st.in_flight.get(arxiv_id)
|
| 449 |
if fut is not None:
|
| 450 |
return await asyncio.shield(fut)
|
| 451 |
fut = st.loop.create_future()
|
| 452 |
st.in_flight[arxiv_id] = fut
|
| 453 |
try:
|
| 454 |
+
result = await _fetch_and_save(arxiv_id, existing, paced=background)
|
| 455 |
except Exception as e:
|
| 456 |
errors.report("paper_source_svc", f"fetching {arxiv_id} failed", e)
|
| 457 |
result = existing
|
app/routers/figures.py
CHANGED
|
@@ -199,10 +199,10 @@ async def _download(src: str, accept: str = "image/", cap: int = MAX_IMAGE_BYTES
|
|
| 199 |
return resp.status_code, bytes(body), ctype
|
| 200 |
|
| 201 |
|
| 202 |
-
async def _generate(arxiv_id: str, src: str, path: Path, kind: str = "img") -> bytes | None:
|
| 203 |
st = _get_state()
|
| 204 |
marker = path.with_suffix(".fail")
|
| 205 |
-
if not await paper_source_svc.pace():
|
| 206 |
return None # breaker open: try again later
|
| 207 |
try:
|
| 208 |
status, raw, ctype = await _download(src)
|
|
@@ -249,13 +249,13 @@ def _drawings(html: bytes, anchors: list[str]) -> dict[str, bytes | str]:
|
|
| 249 |
return out
|
| 250 |
|
| 251 |
|
| 252 |
-
async def _generate_inline(source, src: str) -> None:
|
| 253 |
"""Every drawing of a paper from one fetch of its page, written to the cache."""
|
| 254 |
st = _get_state()
|
| 255 |
wanted = {f["anchor"]: _cache_path(source.arxiv_id, f"{i}-{path_hash(figure_key(f))}.svg")
|
| 256 |
for i, f in enumerate(source.figures)
|
| 257 |
if figure_kind(f) == "svg-inline" and f.get("src") == src and f.get("anchor")}
|
| 258 |
-
if not wanted or not await paper_source_svc.pace():
|
| 259 |
return
|
| 260 |
try:
|
| 261 |
status, raw, ctype = await _download(src, accept="text/html", cap=arxiv_html.MAX_HTML_BYTES)
|
|
@@ -279,8 +279,11 @@ async def _generate_inline(source, src: str) -> None:
|
|
| 279 |
runtime_stats.count("figure_failed")
|
| 280 |
|
| 281 |
|
| 282 |
-
async def thumbnail(arxiv_id: str, n: int, h8: str, ext: str = "webp"
|
| 283 |
-
|
|
|
|
|
|
|
|
|
|
| 284 |
if not paper_source_svc.ID_PATTERN.match(arxiv_id):
|
| 285 |
return None, None
|
| 286 |
source = await paper_source_svc.get(arxiv_id)
|
|
@@ -309,10 +312,10 @@ async def thumbnail(arxiv_id: str, n: int, h8: str, ext: str = "webp") -> tuple[
|
|
| 309 |
data = None
|
| 310 |
try:
|
| 311 |
if kind == "svg-inline":
|
| 312 |
-
await _generate_inline(source, src)
|
| 313 |
data = path.read_bytes() if path.exists() else None
|
| 314 |
else:
|
| 315 |
-
data = await _generate(arxiv_id, src, path, kind)
|
| 316 |
except Exception as e:
|
| 317 |
errors.report("figures", f"thumbnail {key} failed", e)
|
| 318 |
finally:
|
|
@@ -337,11 +340,21 @@ async def figure(arxiv_id: str, name: str, request: Request):
|
|
| 337 |
return Response(status_code=404)
|
| 338 |
|
| 339 |
|
| 340 |
-
async def prepare(source, n: int) -> bool:
|
| 341 |
-
"""Make figure n ready in the cache, as a page request for it would.
|
|
|
|
|
|
|
|
|
|
| 342 |
url = figure_url(source, n)
|
| 343 |
m = _NAME.match(url.rsplit("/", 1)[1]) if url else None
|
| 344 |
if m is None:
|
| 345 |
return False
|
| 346 |
-
path
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
return resp.status_code, bytes(body), ctype
|
| 200 |
|
| 201 |
|
| 202 |
+
async def _generate(arxiv_id: str, src: str, path: Path, kind: str = "img", paced: bool = False) -> bytes | None:
|
| 203 |
st = _get_state()
|
| 204 |
marker = path.with_suffix(".fail")
|
| 205 |
+
if not paced and not await paper_source_svc.pace():
|
| 206 |
return None # breaker open: try again later
|
| 207 |
try:
|
| 208 |
status, raw, ctype = await _download(src)
|
|
|
|
| 249 |
return out
|
| 250 |
|
| 251 |
|
| 252 |
+
async def _generate_inline(source, src: str, paced: bool = False) -> None:
|
| 253 |
"""Every drawing of a paper from one fetch of its page, written to the cache."""
|
| 254 |
st = _get_state()
|
| 255 |
wanted = {f["anchor"]: _cache_path(source.arxiv_id, f"{i}-{path_hash(figure_key(f))}.svg")
|
| 256 |
for i, f in enumerate(source.figures)
|
| 257 |
if figure_kind(f) == "svg-inline" and f.get("src") == src and f.get("anchor")}
|
| 258 |
+
if not wanted or (not paced and not await paper_source_svc.pace()):
|
| 259 |
return
|
| 260 |
try:
|
| 261 |
status, raw, ctype = await _download(src, accept="text/html", cap=arxiv_html.MAX_HTML_BYTES)
|
|
|
|
| 279 |
runtime_stats.count("figure_failed")
|
| 280 |
|
| 281 |
|
| 282 |
+
async def thumbnail(arxiv_id: str, n: int, h8: str, ext: str = "webp",
|
| 283 |
+
paced: bool = False) -> tuple[Path | None, bytes | None]:
|
| 284 |
+
"""(cached file, or freshly made bytes) for a figure, or (None, None).
|
| 285 |
+
|
| 286 |
+
paced=True: the caller already waited for its turn (a background slot)."""
|
| 287 |
if not paper_source_svc.ID_PATTERN.match(arxiv_id):
|
| 288 |
return None, None
|
| 289 |
source = await paper_source_svc.get(arxiv_id)
|
|
|
|
| 312 |
data = None
|
| 313 |
try:
|
| 314 |
if kind == "svg-inline":
|
| 315 |
+
await _generate_inline(source, src, paced)
|
| 316 |
data = path.read_bytes() if path.exists() else None
|
| 317 |
else:
|
| 318 |
+
data = await _generate(arxiv_id, src, path, kind, paced)
|
| 319 |
except Exception as e:
|
| 320 |
errors.report("figures", f"thumbnail {key} failed", e)
|
| 321 |
finally:
|
|
|
|
| 340 |
return Response(status_code=404)
|
| 341 |
|
| 342 |
|
| 343 |
+
async def prepare(source, n: int, background: bool = False) -> bool:
|
| 344 |
+
"""Make figure n ready in the cache, as a page request for it would.
|
| 345 |
+
|
| 346 |
+
background=True (the warm-up) waits for a background slot first, and only
|
| 347 |
+
when there is something to fetch, so a cached figure costs no slot."""
|
| 348 |
url = figure_url(source, n)
|
| 349 |
m = _NAME.match(url.rsplit("/", 1)[1]) if url else None
|
| 350 |
if m is None:
|
| 351 |
return False
|
| 352 |
+
path = _cache_path(source.arxiv_id, m.group(0))
|
| 353 |
+
if path.exists():
|
| 354 |
+
return True
|
| 355 |
+
if _failed_recently(path.with_suffix(".fail")):
|
| 356 |
+
return False
|
| 357 |
+
if background and not await paper_source_svc.pace(background=True):
|
| 358 |
+
return False
|
| 359 |
+
made, data = await thumbnail(source.arxiv_id, int(m.group(1)), m.group(2), m.group(3), paced=background)
|
| 360 |
+
return bool(made or data)
|
app/routers/recommendations.py
CHANGED
|
@@ -25,7 +25,7 @@ from collections import OrderedDict
|
|
| 25 |
import numpy as np
|
| 26 |
from fastapi import APIRouter, Request, Cookie
|
| 27 |
from fastapi.responses import HTMLResponse
|
| 28 |
-
from app import card_data, db, discovery_svc, errors, features, qdrant_svc, arxiv_svc, runtime_stats, turso_svc, user_state as us
|
| 29 |
from app.config import (
|
| 30 |
COOKIE_NAME, REC_LIMIT, REC_MIN_POSITIVES, CLUSTER_POSITIVE_LIMIT,
|
| 31 |
DEFAULT_TRENDING_CATEGORIES,
|
|
@@ -376,6 +376,9 @@ async def _serve_recommendations(
|
|
| 376 |
card_v2 = features.visible("FEED_CARD_V2", request)
|
| 377 |
if card_v2:
|
| 378 |
papers = await card_data.enrich(papers, request)
|
|
|
|
|
|
|
|
|
|
| 379 |
|
| 380 |
ctx = {
|
| 381 |
"card_v2": card_v2,
|
|
|
|
| 25 |
import numpy as np
|
| 26 |
from fastapi import APIRouter, Request, Cookie
|
| 27 |
from fastapi.responses import HTMLResponse
|
| 28 |
+
from app import card_data, db, discovery_svc, errors, features, figure_prewarm, qdrant_svc, arxiv_svc, runtime_stats, turso_svc, user_state as us
|
| 29 |
from app.config import (
|
| 30 |
COOKIE_NAME, REC_LIMIT, REC_MIN_POSITIVES, CLUSTER_POSITIVE_LIMIT,
|
| 31 |
DEFAULT_TRENDING_CATEGORIES,
|
|
|
|
| 376 |
card_v2 = features.visible("FEED_CARD_V2", request)
|
| 377 |
if card_v2:
|
| 378 |
papers = await card_data.enrich(papers, request)
|
| 379 |
+
# Cards only show figures already saved; queue this page's papers so the
|
| 380 |
+
# warm-up reads them (slowly, in the background) for next time.
|
| 381 |
+
figure_prewarm.enqueue([p["arxiv_id"] for p in papers if p.get("arxiv_id")])
|
| 382 |
|
| 383 |
ctx = {
|
| 384 |
"card_v2": card_v2,
|
app/routers/search.py
CHANGED
|
@@ -14,7 +14,7 @@ Phase 3.5: Metadata now fetched from Turso cloud DB (fast, includes citations)
|
|
| 14 |
import uuid
|
| 15 |
from fastapi import APIRouter, Request, Cookie
|
| 16 |
from fastapi.responses import HTMLResponse
|
| 17 |
-
from app import arxiv_svc, db, turso_svc, user_state as us, hybrid_search_svc
|
| 18 |
from app.config import COOKIE_NAME, ARXIV_MAX_RESULTS
|
| 19 |
from app.templates_env import templates
|
| 20 |
|
|
@@ -98,6 +98,13 @@ async def search(
|
|
| 98 |
p["propensity"] = 1.0 # search is deterministic
|
| 99 |
p["policy_id"] = "search_v2_independent_lexical"
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
if request.headers.get("HX-Request"):
|
| 102 |
resp = templates.TemplateResponse(
|
| 103 |
request,
|
|
|
|
| 14 |
import uuid
|
| 15 |
from fastapi import APIRouter, Request, Cookie
|
| 16 |
from fastapi.responses import HTMLResponse
|
| 17 |
+
from app import arxiv_svc, card_data, db, features, figure_prewarm, turso_svc, user_state as us, hybrid_search_svc
|
| 18 |
from app.config import COOKIE_NAME, ARXIV_MAX_RESULTS
|
| 19 |
from app.templates_env import templates
|
| 20 |
|
|
|
|
| 98 |
p["propensity"] = 1.0 # search is deterministic
|
| 99 |
p["policy_id"] = "search_v2_independent_lexical"
|
| 100 |
|
| 101 |
+
# A small figure beside each result that already has one saved (switch
|
| 102 |
+
# SEARCH_FIGURES; local reads only, order and instrumentation untouched),
|
| 103 |
+
# and the top few queued so the warm-up reads them for next time.
|
| 104 |
+
if features.visible("SEARCH_FIGURES", request):
|
| 105 |
+
papers = await card_data.enrich(papers, request)
|
| 106 |
+
figure_prewarm.enqueue([p["arxiv_id"] for p in papers[:figure_prewarm.SEARCH_TOP] if p.get("arxiv_id")])
|
| 107 |
+
|
| 108 |
if request.headers.get("HX-Request"):
|
| 109 |
resp = templates.TemplateResponse(
|
| 110 |
request,
|
app/static/app.js
CHANGED
|
@@ -441,13 +441,14 @@
|
|
| 441 |
/* ββ Figures that cannot be shown ββ
|
| 442 |
/fig/ answers 404 when a thumbnail cannot be made (too large, not an
|
| 443 |
image, arXiv refused). Hide that figure rather than leave a broken box:
|
| 444 |
-
its card figure, the key-figure section, or its tile
|
| 445 |
-
that section too once no tile is left). Error events
|
| 446 |
-
this listens in the capture phase; this script runs at
|
| 447 |
-
page, so images that failed before it ran are swept up
|
|
|
|
| 448 |
function hideFigure(img) {
|
| 449 |
if (!img || img.tagName !== 'IMG' || (img.getAttribute('src') || '').indexOf('/fig/') !== 0) return;
|
| 450 |
-
var box = img.closest('.pc-fig, #sec-fig, .figs > button');
|
| 451 |
if (!box) return;
|
| 452 |
box.hidden = true;
|
| 453 |
var grid = box.parentNode && box.parentNode.classList.contains('figs') ? box.parentNode : null;
|
|
|
|
| 441 |
/* ββ Figures that cannot be shown ββ
|
| 442 |
/fig/ answers 404 when a thumbnail cannot be made (too large, not an
|
| 443 |
image, arXiv refused). Hide that figure rather than leave a broken box:
|
| 444 |
+
its card figure or search thumbnail, the key-figure section, or its tile
|
| 445 |
+
in All figures (and that section too once no tile is left). Error events
|
| 446 |
+
do not bubble, so this listens in the capture phase; this script runs at
|
| 447 |
+
the end of the page, so images that failed before it ran are swept up
|
| 448 |
+
once. */
|
| 449 |
function hideFigure(img) {
|
| 450 |
if (!img || img.tagName !== 'IMG' || (img.getAttribute('src') || '').indexOf('/fig/') !== 0) return;
|
| 451 |
+
var box = img.closest('.pc-fig, .card-thumb, #sec-fig, .figs > button');
|
| 452 |
if (!box) return;
|
| 453 |
box.hidden = true;
|
| 454 |
var grid = box.parentNode && box.parentNode.classList.contains('figs') ? box.parentNode : null;
|
app/static/styles.css
CHANGED
|
@@ -1726,6 +1726,20 @@ a.src:hover { text-decoration: underline; }
|
|
| 1726 |
.pc-actions .card-why { display: none; }
|
| 1727 |
.pc .card-reason { margin: 0; }
|
| 1728 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1729 |
/* ββ wide feed (FEED_WIDE): rail + two columns, served order kept ββββββββββ
|
| 1730 |
The feed stays ONE list in served order (quota interleaves interests, Β§3.1).
|
| 1731 |
CSS columns would fill the left column top to bottom and undo that, and two
|
|
|
|
| 1726 |
.pc-actions .card-why { display: none; }
|
| 1727 |
.pc .card-reason { margin: 0; }
|
| 1728 |
|
| 1729 |
+
/* ββ search thumbnails (SEARCH_FIGURES): a small figure beside the text ββ
|
| 1730 |
+
Search is for scanning titles, so the figure stays small and to the side;
|
| 1731 |
+
the feed card is where figures are large. */
|
| 1732 |
+
.card-split { display: grid; grid-template-columns: minmax(0, 1fr) 7.5rem; column-gap: 1rem; align-items: start; }
|
| 1733 |
+
.card-main { display: flex; flex-direction: column; gap: .55rem; min-width: 0; }
|
| 1734 |
+
.card-thumb { display: block; margin-top: .2rem; }
|
| 1735 |
+
.card-thumb .plate { padding: .25rem; }
|
| 1736 |
+
.card-thumb .plate img { aspect-ratio: 4 / 3; max-height: 6rem; }
|
| 1737 |
+
.card-split:has(> .card-thumb[hidden]) { grid-template-columns: minmax(0, 1fr); }
|
| 1738 |
+
@media (max-width: 560px) {
|
| 1739 |
+
.card-split { grid-template-columns: minmax(0, 1fr) 4.75rem; column-gap: .75rem; }
|
| 1740 |
+
.card-thumb .plate img { max-height: 3.75rem; }
|
| 1741 |
+
}
|
| 1742 |
+
|
| 1743 |
/* ββ wide feed (FEED_WIDE): rail + two columns, served order kept ββββββββββ
|
| 1744 |
The feed stays ONE list in served order (quota interleaves interests, Β§3.1).
|
| 1745 |
CSS columns would fill the left column top to bottom and undo that, and two
|
app/templates/partials/paper_card.html
CHANGED
|
@@ -101,6 +101,15 @@
|
|
| 101 |
{%- if paper.candidate_source %}{% set _ = _q.append("src=" ~ paper.candidate_source) %}{% endif -%}
|
| 102 |
{%- if paper.propensity %}{% set _ = _q.append("prop=" ~ paper.propensity) %}{% endif -%}
|
| 103 |
{%- if paper.policy_id %}{% set _ = _q.append("pol=" ~ paper.policy_id) %}{% endif -%}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
<a class="card-title"
|
| 105 |
href="/p/{{ paper.arxiv_id }}{% if _q %}?{{ _q | join('&') }}{% endif %}">{{ paper.title }}</a>
|
| 106 |
|
|
@@ -142,6 +151,16 @@
|
|
| 142 |
target="_blank" rel="noopener">Full abstract on arXiv β</a>
|
| 143 |
{% endif %}
|
| 144 |
{% endif %}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
{# Provenance line. The arXiv id is set as a catalogue number because it is
|
| 147 |
the thing a researcher actually copies, cites and searches for. #}
|
|
|
|
| 101 |
{%- if paper.candidate_source %}{% set _ = _q.append("src=" ~ paper.candidate_source) %}{% endif -%}
|
| 102 |
{%- if paper.propensity %}{% set _ = _q.append("prop=" ~ paper.propensity) %}{% endif -%}
|
| 103 |
{%- if paper.policy_id %}{% set _ = _q.append("pol=" ~ paper.policy_id) %}{% endif -%}
|
| 104 |
+
{#
|
| 105 |
+
A small figure beside the text, only where the caller enriched the paper
|
| 106 |
+
(search, switch SEARCH_FIGURES, via card_data) and a figure is saved.
|
| 107 |
+
Without one the markup is exactly as before. The thumbnail repeats the
|
| 108 |
+
title's link, so it is left out of the tab order and hidden from screen
|
| 109 |
+
readers; its credit is in the title attribute and on the paper page.
|
| 110 |
+
#}
|
| 111 |
+
{% set thumb = paper.card_figure if paper.card_figure is defined else none %}
|
| 112 |
+
{% if thumb %}<div class="card-split"><div class="card-main">{% endif %}
|
| 113 |
<a class="card-title"
|
| 114 |
href="/p/{{ paper.arxiv_id }}{% if _q %}?{{ _q | join('&') }}{% endif %}">{{ paper.title }}</a>
|
| 115 |
|
|
|
|
| 151 |
target="_blank" rel="noopener">Full abstract on arXiv β</a>
|
| 152 |
{% endif %}
|
| 153 |
{% endif %}
|
| 154 |
+
{% if thumb %}
|
| 155 |
+
</div>
|
| 156 |
+
<a class="card-thumb" href="/p/{{ paper.arxiv_id }}{% if _q %}?{{ _q | join('&') }}{% endif %}#sec-fig"
|
| 157 |
+
tabindex="-1" aria-hidden="true"
|
| 158 |
+
title="{{ thumb.label }}{% if thumb.label and thumb.credit %} Β· {% endif %}{{ thumb.credit }}">
|
| 159 |
+
<span class="plate"><img src="{{ thumb.url }}" alt="" loading="lazy" decoding="async"
|
| 160 |
+
{% if thumb.w and thumb.h %}width="{{ thumb.w }}" height="{{ thumb.h }}"{% endif %}></span>
|
| 161 |
+
</a>
|
| 162 |
+
</div>
|
| 163 |
+
{% endif %}
|
| 164 |
|
| 165 |
{# Provenance line. The arXiv id is set as a catalogue number because it is
|
| 166 |
the thing a researcher actually copies, cites and searches for. #}
|
docs/CURRENT-STATE.md
CHANGED
|
@@ -35,7 +35,7 @@ and deployed. Never copy old corpus counts or benchmark results into current cla
|
|
| 35 |
| Attribution | Ranked visits are clicks with origin fields; direct visits are views without fabricated policy/propensity. Card links carry their surface (`sf=search`, `recommendation`, `saved`) since the card-link fix (branch `fix/click-surface-baseline`); click rows before its deploy say `recommendation` whatever page they came from. Paper-page timings and explanation cache hits/misses appear in `/healthz/runtime`; `scripts/baseline_metrics.py` turns an interactions export into weekly reading metrics | `app/routers/paper.py`, `partials/paper_card.html`, `scripts/baseline_metrics.py` |
|
| 36 |
| Persistence | Local SQLite; periodic Turso replication of four core user tables plus the redesign's paper caches and logs (`paper_explanations`, `paper_abstracts`, `paper_sources`, `paper_briefings`, `paper_answers`, `llm_calls`, `content_reports`), which use an AUTOINCREMENT `id` watermark and restore in pages of 2,000 | `app/turso_sync.py:TABLES` |
|
| 37 |
| Full abstracts | Behind `FULL_ABSTRACTS` (off by default). A paper whose stored abstract is cut at 500 characters is queued on first open; the arXiv API is called with up to 20 ids at least 3.1 s apart, honouring Retry-After, up to `FULL_ABSTRACTS_DAILY_CAP` ids a day. Saved abstracts replace stumps on the paper page and in `/explain`; queue state is in `/healthz/runtime` | `app/abstract_svc.py`, `app/routers/paper.py` |
|
| 38 |
-
| Paper sources | Behind `PAPER_SOURCES` (off, shadow, on). Opening a paper schedules one background fetch of `arxiv.org/html/<id>`; the page is parsed in a thread (standard-library parser) into licence, version, sections, paragraphs and figures. `paper_sources` (replicated, at most
|
| 39 |
| Figure thumbnails | Behind `FIGURES`. `/fig/<id>/<n>-<hash>.webp` serves a saved picture (PNG, JPEG, GIF) as a WebP at most 800 px wide, made with Pillow in a thread; JPEGs decode at reduced scale, so print-resolution exports work. `/fig/<id>/<n>-<hash>.svg` serves a vector figure, an SVG file or a drawing inline in the arXiv page (one page fetch per paper), rebuilt from drawing elements only by `app/svg_clean.py` and served with `Content-Security-Policy: default-src 'none'; β¦; sandbox`. Up to 24 figures per paper. Everything is fetched once from arXiv through the paper-source pacer and cached in `FIG_CACHE_DIR` (wiped on restart, swept to `FIG_CACHE_MAX_MB`). Rate limit 600 a minute per IP. A figure that can't be made is hidden by `app.js`. Every figure shows a credit and licence line | `app/routers/figures.py`, `app/thumbnails.py`, `app/svg_clean.py` |
|
| 40 |
| Paper page v2 | Behind `PAPER_PAGE_V2` (off, preview, on); `paper.html` serves when off. Outline and links, reading column (summary box with In plain terms / Abstract tabs, key figure, all figures, nearby papers), Ask slot. Reads only saved data; the plain summary (`/explain?v=2`), Code chip (`/api/papers/<id>/code`, Hugging Face, cached weekly) and briefing load after paint. KaTeX 0.18.11 vendored under `/static/vendor/`. Static URLs carry `?v=<content hash>`. Browser tests: `tests/test_e2e_paper.py` on the world from `scripts/seed_e2e.py` | `app/templates/paper_v2.html`, `app/static/paper.js`, `app/routers/paper.py` |
|
| 41 |
| Briefing | Behind `BRIEFING` (off, shadow, preview, on). `/api/papers/<id>/briefing` returns three cited points, steps and a use line written by the `GROQ_MODELS` chain from up to 16,000 characters of the paper's passages; points citing an unsent passage or holding a number not in it are dropped. Cached in `paper_briefings` per version, parser, prompt and model. One call at a time, 8 s apart; readers wait at most 12 s. Model calls are logged to `llm_calls` with daily caps. Report a problem goes to `content_reports` | `app/briefing_svc.py`, `app/llm.py`, `scripts/eval_briefings.py` |
|
|
@@ -43,7 +43,8 @@ and deployed. Never copy old corpus counts or benchmark results into current cla
|
|
| 43 |
| Feed card v2 | Behind `FEED_CARD_V2` (off, preview, on); the feed only, every other surface keeps `paper_card.html`. At most eight things to click: menu (Why this paper, 3D, arXiv, copy ID), title, Code chip, first figure, In plain terms / Abstract tabs, Save, Pass. Title link and Save/Pass values identical to today's card (Β§3.11). `card_data.enrich()` adds figure, code link and a cached plain summary from local tables only, after exposures are logged, and never changes order, ids or instrumentation; a summary shows only when cached for the abstract on the card | `partials/paper_card_v2.html`, `app/card_data.py`, `app/routers/recommendations.py` |
|
| 44 |
| Wide feed | Behind `FEED_WIDE` (off, preview, on). From 900 px a rail (issue line, interest filter with counts, Edit interests, Recent papers, which text cards open on); from 1180 px two columns. The feed stays one list in served order: a grid of 4 px rows, each card spanning rows to its height (ResizeObserver), `grid-auto-flow: row`, never dense. The filter hides cards client-side and never refetches. Browser tests: `tests/test_e2e_feed_v2.py` | `app/templates/index.html`, `app/static/app.js`, `app/static/styles.css` |
|
| 45 |
| Layout logging | `interactions.layout` is `list` or `grid2` (anything else stored as NULL) on saves, passes and clicks from cards (`lay=` on title links); replicated, with the remote column added by `REMOTE_COLUMNS` in `ensure_remote_schema`. Feed-control events (`filter_on`, `filter_off`, `cardtext`) go to `ui_events`, which is local and not replicated | `app/db.py`, `app/turso_sync.py`, `app/routers/paper.py` |
|
| 46 |
-
| Figure warm-up | Behind `FIGURE_PREWARM` (off, on).
|
|
|
|
| 47 |
| Feature switches | Redesign features read `off`, `shadow`, `preview` or `on` from Space variables; `preview` shows only to a browser that visited `?preview=<PREVIEW_TOKEN>` | `app/features.py` |
|
| 48 |
| Corpus freshness | 1,853,777 papers through 2026-09-29 (2026-10-01). New papers go to `arxiv_recent` + Turso via `scripts/ingest_arxiv.py` (`--source oai`, arXiv's OAI-PMH feed, for the daily job; `--source search` for backfills), and the OAI path writes each paper's licence to Turso `paper_licences`. The sidecar catches up at the next publish + deploy. A daily job exists (`scripts/daily_refresh.py`, `.github/workflows/daily-refresh.yml`) but is off until `DAILY_REFRESH=on` | PHASE7 Β§8 |
|
| 49 |
| Citations | Semantic Scholar counts for the whole corpus, refreshed 2026-10-01 (99.47% found); the daily job refreshes the last three months | `scripts/refresh_citations.py` |
|
|
|
|
| 35 |
| Attribution | Ranked visits are clicks with origin fields; direct visits are views without fabricated policy/propensity. Card links carry their surface (`sf=search`, `recommendation`, `saved`) since the card-link fix (branch `fix/click-surface-baseline`); click rows before its deploy say `recommendation` whatever page they came from. Paper-page timings and explanation cache hits/misses appear in `/healthz/runtime`; `scripts/baseline_metrics.py` turns an interactions export into weekly reading metrics | `app/routers/paper.py`, `partials/paper_card.html`, `scripts/baseline_metrics.py` |
|
| 36 |
| Persistence | Local SQLite; periodic Turso replication of four core user tables plus the redesign's paper caches and logs (`paper_explanations`, `paper_abstracts`, `paper_sources`, `paper_briefings`, `paper_answers`, `llm_calls`, `content_reports`), which use an AUTOINCREMENT `id` watermark and restore in pages of 2,000 | `app/turso_sync.py:TABLES` |
|
| 37 |
| Full abstracts | Behind `FULL_ABSTRACTS` (off by default). A paper whose stored abstract is cut at 500 characters is queued on first open; the arXiv API is called with up to 20 ids at least 3.1 s apart, honouring Retry-After, up to `FULL_ABSTRACTS_DAILY_CAP` ids a day. Saved abstracts replace stumps on the paper page and in `/explain`; queue state is in `/healthz/runtime` | `app/abstract_svc.py`, `app/routers/paper.py` |
|
| 38 |
+
| Paper sources | Behind `PAPER_SOURCES` (off, shadow, on). Opening a paper schedules one background fetch of `arxiv.org/html/<id>`; the page is parsed in a thread (standard-library parser) into licence, version, sections, paragraphs and figures. `paper_sources` (replicated, at most 24 figures) and local `paper_fulltext`/`paper_paragraphs` (pruned to `FULLTEXT_MAX_PAPERS`). Pacer: 1 request per 2 s, bursts of 3, for fetches a reader triggers; background work (the warm-up) also waits 15 s between its own requests, arXiv's robots.txt `Crawl-delay`. 3 soft blocks in 10 min open a 15-min breaker. Figures show for every licence unless `FIGURE_LICENCES` lists codes. `/healthz/sources` reports coverage | `app/paper_source_svc.py`, `app/arxiv_html.py`, `app/licences.py` |
|
| 39 |
| Figure thumbnails | Behind `FIGURES`. `/fig/<id>/<n>-<hash>.webp` serves a saved picture (PNG, JPEG, GIF) as a WebP at most 800 px wide, made with Pillow in a thread; JPEGs decode at reduced scale, so print-resolution exports work. `/fig/<id>/<n>-<hash>.svg` serves a vector figure, an SVG file or a drawing inline in the arXiv page (one page fetch per paper), rebuilt from drawing elements only by `app/svg_clean.py` and served with `Content-Security-Policy: default-src 'none'; β¦; sandbox`. Up to 24 figures per paper. Everything is fetched once from arXiv through the paper-source pacer and cached in `FIG_CACHE_DIR` (wiped on restart, swept to `FIG_CACHE_MAX_MB`). Rate limit 600 a minute per IP. A figure that can't be made is hidden by `app.js`. Every figure shows a credit and licence line | `app/routers/figures.py`, `app/thumbnails.py`, `app/svg_clean.py` |
|
| 40 |
| Paper page v2 | Behind `PAPER_PAGE_V2` (off, preview, on); `paper.html` serves when off. Outline and links, reading column (summary box with In plain terms / Abstract tabs, key figure, all figures, nearby papers), Ask slot. Reads only saved data; the plain summary (`/explain?v=2`), Code chip (`/api/papers/<id>/code`, Hugging Face, cached weekly) and briefing load after paint. KaTeX 0.18.11 vendored under `/static/vendor/`. Static URLs carry `?v=<content hash>`. Browser tests: `tests/test_e2e_paper.py` on the world from `scripts/seed_e2e.py` | `app/templates/paper_v2.html`, `app/static/paper.js`, `app/routers/paper.py` |
|
| 41 |
| Briefing | Behind `BRIEFING` (off, shadow, preview, on). `/api/papers/<id>/briefing` returns three cited points, steps and a use line written by the `GROQ_MODELS` chain from up to 16,000 characters of the paper's passages; points citing an unsent passage or holding a number not in it are dropped. Cached in `paper_briefings` per version, parser, prompt and model. One call at a time, 8 s apart; readers wait at most 12 s. Model calls are logged to `llm_calls` with daily caps. Report a problem goes to `content_reports` | `app/briefing_svc.py`, `app/llm.py`, `scripts/eval_briefings.py` |
|
|
|
|
| 43 |
| Feed card v2 | Behind `FEED_CARD_V2` (off, preview, on); the feed only, every other surface keeps `paper_card.html`. At most eight things to click: menu (Why this paper, 3D, arXiv, copy ID), title, Code chip, first figure, In plain terms / Abstract tabs, Save, Pass. Title link and Save/Pass values identical to today's card (Β§3.11). `card_data.enrich()` adds figure, code link and a cached plain summary from local tables only, after exposures are logged, and never changes order, ids or instrumentation; a summary shows only when cached for the abstract on the card | `partials/paper_card_v2.html`, `app/card_data.py`, `app/routers/recommendations.py` |
|
| 44 |
| Wide feed | Behind `FEED_WIDE` (off, preview, on). From 900 px a rail (issue line, interest filter with counts, Edit interests, Recent papers, which text cards open on); from 1180 px two columns. The feed stays one list in served order: a grid of 4 px rows, each card spanning rows to its height (ResizeObserver), `grid-auto-flow: row`, never dense. The filter hides cards client-side and never refetches. Browser tests: `tests/test_e2e_feed_v2.py` | `app/templates/index.html`, `app/static/app.js`, `app/static/styles.css` |
|
| 45 |
| Layout logging | `interactions.layout` is `list` or `grid2` (anything else stored as NULL) on saves, passes and clicks from cards (`lay=` on title links); replicated, with the remote column added by `REMOTE_COLUMNS` in `ensure_remote_schema`. Feed-control events (`filter_on`, `filter_off`, `cardtext`) go to `ui_events`, which is local and not replicated | `app/db.py`, `app/turso_sync.py`, `app/routers/paper.py` |
|
| 46 |
+
| Figure warm-up | Behind `FIGURE_PREWARM` (off, on). Reads papers and prepares their first figure before anyone opens them, from two sources: papers people were shown (every feed page and the top 5 search results call `figure_prewarm.enqueue()`; queue of 300, oldest dropped) and, every 6 hours, papers Turso dates in the last 2 days (batches of 300). Every request takes the background lane, one per 15 s at most; 800 papers a day; stops while the breaker is open; one runner per container (file lock). Queue, reads today and the cap in `/healthz/sources` | `app/figure_prewarm.py` |
|
| 47 |
+
| Search thumbnails | Behind `SEARCH_FIGURES` (off, preview, on). A small figure (7.5rem; 4.75rem on a phone) beside a search result whose paper has one saved, via `card_data.enrich()` (local reads only). The classic card's markup is unchanged without a figure. The thumbnail repeats the title's Β§3.11 link with `#sec-fig`, out of the tab order. Browser tests: `tests/test_e2e_search.py` | `partials/paper_card.html`, `app/routers/search.py` |
|
| 48 |
| Feature switches | Redesign features read `off`, `shadow`, `preview` or `on` from Space variables; `preview` shows only to a browser that visited `?preview=<PREVIEW_TOKEN>` | `app/features.py` |
|
| 49 |
| Corpus freshness | 1,853,777 papers through 2026-09-29 (2026-10-01). New papers go to `arxiv_recent` + Turso via `scripts/ingest_arxiv.py` (`--source oai`, arXiv's OAI-PMH feed, for the daily job; `--source search` for backfills), and the OAI path writes each paper's licence to Turso `paper_licences`. The sidecar catches up at the next publish + deploy. A daily job exists (`scripts/daily_refresh.py`, `.github/workflows/daily-refresh.yml`) but is off until `DAILY_REFRESH=on` | PHASE7 Β§8 |
|
| 50 |
| Citations | Semantic Scholar counts for the whole corpus, refreshed 2026-10-01 (99.47% found); the daily job refreshes the last three months | `scripts/refresh_citations.py` |
|
docs/research/06-Deep-Research-Verdict.md
CHANGED
|
@@ -766,3 +766,33 @@ shows one of its bars); ours match arXiv's page, and the PDF stays linked.
|
|
| 766 |
class of real figures fails cleaning, widen the allow-list with a test for it,
|
| 767 |
never by relaxing the attribute checks.
|
| 768 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 766 |
class of real figures fails cleaning, widen the allow-list with a test for it,
|
| 767 |
never by relaxing the attribute checks.
|
| 768 |
|
| 769 |
+
### 2026-10-20 β arXiv access: a readers' lane and a 15-second background lane
|
| 770 |
+
**Decision:** Requests to arxiv.org are split by who is waiting. Fetches a
|
| 771 |
+
reader triggers (opening a paper, viewing its figures) keep the shared pacer of
|
| 772 |
+
one per 2 s in bursts of 3: each replaces what that reader's own browser would
|
| 773 |
+
have downloaded from arXiv, and is cached for everyone. Work nobody is waiting
|
| 774 |
+
for (the figure warm-up, which now also reads papers people were shown in the
|
| 775 |
+
feed and the top 5 search results) additionally waits 15 s after the previous
|
| 776 |
+
background request, at most 800 papers a day, and gives way to any reader
|
| 777 |
+
fetching the same paper. Search shows a small figure beside each result
|
| 778 |
+
(`SEARCH_FIGURES`).
|
| 779 |
+
**Supersedes:** the figure warm-up's shared pacer and batch of 1,500
|
| 780 |
+
(2026-10-19, two-column feed entry).
|
| 781 |
+
**Rationale:** arxiv.org/robots.txt sets `Crawl-delay: 15` for all automated
|
| 782 |
+
clients and says indiscriminate automated downloads are not permitted;
|
| 783 |
+
info.arxiv.org/help/bulk_data says arXiv's "first priority is to support
|
| 784 |
+
interactive use by human users" and points bulk work to S3 and export.arxiv.org
|
| 785 |
+
(whose robots.txt disallows everything; its API terms ask one request per 3 s).
|
| 786 |
+
Background reading at one request per 15 s stays inside the rule even at full
|
| 787 |
+
volume. Thumbnails in results helped people find the wanted result faster
|
| 788 |
+
without changing how they scan, in Google's eye-tracking and a 2025 IJHCI study.
|
| 789 |
+
**Open risk, owner's call:** arXiv's API terms say e-print content may be
|
| 790 |
+
retrieved and stored for personal or research use, but redistributing it needs
|
| 791 |
+
the copyright holder's permission. Figures are shown for every licence by the
|
| 792 |
+
owner's choice (2026-10-18); the arXiv default licence (about 41% of one day's
|
| 793 |
+
cs papers) grants no reuse rights. `FIGURE_LICENCES` restricts figures to
|
| 794 |
+
Creative Commons licences without a deploy.
|
| 795 |
+
**Action items:** Watch `queued`, `read_today` and `soft_blocks_last_hour` in
|
| 796 |
+
`/healthz/sources` after turning `FIGURE_PREWARM` on. Revisit the licence
|
| 797 |
+
policy before the audience grows.
|
| 798 |
+
|
scripts/seed_e2e.py
CHANGED
|
@@ -23,9 +23,10 @@ Then start the app against them with every outside service blanked, so the
|
|
| 23 |
values in .env.local can't leak in (load_dotenv never overrides a set name):
|
| 24 |
|
| 25 |
DB_PATH=/tmp/e2e.db METADATA_SIDECAR_PATH=/tmp/e2e_sidecar.sqlite \\
|
| 26 |
-
RESEARCHIT_ENV=test ARXIV_HTML_BASE=http://127.0.0.1:8799 \\
|
| 27 |
TURSO_URL= TURSO_DB_TOKEN= QDRANT_URL= GROQ_API_KEY= TURSO_SYNC_DISABLED=1 \\
|
| 28 |
PAPER_PAGE_V2=on FIGURES=on PAPER_SOURCES=on BRIEFING=on ASK=on FEED_CARD_V2=on FEED_WIDE=on \\
|
|
|
|
| 29 |
PORT=7861 python run.py
|
| 30 |
"""
|
| 31 |
from __future__ import annotations
|
|
@@ -89,6 +90,11 @@ def build_sidecar(path: Path, parsed: dict) -> None:
|
|
| 89 |
conn.executemany("INSERT INTO papers VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", rows)
|
| 90 |
conn.executemany("INSERT INTO paper_categories VALUES (?, ?, ?, ?)",
|
| 91 |
[(cats.split()[0], aid, 3, "2026-09-25") for aid, (cats, _) in PAPERS.items()])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
conn.commit()
|
| 93 |
conn.close()
|
| 94 |
|
|
|
|
| 23 |
values in .env.local can't leak in (load_dotenv never overrides a set name):
|
| 24 |
|
| 25 |
DB_PATH=/tmp/e2e.db METADATA_SIDECAR_PATH=/tmp/e2e_sidecar.sqlite \\
|
| 26 |
+
RESEARCHIT_ENV=test ARXIV_HTML_BASE=http://127.0.0.1:8799 ARXIV_API_URL=http://127.0.0.1:8799/api \\
|
| 27 |
TURSO_URL= TURSO_DB_TOKEN= QDRANT_URL= GROQ_API_KEY= TURSO_SYNC_DISABLED=1 \\
|
| 28 |
PAPER_PAGE_V2=on FIGURES=on PAPER_SOURCES=on BRIEFING=on ASK=on FEED_CARD_V2=on FEED_WIDE=on \\
|
| 29 |
+
SEARCH_FIGURES=on \\
|
| 30 |
PORT=7861 python run.py
|
| 31 |
"""
|
| 32 |
from __future__ import annotations
|
|
|
|
| 90 |
conn.executemany("INSERT INTO papers VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", rows)
|
| 91 |
conn.executemany("INSERT INTO paper_categories VALUES (?, ?, ?, ?)",
|
| 92 |
[(cats.split()[0], aid, 3, "2026-09-25") for aid, (cats, _) in PAPERS.items()])
|
| 93 |
+
# The word index search uses (app/fts_svc.py). Without it search found
|
| 94 |
+
# nothing and fell back to the real arXiv API.
|
| 95 |
+
conn.execute("CREATE VIRTUAL TABLE papers_fts USING fts5(title, abstract_preview, content='papers', "
|
| 96 |
+
"content_rowid='rowid', tokenize='porter unicode61')")
|
| 97 |
+
conn.execute("INSERT INTO papers_fts(papers_fts) VALUES('rebuild')")
|
| 98 |
conn.commit()
|
| 99 |
conn.close()
|
| 100 |
|
tests/test_e2e_search.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Browser tests for search thumbnails (SEARCH_FIGURES), against the seeded world.
|
| 3 |
+
|
| 4 |
+
Same world and server as tests/test_e2e_paper.py (see scripts/seed_e2e.py);
|
| 5 |
+
its sidecar has the word index, so "navigation" finds SatNav and GPT-6-Astra
|
| 6 |
+
without any outside service. Skips itself when no such server answers.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
import urllib.error
|
| 12 |
+
import urllib.request
|
| 13 |
+
import uuid
|
| 14 |
+
|
| 15 |
+
import pytest
|
| 16 |
+
|
| 17 |
+
playwright_api = pytest.importorskip("playwright.sync_api", reason="playwright not installed")
|
| 18 |
+
|
| 19 |
+
BASE_URL = os.getenv("E2E_BASE_URL", "http://127.0.0.1:7861").rstrip("/")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _search_world() -> bool:
|
| 23 |
+
try:
|
| 24 |
+
req = urllib.request.Request(f"{BASE_URL}/search?q=navigation", headers={"HX-Request": "true"})
|
| 25 |
+
return "card-thumb" in urllib.request.urlopen(req, timeout=30).read().decode()
|
| 26 |
+
except (urllib.error.URLError, OSError):
|
| 27 |
+
return False
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
pytestmark = [
|
| 31 |
+
pytest.mark.browser,
|
| 32 |
+
pytest.mark.skipif(not _search_world(),
|
| 33 |
+
reason=f"no seeded server with SEARCH_FIGURES at {BASE_URL} (see scripts/seed_e2e.py)"),
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.fixture(scope="module")
|
| 38 |
+
def browser():
|
| 39 |
+
with playwright_api.sync_playwright() as p:
|
| 40 |
+
b = p.chromium.launch()
|
| 41 |
+
yield b
|
| 42 |
+
b.close()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def search(browser, width, height=900):
|
| 46 |
+
ctx = browser.new_context(viewport={"width": width, "height": height})
|
| 47 |
+
ctx.add_cookies([{"name": "arxiv_user_id", "value": f"e2e-{uuid.uuid4()}", "url": BASE_URL}])
|
| 48 |
+
page = ctx.new_page()
|
| 49 |
+
page.errors = []
|
| 50 |
+
page.on("pageerror", lambda e: page.errors.append(str(e)))
|
| 51 |
+
page.goto(f"{BASE_URL}/search?q=navigation", wait_until="networkidle")
|
| 52 |
+
page.wait_for_function("""() => { const i = Array.from(document.querySelectorAll('.card-thumb img'));
|
| 53 |
+
return i.length > 0 && i.every(x => x.complete && x.naturalWidth > 0); }""")
|
| 54 |
+
return ctx, page
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@pytest.mark.parametrize("width,max_thumb", [(1440, 125), (390, 80)])
|
| 58 |
+
def test_thumbnails_sit_beside_the_text_and_stay_small(browser, width, max_thumb):
|
| 59 |
+
ctx, page = search(browser, width)
|
| 60 |
+
try:
|
| 61 |
+
boxes = page.evaluate("""() => Array.from(document.querySelectorAll('.card-split')).map(s => {
|
| 62 |
+
const t = s.querySelector('.card-title').getBoundingClientRect();
|
| 63 |
+
const m = s.querySelector('.card-thumb').getBoundingClientRect();
|
| 64 |
+
return {titleRight: t.right, thumbLeft: m.left, thumbWidth: m.width, thumbTop: m.top, titleTop: t.top}; })""")
|
| 65 |
+
assert boxes
|
| 66 |
+
for b in boxes:
|
| 67 |
+
assert b["thumbLeft"] >= b["titleRight"] - 1 # beside the text, not over it
|
| 68 |
+
assert b["thumbWidth"] <= max_thumb
|
| 69 |
+
assert abs(b["thumbTop"] - b["titleTop"]) < 20 # level with the title
|
| 70 |
+
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
| 71 |
+
assert page.errors == []
|
| 72 |
+
finally:
|
| 73 |
+
ctx.close()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_a_thumbnail_opens_the_paper_at_its_figure_with_the_search_link(browser):
|
| 77 |
+
ctx, page = search(browser, 1440)
|
| 78 |
+
try:
|
| 79 |
+
thumb = page.locator(".card-thumb").first
|
| 80 |
+
assert thumb.get_attribute("tabindex") == "-1" and thumb.get_attribute("aria-hidden") == "true"
|
| 81 |
+
with page.expect_navigation():
|
| 82 |
+
thumb.click()
|
| 83 |
+
assert "/p/" in page.url and "sf=search" in page.url and page.url.endswith("#sec-fig")
|
| 84 |
+
finally:
|
| 85 |
+
ctx.close()
|
tests/test_features.py
CHANGED
|
@@ -77,3 +77,17 @@ def test_templates_can_ask_whether_a_feature_is_visible(monkeypatch):
|
|
| 77 |
monkeypatch.setenv("F", "on")
|
| 78 |
out = templates.env.from_string("{{ 'yes' if feature_visible('F', None) else 'no' }}").render()
|
| 79 |
assert out == "yes"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
monkeypatch.setenv("F", "on")
|
| 78 |
out = templates.env.from_string("{{ 'yes' if feature_visible('F', None) else 'no' }}").render()
|
| 79 |
assert out == "yes"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@pytest.mark.parametrize("env,expected", [
|
| 83 |
+
({"RESEARCHIT_ENV": "test", "ARXIV_API_URL": "http://127.0.0.1:8799/api/"}, "http://127.0.0.1:8799/api"),
|
| 84 |
+
({"RESEARCHIT_ENV": "test"}, "https://export.arxiv.org/api/query"),
|
| 85 |
+
({"RESEARCHIT_ENV": "", "ARXIV_API_URL": "http://evil.example/api"}, "https://export.arxiv.org/api/query"),
|
| 86 |
+
({"RESEARCHIT_ENV": "production", "ARXIV_API_URL": "http://evil.example/api"}, "https://export.arxiv.org/api/query"),
|
| 87 |
+
])
|
| 88 |
+
def test_arxiv_addresses_can_only_be_redirected_in_the_test_world(monkeypatch, env, expected):
|
| 89 |
+
from app import config
|
| 90 |
+
monkeypatch.delenv("ARXIV_API_URL", raising=False)
|
| 91 |
+
for k, v in env.items():
|
| 92 |
+
monkeypatch.setenv(k, v)
|
| 93 |
+
assert config._test_override("ARXIV_API_URL", "https://export.arxiv.org/api/query") == expected
|
tests/test_paper_source_svc.py
CHANGED
|
@@ -245,6 +245,55 @@ async def test_the_pacer_allows_a_burst_of_three_then_one_every_two_seconds(cloc
|
|
| 245 |
assert clock["sleeps"] == [pytest.approx(2.0), pytest.approx(2.0)]
|
| 246 |
|
| 247 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
async def test_parsing_a_large_page_does_not_stall_the_event_loop(fake_arxiv):
|
| 249 |
body = SATNAV.replace(b"</body>", b"".join(
|
| 250 |
b'<div class="ltx_para" id="S9.p%d"><p class="ltx_p">%s</p></div>' % (i, b"word " * 200)
|
|
|
|
| 245 |
assert clock["sleeps"] == [pytest.approx(2.0), pytest.approx(2.0)]
|
| 246 |
|
| 247 |
|
| 248 |
+
async def test_background_requests_are_at_least_15_seconds_apart(clock):
|
| 249 |
+
for _ in range(3):
|
| 250 |
+
assert await pss.pace(background=True)
|
| 251 |
+
assert clock["sleeps"] == [pytest.approx(15.0), pytest.approx(15.0)]
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
async def test_readers_are_not_held_back_by_the_background_lane(clock):
|
| 255 |
+
assert await pss.pace(background=True)
|
| 256 |
+
assert await pss.pace() and await pss.pace()
|
| 257 |
+
assert clock["sleeps"] == [] # the shared bucket still had room
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
async def test_a_background_read_of_a_saved_paper_costs_no_slot(fake_arxiv, clock):
|
| 261 |
+
await pss.ensure("2609.31507") # a reader opened it
|
| 262 |
+
await pss.ensure("2609.20888", background=True)
|
| 263 |
+
clock["sleeps"].clear()
|
| 264 |
+
src = await pss.ensure("2609.31507", background=True)
|
| 265 |
+
assert src.ok and clock["sleeps"] == [] and len(fake_arxiv["requests"]) == 2
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
async def test_background_reads_go_through_the_slow_lane(fake_arxiv, clock):
|
| 269 |
+
fake_arxiv["pages"]["2609.20888"] = (200, (FIXTURES / "2609.20888.html").read_bytes(), {})
|
| 270 |
+
assert (await pss.ensure("2609.31507", background=True)).ok
|
| 271 |
+
assert (await pss.ensure("2609.20888", background=True)).ok
|
| 272 |
+
assert clock["sleeps"] == [pytest.approx(15.0)]
|
| 273 |
+
assert len(fake_arxiv["requests"]) == 2
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
async def test_a_background_read_never_queues_behind_or_ahead_of_a_reader(fake_arxiv, clock):
|
| 277 |
+
gate = asyncio.Event()
|
| 278 |
+
original = pss._download
|
| 279 |
+
|
| 280 |
+
async def slow(arxiv_id):
|
| 281 |
+
await gate.wait()
|
| 282 |
+
return await original(arxiv_id)
|
| 283 |
+
|
| 284 |
+
pss._download = slow
|
| 285 |
+
try:
|
| 286 |
+
reader = asyncio.create_task(pss.ensure("2609.31507"))
|
| 287 |
+
while "2609.31507" not in pss._get_state().in_flight:
|
| 288 |
+
await asyncio.sleep(0)
|
| 289 |
+
assert await pss.ensure("2609.31507", background=True) is None # returns at once, nothing saved yet
|
| 290 |
+
gate.set()
|
| 291 |
+
assert (await reader).ok
|
| 292 |
+
finally:
|
| 293 |
+
pss._download = original
|
| 294 |
+
assert len(fake_arxiv["requests"]) == 1
|
| 295 |
+
|
| 296 |
+
|
| 297 |
async def test_parsing_a_large_page_does_not_stall_the_event_loop(fake_arxiv):
|
| 298 |
body = SATNAV.replace(b"</body>", b"".join(
|
| 299 |
b'<div class="ltx_para" id="S9.p%d"><p class="ltx_p">%s</p></div>' % (i, b"word " * 200)
|
tests/test_search_figures.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Search thumbnails (switch SEARCH_FIGURES): a small figure beside a search
|
| 3 |
+
result whose paper already has one saved.
|
| 4 |
+
|
| 5 |
+
What matters: without a figure the classic card is byte-for-byte unchanged
|
| 6 |
+
(it is used on every page), the thumbnail carries the same Β§3.11 link as the
|
| 7 |
+
title, and nothing changes with the switch off.
|
| 8 |
+
"""
|
| 9 |
+
import json
|
| 10 |
+
import re
|
| 11 |
+
from unittest.mock import patch
|
| 12 |
+
|
| 13 |
+
import aiosqlite
|
| 14 |
+
from fastapi.testclient import TestClient
|
| 15 |
+
|
| 16 |
+
from app import config, hybrid_search_svc, turso_svc
|
| 17 |
+
from app.templates_env import templates
|
| 18 |
+
|
| 19 |
+
PAPER = {
|
| 20 |
+
"arxiv_id": "2609.31507", "title": "SatNav", "abstract": "Urban UAV navigation needs memory. We build SatNav.",
|
| 21 |
+
"authors": '["Jiajun Jiang", "Chunliang Hua"]', "year": 2026, "category": "cs.CV",
|
| 22 |
+
"query_id": "q-1", "position": 0, "propensity": 1.0, "policy_id": "search_v2_independent_lexical",
|
| 23 |
+
}
|
| 24 |
+
THUMB = {"url": "/fig/2609.31507/0-69f7df71.webp", "w": 476, "h": 235, "label": "Figure 1",
|
| 25 |
+
"caption": "Overview.", "credit": "Jiang et al. 2026, CC BY 4.0"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def render(paper):
|
| 29 |
+
return templates.env.get_template("partials/paper_card.html").render(paper=paper, source="search")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_without_a_figure_the_card_is_unchanged():
|
| 33 |
+
assert render(PAPER) == render({**PAPER, "card_figure": None})
|
| 34 |
+
assert "card-split" not in render(PAPER) and "card-thumb" not in render(PAPER)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_the_thumbnail_links_like_the_title_and_stays_out_of_the_way():
|
| 38 |
+
html = render({**PAPER, "card_figure": THUMB})
|
| 39 |
+
title = re.search(r'class="card-title"\s+href="([^"]+)"', html).group(1)
|
| 40 |
+
thumb = re.search(r'<a class="card-thumb" href="([^"]+)"', html).group(1)
|
| 41 |
+
assert thumb == title + "#sec-fig" and "qid=q-1" in title and "sf=search" in title
|
| 42 |
+
tag = re.search(r'<a class="card-thumb"[^>]*>', html, re.S).group(0)
|
| 43 |
+
assert 'tabindex="-1"' in tag and 'aria-hidden="true"' in tag and "CC BY 4.0" in tag
|
| 44 |
+
assert f'src="{THUMB["url"]}"' in html and 'alt=""' in html
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
async def save_source():
|
| 48 |
+
figs = [{"anchor": "S1.F1", "label": "Figure 1", "caption": "Overview.",
|
| 49 |
+
"src": "2609.31507v1/overview-final.png", "w": 476, "h": 235}]
|
| 50 |
+
async with aiosqlite.connect(config.DB_PATH) as conn:
|
| 51 |
+
await conn.execute(
|
| 52 |
+
"INSERT OR REPLACE INTO paper_sources (arxiv_id, status, version, licence, figures_json, "
|
| 53 |
+
"parser_version) VALUES ('2609.31507', 'ok', 'v1', 'CC-BY-4.0', ?, 2)", (json.dumps(figs),))
|
| 54 |
+
await conn.commit()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def search_html(monkeypatch, mode):
|
| 58 |
+
from app.main import app
|
| 59 |
+
import asyncio
|
| 60 |
+
monkeypatch.setenv("SEARCH_FIGURES", mode)
|
| 61 |
+
monkeypatch.setenv("FIGURES", "on")
|
| 62 |
+
asyncio.run(save_source())
|
| 63 |
+
|
| 64 |
+
async def fake_search(q, limit=20, return_meta=False):
|
| 65 |
+
return ["2609.31507", "2609.00002"], {}
|
| 66 |
+
|
| 67 |
+
async def meta(ids):
|
| 68 |
+
return {i: {**PAPER, "arxiv_id": i, "title": f"Paper {i}"} for i in ids}
|
| 69 |
+
|
| 70 |
+
with patch.object(hybrid_search_svc, "search", side_effect=fake_search), \
|
| 71 |
+
patch.object(turso_svc, "fetch_metadata_batch", side_effect=meta), TestClient(app) as c:
|
| 72 |
+
return c.get("/search?q=drones", headers={"HX-Request": "true"}).text
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_search_shows_a_thumbnail_only_with_the_switch_on(monkeypatch):
|
| 76 |
+
on = search_html(monkeypatch, "on")
|
| 77 |
+
assert on.count('class="card-thumb"') == 1 # only the paper with a saved figure
|
| 78 |
+
assert "/fig/2609.31507/0-" in on
|
| 79 |
+
assert [m for m in re.findall(r'data-arxiv-id="([^"]+)"', on)] == ["2609.31507", "2609.00002"]
|
| 80 |
+
off = search_html(monkeypatch, "off")
|
| 81 |
+
assert "card-thumb" not in off and "/fig/" not in off
|
tests/test_wide_feed.py
CHANGED
|
@@ -144,8 +144,9 @@ def warmup(monkeypatch):
|
|
| 144 |
return [("2609.00001", "CC-BY-4.0"), ("2609.00002", "ARXIV-NONEXCLUSIVE-1.0"),
|
| 145 |
("2609.00003", "CC-BY-4.0"), ("2609.00004", "")]
|
| 146 |
|
| 147 |
-
async def fake_ensure(arxiv_id, force=False):
|
| 148 |
calls["ensure"].append(arxiv_id)
|
|
|
|
| 149 |
if arxiv_id == "2609.00003":
|
| 150 |
raise RuntimeError("boom")
|
| 151 |
return SimpleNamespace(arxiv_id=arxiv_id, ok=True, figures=[{"src": f"{arxiv_id}v1/a.png"}],
|
|
@@ -205,3 +206,91 @@ async def test_it_is_off_by_default_and_only_one_runner_holds_the_lock(monkeypat
|
|
| 205 |
assert figure_prewarm._task is not None
|
| 206 |
await figure_prewarm.stop()
|
| 207 |
assert figure_prewarm._task is None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
return [("2609.00001", "CC-BY-4.0"), ("2609.00002", "ARXIV-NONEXCLUSIVE-1.0"),
|
| 145 |
("2609.00003", "CC-BY-4.0"), ("2609.00004", "")]
|
| 146 |
|
| 147 |
+
async def fake_ensure(arxiv_id, force=False, background=False):
|
| 148 |
calls["ensure"].append(arxiv_id)
|
| 149 |
+
calls.setdefault("background", []).append(background)
|
| 150 |
if arxiv_id == "2609.00003":
|
| 151 |
raise RuntimeError("boom")
|
| 152 |
return SimpleNamespace(arxiv_id=arxiv_id, ok=True, figures=[{"src": f"{arxiv_id}v1/a.png"}],
|
|
|
|
| 206 |
assert figure_prewarm._task is not None
|
| 207 |
await figure_prewarm.stop()
|
| 208 |
assert figure_prewarm._task is None
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
async def test_every_warm_up_request_uses_the_background_lane(warmup):
|
| 212 |
+
await figure_prewarm.run_once()
|
| 213 |
+
assert warmup["background"] and all(warmup["background"])
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# ββ papers people were shown βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 217 |
+
|
| 218 |
+
@pytest.fixture
|
| 219 |
+
def queue(monkeypatch):
|
| 220 |
+
monkeypatch.setattr(figure_prewarm, "_queue", figure_prewarm.deque())
|
| 221 |
+
monkeypatch.setattr(figure_prewarm, "_queued", set())
|
| 222 |
+
monkeypatch.setattr(figure_prewarm, "_day", {"date": "", "read": 0, "shown_done": 0})
|
| 223 |
+
monkeypatch.setenv("FIGURE_PREWARM", "on")
|
| 224 |
+
return figure_prewarm
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def test_enqueue_does_nothing_with_the_switch_off(queue, monkeypatch):
|
| 228 |
+
monkeypatch.setenv("FIGURE_PREWARM", "off")
|
| 229 |
+
assert queue.enqueue(["2609.00001"]) == 0 and not queue._queue
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def test_enqueue_skips_duplicates_and_bad_ids_and_drops_the_oldest(queue, monkeypatch):
|
| 233 |
+
monkeypatch.setattr(queue, "QUEUE_MAX", 3)
|
| 234 |
+
assert queue.enqueue(["2609.00001", "2609.00001", "../etc", "2609.00002"]) == 2
|
| 235 |
+
queue.enqueue(["2609.00003", "2609.00004"])
|
| 236 |
+
assert list(queue._queue) == ["2609.00002", "2609.00003", "2609.00004"]
|
| 237 |
+
assert queue._queued == {"2609.00002", "2609.00003", "2609.00004"}
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
async def test_queued_papers_are_read_in_order_through_the_background_lane(queue, warmup, monkeypatch, tmp_path):
|
| 241 |
+
monkeypatch.setattr(queue, "LOCK_PATH", tmp_path / "prewarm.lock")
|
| 242 |
+
monkeypatch.setattr(queue, "FIRST_RUN_DELAY_S", 3600)
|
| 243 |
+
queue.enqueue(["2609.00001", "2609.00002"])
|
| 244 |
+
await queue.start()
|
| 245 |
+
try:
|
| 246 |
+
for _ in range(100):
|
| 247 |
+
if len(warmup["ensure"]) == 2:
|
| 248 |
+
break
|
| 249 |
+
await asyncio.sleep(0.01)
|
| 250 |
+
queue.enqueue(["2609.00004"])
|
| 251 |
+
for _ in range(100):
|
| 252 |
+
if len(warmup["ensure"]) == 3:
|
| 253 |
+
break
|
| 254 |
+
await asyncio.sleep(0.01)
|
| 255 |
+
finally:
|
| 256 |
+
await queue.stop()
|
| 257 |
+
assert warmup["ensure"] == ["2609.00001", "2609.00002", "2609.00004"]
|
| 258 |
+
assert all(warmup["background"])
|
| 259 |
+
assert queue.status()["shown_warmed_today"] == 3
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
async def test_the_daily_cap_stops_reading(queue, warmup, monkeypatch):
|
| 263 |
+
monkeypatch.setattr(queue, "DAILY_MAX", 2)
|
| 264 |
+
results = [await queue.warm(a) for a in ("2609.00001", "2609.00002", "2609.00004")]
|
| 265 |
+
assert results == ["done", "done", "skipped"] and len(warmup["ensure"]) == 2
|
| 266 |
+
assert queue.status()["read_today"] == 2
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def test_the_feed_and_search_queue_what_they_showed(monkeypatch):
|
| 270 |
+
from app.main import app
|
| 271 |
+
from app.routers import recommendations as recs
|
| 272 |
+
seen = []
|
| 273 |
+
monkeypatch.setattr(figure_prewarm, "enqueue", lambda ids: seen.append(list(ids)) or len(ids))
|
| 274 |
+
|
| 275 |
+
async def fake_build_feed(user_id, state, query_id, **kw):
|
| 276 |
+
return {"user_id": user_id, "query_id": query_id, "ranked": ["2609.00001"], "tags": {}}
|
| 277 |
+
|
| 278 |
+
async def fake_build_page(entry, seen_ids):
|
| 279 |
+
return [{"arxiv_id": "2609.00001", "title": "T", "abstract": "A."},
|
| 280 |
+
{"arxiv_id": "2609.00002", "title": "T", "abstract": "A."}], False
|
| 281 |
+
|
| 282 |
+
async def fake_search(q, limit=20, return_meta=False):
|
| 283 |
+
return [f"2609.{i:05d}" for i in range(1, 9)], {}
|
| 284 |
+
|
| 285 |
+
async def meta(ids):
|
| 286 |
+
return {i: {"arxiv_id": i, "title": "T", "abstract": "A.", "authors": "[]"} for i in ids}
|
| 287 |
+
|
| 288 |
+
from app import hybrid_search_svc, turso_svc
|
| 289 |
+
with patch.object(recs, "_build_feed", side_effect=fake_build_feed), \
|
| 290 |
+
patch.object(recs, "_build_page", side_effect=fake_build_page), \
|
| 291 |
+
patch.object(hybrid_search_svc, "search", side_effect=fake_search), \
|
| 292 |
+
patch.object(turso_svc, "fetch_metadata_batch", side_effect=meta), TestClient(app) as c:
|
| 293 |
+
c.get("/api/recommendations")
|
| 294 |
+
c.get("/search?q=drones", headers={"HX-Request": "true"})
|
| 295 |
+
assert seen == [["2609.00001", "2609.00002"], [f"2609.{i:05d}" for i in range(1, 6)]]
|
| 296 |
+
|