From 2d0129c138551749f97ea1be76ee5e932957f3a1 Mon Sep 17 00:00:00 2001 From: Vidit Date: Sun, 18 Oct 2026 14:56:49 +0530 Subject: [PATCH 1/3] Cache repeated checks so the demo doesn't burn the model quota MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /api/check now reuses a real model verdict for the same normalized text against the same settled ledger and feedback for 10 minutes (256 entries max) and marks it "cached": true. Fallback verdicts are never cached. The UI appends " · cached" to the model name. Co-Authored-By: Claude Opus 5.5 --- docs/CONTRACTS.md | 2 +- web/app.py | 28 ++++++++++++++++++++++- web/static/index.html | 4 ++-- web/tests/test_verdict_cache.py | 40 +++++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+), 4 deletions(-) create mode 100644 web/tests/test_verdict_cache.py diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index 8b49440..bc1c6a6 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -60,7 +60,7 @@ api.sync(path: str = "AGENTS.md") -> str # returns the wr |---|---|---|---| | GET | `/api/entries` | `status, kind, q` | `Entry[]` | | POST | `/api/entries/{id}/review` | `{action, note}` | `Entry` | -| POST | `/api/check` | `{text}` | `Verdict` | +| POST | `/api/check` | `{text}` | `Verdict`, plus `"cached": true` when an identical check against the same settled ledger and feedback ran in the last 10 minutes (fallback verdicts are never cached) | | POST | `/api/ingest` | multipart file + `kind` | `{messages, sources}` | | POST | `/api/extract` | `{limit}` | `Entry[]` | | GET | `/api/stats` | none | feedback stats + counts | diff --git a/web/app.py b/web/app.py index 2f9c51b..5d1a084 100644 --- a/web/app.py +++ b/web/app.py @@ -2,6 +2,7 @@ from __future__ import annotations +import copy import json import os import queue @@ -121,8 +122,13 @@ def check(body: CheckBody): if not body.text.strip(): raise HTTPException(400, "text is empty") text = body.text[:4000] + c = con() + key = (fallback.normalize(text), _ledger_fingerprint(c)) + hit = _verdict_cache.get(key) + if hit and time.monotonic() - hit[0] < VERDICT_TTL: + return {**copy.deepcopy(hit[1]), "cached": True} try: - return api.check(text, con=con()).model_dump() + v = api.check(text, con=c).model_dump() except Exception as e: # If the hosted model is unreachable: the built-in examples fall back to verdicts recorded from a # real local Qwen3 run, and other text to a keyword match on explicitly rejected alternatives. @@ -135,6 +141,26 @@ def check(body: CheckBody): if v: return {**v.model_dump(), "fallback": "keyword"} raise HTTPException(502, f"Model call failed: {e}") + # Only real model verdicts are cached; the fallbacks above return before reaching here. + _verdict_cache.pop(key, None) + if len(_verdict_cache) >= VERDICT_CACHE_MAX: + _verdict_cache.pop(next(iter(_verdict_cache))) + _verdict_cache[key] = (time.monotonic(), copy.deepcopy(v)) + return v + + +# Repeated checks of the same text (e.g. judges clicking the same example) reuse the model's verdict instead of +# spending the hosted model's small per-minute quota. The key includes a fingerprint of the settled ledger and of +# the feedback, so a correction or a new or changed decision makes the next check ask the model again. +VERDICT_TTL = 600 +VERDICT_CACHE_MAX = 256 +_verdict_cache: dict[tuple, tuple[float, dict]] = {} + + +def _ledger_fingerprint(c) -> tuple: + settled = c.execute("SELECT COUNT(*), MAX(recorded_at) FROM entries WHERE status = 'settled'").fetchone() + feedback = c.execute("SELECT COUNT(*) FROM feedback").fetchone() + return (settled[0], settled[1], feedback[0]) def _cached_checks() -> dict: diff --git a/web/static/index.html b/web/static/index.html index eecd079..c33cb1e 100644 --- a/web/static/index.html +++ b/web/static/index.html @@ -444,7 +444,7 @@

function fineNote(v) { return v.fallback === "keyword" ? "The model is offline, so this is a keyword match on alternatives you rejected. It is not a model verdict." : v.fallback === "recorded" ? "Recorded from a real local Qwen3 run. The hosted model is offline." - : `Flagged by ${esc(v.model)}, then double-checked by a second pass.`; + : `Flagged by ${esc(v.model)}${v.cached ? " · cached" : ""}, then double-checked by a second pass.`; } async function renderOverruled(v, text) { const c = v.conflicts[0], e = c.entry, arena = $("#arena"); @@ -480,7 +480,7 @@

${esc(e.statement)}

“${esc(e.source.quote)}”
CLEARED

${unrelated ? "Nothing you've settled covers this." : "This follows what you've settled."}

${unrelated ? "No related decisions, so go ahead." : "The plan agrees with every related decision."}

-

Checked by ${esc(v.model)}

`; +

Checked by ${esc(v.model)}${v.cached ? " · cached" : ""}

`; $("#arena").classList.remove("hit"); blip("ok"); } diff --git a/web/tests/test_verdict_cache.py b/web/tests/test_verdict_cache.py new file mode 100644 index 0000000..094379b --- /dev/null +++ b/web/tests/test_verdict_cache.py @@ -0,0 +1,40 @@ +"""The verdict cache on POST /api/check: repeated checks reuse the model's verdict until the ledger or feedback changes.""" + +import os +import tempfile + +os.environ.setdefault("STHIRA_DB", os.path.join(tempfile.mkdtemp(), "web-test.db")) +os.environ.setdefault("STHIRA_PROVIDER", "ollama") +os.environ.setdefault("OLLAMA_HOST", "http://127.0.0.1:9") # nothing listens here, so real model calls fail + +from fastapi.testclient import TestClient # noqa: E402 + +from sthira.models import Verdict # noqa: E402 +from web import app as webapp # noqa: E402 + +client = TestClient(webapp.app) + + +def test_repeated_check_is_cached_until_feedback_changes(monkeypatch): + calls = [] + + def fake_check(text, con=None): + calls.append(text) + return Verdict(input=text, verdict="unrelated", conflicts=[], model="test-model") + + monkeypatch.setattr(webapp.api, "check", fake_check) + webapp._verdict_cache.clear() + text = "Add a CSV export button to the notes list" + first = client.post("/api/check", json={"text": text}).json() + second = client.post("/api/check", json={"text": " add a csv export button to the NOTES list "}).json() + assert len(calls) == 1 and "cached" not in first and second["cached"] is True + + client.post("/api/correct", json={"text": text, "note": "exports are fine"}) + third = client.post("/api/check", json={"text": text}).json() + assert len(calls) == 2 and "cached" not in third + + +def test_fallback_verdicts_are_not_cached(): + webapp._verdict_cache.clear() + client.post("/api/check", json={"text": "let's just move users over to mongodb"}) + assert not webapp._verdict_cache From c9e3a8ff57a32bdef486fc49ab7c43e031dd3b38 Mon Sep 17 00:00:00 2001 From: Vidit Date: Sun, 18 Oct 2026 15:08:54 +0530 Subject: [PATCH 2/3] Add a guided 60-second tour for judges A "Take the tour" button in the hero and a one-time nudge for new visitors start a 7-step driver.js tour themed to the page: the wall, the check (Next runs the MongoDB example for real and waits for the verdict), the OVERRULED receipt, learning, the watcher, import and AGENTS.md. Also stops the learning panel overflowing at 375px. Co-Authored-By: Claude Opus 5.5 --- web/static/index.html | 111 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 105 insertions(+), 6 deletions(-) diff --git a/web/static/index.html b/web/static/index.html index c33cb1e..10ead69 100644 --- a/web/static/index.html +++ b/web/static/index.html @@ -8,6 +8,7 @@ +