~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(web): bound history and library pagination offsets (#7064)
LearningCircuit14d1ba87651e
diff --git a/changelog.d/+offset-pagination-bounds.bugfix.md b/changelog.d/+offset-pagination-bounds.bugfix.mdnew file mode 100644index 0000000000..0f6a6dee40--- /dev/null+++ b/changelog.d/+offset-pagination-bounds.bugfix.md@@ -0,0 +1 @@+Reject history and library pagination offsets above 10,000 with HTTP 400 before querying SQLite, preventing server errors and unbounded scan-and-discard work while preserving ordinary pagination and malformed-number defaults.diff --git a/src/local_deep_research/web/routers/history.py b/src/local_deep_research/web/routers/history.pyindex 2946e5694b..ae183415a8 100644--- a/src/local_deep_research/web/routers/history.py+++ b/src/local_deep_research/web/routers/history.py@@ -3,6 +3,7 @@ from fastapi.responses import JSONResponsefrom ..dependencies.auth import require_authfrom ..dependencies.rate_limit import limiterfrom ..template_config import templates+from ..utils.pagination import OFFSET_LIMIT_ERROR, parse_bounded_offsetimport json@@ -67,9 +68,9 @@ def get_history(except (TypeError, ValueError):limit = 200try:- offset = max(0, int(request.query_params.get("offset", 0)))- except (TypeError, ValueError):- offset = 0+ offset = parse_bounded_offset(request.query_params.get("offset"))+ except ValueError:+ return JSONResponse({"error": OFFSET_LIMIT_ERROR}, status_code=400)try:with get_user_db_session(username) as db_session:diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.pyindex 2c340d7c20..7721deb0e8 100644--- a/src/local_deep_research/web/routers/library.py+++ b/src/local_deep_research/web/routers/library.py@@ -21,6 +21,7 @@ from ..dependencies.threadpool import (from ..utils.range_response import in_memory_range_responsefrom ..template_config import templatesfrom ..utils.download_headers import build_content_disposition+from ..utils.pagination import OFFSET_LIMIT_ERROR, parse_bounded_offsetimport osimport json@@ -61,7 +62,6 @@ from typing import Annotated# Create the routerrouter = APIRouter(prefix="/library", tags=["library"])-#: Upper bound for user-supplied id/url lists on the manual-selection#: routes (check-downloads, mark-redownload). Far above any real bulk#: selection and a safe margin under SQLite's 250,000 bind-parameter@@ -465,9 +465,9 @@ def get_documents(except (TypeError, ValueError):limit = 100try:- offset = max(0, int(request.query_params.get("offset", 0)))- except (TypeError, ValueError):- offset = 0+ offset = parse_bounded_offset(request.query_params.get("offset"))+ except ValueError:+ return JSONResponse({"error": OFFSET_LIMIT_ERROR}, status_code=400)documents = service.get_documents(research_id=research_id,diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.pyindex 192c9e83c1..a7d263645b 100644--- a/src/local_deep_research/web/routers/research.py+++ b/src/local_deep_research/web/routers/research.py@@ -110,6 +110,7 @@ from ...constants import (LANGGRAPH_STRATEGY_NAME as LANGGRAPH_STRATEGY_NAME,)from ..dependencies.json_body import is_json_request, json_body_error+from ..utils.pagination import OFFSET_LIMIT_ERROR, parse_bounded_offset# Create the router for the research applicationrouter = APIRouter(tags=["research"])@@ -2323,9 +2324,9 @@ def get_history(limit = 200limit = max(1, min(limit, 500))try:- offset = max(0, int(request.query_params.get("offset", 0)))- except (TypeError, ValueError):- offset = 0+ offset = parse_bounded_offset(request.query_params.get("offset"))+ except ValueError:+ return JSONResponse({"error": OFFSET_LIMIT_ERROR}, status_code=400)try:with get_user_db_session(username) as db_session:diff --git a/src/local_deep_research/web/utils/pagination.py b/src/local_deep_research/web/utils/pagination.pynew file mode 100644index 0000000000..5fbce86039--- /dev/null+++ b/src/local_deep_research/web/utils/pagination.py@@ -0,0 +1,22 @@+"""Shared offset validation for history and library listings."""++MAX_OFFSET = 10_000+OFFSET_LIMIT_ERROR = f"Offset must not exceed {MAX_OFFSET}"+++def parse_bounded_offset(value: str | None) -> int:+ """Return an offset within the listing limit, or raise ``ValueError``.++ Missing, malformed and negative values retain the legacy zero fallback.+ Values above the ceiling are rejected rather than clamped to another page.+ Callers use ``OFFSET_LIMIT_ERROR`` for the HTTP 400 response rather than+ exposing exception text.+ """+ try:+ offset = max(0, int(value)) if value is not None else 0+ except (TypeError, ValueError):+ return 0++ if offset > MAX_OFFSET:+ raise ValueError(OFFSET_LIMIT_ERROR)+ return offsetdiff --git a/tests/test_known_defect_pattern_sweep.py b/tests/test_known_defect_pattern_sweep.pyindex 1a8142120f..2f11055c60 100644--- a/tests/test_known_defect_pattern_sweep.py+++ b/tests/test_known_defect_pattern_sweep.py@@ -1833,16 +1833,17 @@ P5_KNOWN = {"create_subscription:refresh_minutes",),(- "src/local_deep_research/web/routers/library.py",- "get_documents:offset",+ "src/local_deep_research/web/routers/news_flask_api.py",+ "create_subscription:search_iterations",),}-P5_EXPECTED = P5_KNOWN | {+P5_EXPECTED = P5_KNOWN+P5_REPAIRED_OFFSETS = {("src/local_deep_research/web/routers/history.py", "get_history:offset"),("src/local_deep_research/web/routers/research.py", "get_history:offset"),(- "src/local_deep_research/web/routers/news_flask_api.py",- "create_subscription:search_iterations",+ "src/local_deep_research/web/routers/library.py",+ "get_documents:offset",),}@@ -1876,6 +1877,14 @@ def test_p5_inventory_is_pinned():assert keys(sites) == P5_EXPECTED, report("pattern 5", sites)+def test_p5_repaired_pagination_offsets_stay_absent():+ sites, _ = scan_pattern_5(modules())+ regressed = P5_REPAIRED_OFFSETS & keys(sites)+ assert not regressed, report(+ f"pattern 5 repaired offsets returned: {regressed}", sites+ )++# ===========================================================================# PATTERN 6 -- a value interpolated into a header/log/prompt without the# sanitiser its siblings usediff --git a/tests/ui_tests/test_pagination_query_params_ci.js b/tests/ui_tests/test_pagination_query_params_ci.jsindex 20e777684e..c4ce2d69e4 100644--- a/tests/ui_tests/test_pagination_query_params_ci.js+++ b/tests/ui_tests/test_pagination_query_params_ci.js@@ -138,15 +138,18 @@ async function main() {// LIMIT means "no limit").// ===============================================================const adversarialLimitOffset = [- { limit: 'abc', offset: 'abc' },- { limit: '-1', offset: '-5' },- { limit: '0', offset: '0' },- { limit: '999999999', offset: '999999999' },+ { limit: 'abc', offset: 'abc', expectedStatus: 200 },+ { limit: '-1', offset: '-5', expectedStatus: 200 },+ { limit: '0', offset: '0', expectedStatus: 200 },+ { limit: '20', offset: '37', expectedStatus: 200 },+ { limit: '20', offset: '10000', expectedStatus: 200 },+ { limit: '20', offset: '10001', expectedStatus: 400 },+ { limit: '999999999', offset: '999999999', expectedStatus: 400 },];- for (const { limit, offset } of adversarialLimitOffset) {+ for (const { limit, offset, expectedStatus } of adversarialLimitOffset) {await run('Documents API',- `?limit=${limit}&offset=${offset} returns a valid, bounded response`,+ `?limit=${limit}&offset=${offset} returns HTTP ${expectedStatus}`,async () => {const result = await page.evaluate(async (u) => {const r = await fetch(u, { credentials: 'same-origin' });@@ -155,11 +158,22 @@ async function main() {return { status, body };}, `/library/api/documents?limit=${encodeURIComponent(limit)}&offset=${encodeURIComponent(offset)}`);- const passed = result.status === 200 && result.body && Array.isArray(result.body.documents);+ // Ordinary offsets and malformed-number fallbacks must+ // still return documents. Only offsets above the ceiling+ // receive the specific pagination error.+ const isBounded =+ result.status === 200 &&+ result.body &&+ Array.isArray(result.body.documents);+ const isRejected =+ result.status === 400 &&+ result.body &&+ result.body.error === 'Offset must not exceed 10000';+ const passed = expectedStatus === 400 ? isRejected : isBounded;return {passed,message: passed- ? `HTTP ${result.status}, documents=${result.body.documents.length} (bounded, no crash)`+ ? `HTTP ${result.status} (${isBounded ? 'bounded list' : 'rejected: ' + result.body.error.slice(0, 80)})`: `HTTP ${result.status}, body=${JSON.stringify(result.body).slice(0, 150)}`,};},diff --git a/tests/web/test_pagination_clamping_census.py b/tests/web/test_pagination_clamping_census.pyindex 1f6d105420..52a9414202 100644--- a/tests/web/test_pagination_clamping_census.py+++ b/tests/web/test_pagination_clamping_census.py@@ -13,8 +13,7 @@ while ``int(request.query_params.get(...))`` raises. Each porter re-deriveda clamp, so the same parameter is bounded differently (or not at all) fromone router to the next. This file is a CENSUS: it pins the clamp actuallyin force on each paginated route so a future edit that widens or drops one-fails here by name, and it records — as strict xfails with the mechanism-spelled out — the places where the census found no bound at all.+fails here by name. Every user-controlled offset now has a ceiling.Observation strategy (no large datasets are seeded anywhere):@@ -65,20 +64,6 @@ from local_deep_research.web.routers import unified_search as search_router# offset into a 500 rather than merely a slow query.OVER_INT64 = 10**19-#: Shared reason for the offset gap this census found, quoted by both the-#: behavioural xfail and the static one so they cannot drift apart.-_OFFSET_DEFECT = (- "DEFECT (unfixed): history.py get_history, research.py get_history and "- "library.py get_documents clamp ?offset only at the lower bound -- "- "`max(0, int(...))`. Every page-style sibling (metrics, rag, "- "context_overflow) grew a _MAX_PAGE = 10_000 ceiling for exactly this "- "reason, chat grew MAX_OFFSET = 1_000, and notes clamps offset down to "- "the row count -- but these three offset-style routes were missed. An "- "offset above 2**63-1 reaches .offset() and SQLite's integer binding "- "raises OverflowError, which the global handler turns into a 500; a "- "merely large one makes the single worker scan-and-discard."-)-@pytest.fixturedef client(authenticated_client):@@ -91,10 +76,10 @@ def client(authenticated_client):class TestClampHelperContracts:- """The three shared helpers the routers delegate their parsing to.+ """Parsing contracts for helpers defined within individual routers.- These are the only clamps that are reused across routes; everything- else is an inline expression, pinned through the live routes below.+ The shared history/library offset helper is exercised through all three+ live routes below, including the values that actually reach the database."""@pytest.mark.parametrize(@@ -636,11 +621,10 @@ class TestSqlLevelLimitCensus:# ===========================================================================-# 4. offset with no upper bound — the gap the census found+# 4. Very large offsets are bounded before SQLite sees them# ===========================================================================[email protected](strict=True, reason=_OFFSET_DEFECT)@pytest.mark.parametrize("path", ["/history/api", "/api/history", "/library/api/documents"])@@ -651,6 +635,40 @@ def test_offset_above_int64_does_not_500(client, path):)+ "path", ["/history/api", "/api/history", "/library/api/documents"]+)+ ("raw_offset", "expected"),+ [+ (None, 0),+ ("", 0),+ ("1.5", 0),+ ("-1", 0),+ ("0", 0),+ ("37", 37),+ ("10000", 10000),+ ("10001", None),+ (str(OVER_INT64), None),+ ("abc", 0),+ ],+)+def test_offset_bounds_reach_the_database(+ client, sql_probe, path, raw_offset, expected+):+ """Keep ordinary pages and fallback behavior while bounding SQL work."""+ query = "" if raw_offset is None else f"?offset={raw_offset}"+ resp = client.get(f"{path}{query}")+ if expected is None:+ assert resp.status_code == 400, resp.text+ assert not sql_probe["offset"], sql_probe+ assert resp.json()["error"] == "Offset must not exceed 10000"+ else:+ assert resp.status_code == 200, resp.text+ assert sql_probe["offset"], f"{path} issued no offset query"+ assert set(sql_probe["offset"]) == {expected}, sql_probe++# ===========================================================================# 5. Cursor pagination (chat) — before_created_at / before_id# ===========================================================================@@ -828,6 +846,9 @@ PAGINATION_PARAM_NAMES = frozenset({"limit", "offset", "page", "per_page"})#: never names ``query_params`` at that line.LIMIT_CLAMP_HELPERS = frozenset({"_clamp_limit"})+#: Helpers with fixed ceilings, verified by the behavioural tests above.+FIXED_BOUND_HELPERS = LIMIT_CLAMP_HELPERS | {"parse_bounded_offset"}+#: Helper whose ``max_val=`` keyword supplies the ceiling.BOUNDED_HELPERS = frozenset({"_parse_int_param"})@@ -876,14 +897,14 @@ def _binding_param(value_node):def _upper_bound_kind(func_node, binding, variables):"""Classify the ceiling on *variables* inside *func_node*.- ``"helper"`` delegated to a helper that takes an explicit ``max_val``- (or to ``_clamp_limit``, whose ceiling is ``MAX_LIMIT``);+ ``"helper"`` delegated to a helper with a fixed ceiling or an explicit+ ``max_val`` argument;``"min"`` an explicit ``min(...)`` in an assignment to the variableor to something derived from it;``"guard"`` an ``if <var> > ...:`` statement (reject or clamp);``"none"`` no upper bound anywhere in the handler."""- for helper in LIMIT_CLAMP_HELPERS:+ for helper in FIXED_BOUND_HELPERS:if _find_call(binding.value, helper) is not None:return "helper"for helper in BOUNDED_HELPERS:@@ -977,8 +998,7 @@ def survey_routers():#: The census, frozen. Keys are (router module, handler, query param);#: values are the kind of ceiling in force (see ``_upper_bound_kind``).-#: ``"none"`` entries are DEFECTS, kept in the table so the gap is visible-#: rather than absent — the xfail below is what asserts they are still gaps.+#: All user-controlled page sizes and offsets must have an upper bound.EXPECTED_PAGINATION_CENSUS = {("benchmark.py", "get_benchmark_results", "limit"): "min",("chat.py", "list_sessions", "limit"): "helper",@@ -996,12 +1016,12 @@ EXPECTED_PAGINATION_CENSUS = {"per_page",): "min",("history.py", "get_history", "limit"): "min",- ("history.py", "get_history", "offset"): "none",+ ("history.py", "get_history", "offset"): "helper",("history.py", "get_research_logs", "limit"): "min",("library.py", "library_page", "page"): "min",("library.py", "download_manager_page", "page"): "min",("library.py", "get_documents", "limit"): "min",- ("library.py", "get_documents", "offset"): "none",+ ("library.py", "get_documents", "offset"): "helper",("metrics.py", "api_journal_quality", "page"): "min",("metrics.py", "api_journal_quality", "per_page"): "min",("news_flask_api.py", "get_news_feed", "limit"): "min",@@ -1017,7 +1037,7 @@ EXPECTED_PAGINATION_CENSUS = {("rag.py", "get_documents", "page"): "min",("rag.py", "get_documents", "per_page"): "min",("research.py", "get_history", "limit"): "min",- ("research.py", "get_history", "offset"): "none",+ ("research.py", "get_history", "offset"): "helper",("research.py", "get_research_logs", "limit"): "min",("unified_search.py", "_validated_query_and_limit", "limit"): "min",}@@ -1071,6 +1091,23 @@ class TestSurveyorSelfTest:("m.py", "handler", "page"): "guard"}+ @pytest.mark.parametrize(+ ("parser", "expected"),+ [+ ("parse_bounded_offset", "helper"),+ ("parse_offset", "none"),+ ("int", "none"),+ ],+ )+ def test_only_known_offset_helper_is_bounded(self, parser, expected):+ source = (+ "def handler(request):\n"+ f" offset = {parser}(request.query_params.get('offset'))\n"+ )+ assert survey_module(source, "m.py") == {+ ("m.py", "handler", "offset"): expected+ }+def test_ignores_non_pagination_query_params(self):source = ("def handler(request):\n"@@ -1119,15 +1156,12 @@ class TestPaginationCensus:pytest.param(("notes.py", "get_note_versions", "offset")),pytest.param(("history.py", "get_history", "offset"),- marks=pytest.mark.xfail(strict=True, reason=_OFFSET_DEFECT),),pytest.param(("library.py", "get_documents", "offset"),- marks=pytest.mark.xfail(strict=True, reason=_OFFSET_DEFECT),),pytest.param(("research.py", "get_history", "offset"),- marks=pytest.mark.xfail(strict=True, reason=_OFFSET_DEFECT),),],)diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.pyindex aeb8e425bc..6e4f4558cf 100644--- a/tests/web/test_route_table_parity.py+++ b/tests/web/test_route_table_parity.py@@ -1671,6 +1671,14 @@ EXPECTED_STATUS_CODES_LOST = {# not. Not automatically a regression — most are new input validation — but# each one can turn a request that used to succeed into a failure.EXPECTED_STATUS_CODES_GAINED = {+ # Offsets above 10,000 are rejected before reaching the database. Flask+ # attempted the query (and could raise on values outside SQLite's integer+ # range); ordinary offsets and non-integer fallback behavior are retained.+ # test_pagination_clamping_census exercises the accepted boundary and the+ # rejected requests for each route, rather than relying on this AST census.+ ("GET", "/api/history"): [400],+ ("GET", "/history/api"): [400],+ ("GET", "/library/api/documents"): [400],# Chat pagination now rejects malformed, timezone-free, overflowing,# and incomplete cursors with 400 instead of replaying the newest page# or failing during DB binding. Runtime coverage: TestChatMessageAPI.