Skip to content

~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.

fix(chat): stabilize pagination and validate cursors and titles (#7225)

LearningCircuit04690cf7c484
diff --git a/changelog.d/+chat-cursor-title-validation.bugfix.md b/changelog.d/+chat-cursor-title-validation.bugfix.md
new file mode 100644
index 0000000000..e465dc743c
--- /dev/null
+++ b/changelog.d/+chat-cursor-title-validation.bugfix.md
@@ -0,0 +1 @@
+Invalid chat pagination cursors now return a clear client error. Chat pagination follows the same ordering as displayed messages and progress steps, including timestamps stored with different precision, so boundaries cannot skip messages or repeat a page. A cursor whose boundary entry was deleted must be refreshed. LLM-generated chat titles stay on one line, and title generation falls back safely when a saved timeout is invalid.
diff --git a/src/local_deep_research/chat/service.py b/src/local_deep_research/chat/service.py
index 5c569426de..fb7d2ca30c 100644
--- a/src/local_deep_research/chat/service.py
+++ b/src/local_deep_research/chat/service.py
@@ -11,9 +11,10 @@ from concurrent.futures import (
TimeoutError as FuturesTimeoutError,
)
from datetime import datetime, UTC
+from math import isfinite
import uuid
from loguru import logger
-from sqlalchemy import and_, or_, update
+from sqlalchemy import String, and_, cast, func, literal, or_, tuple_, update
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.sql import ColumnElement
@@ -42,6 +43,10 @@ from ..constants import ResearchStatus
DB_EXCEPTIONS = (ValueError, RuntimeError, SQLAlchemyError)
+class ChatCursorError(ValueError):
+ """Raised for an invalid chat pagination cursor; maps to HTTP 400."""
+
+
class ArchiveBlockedError(RuntimeError):
"""Raised when archive_session is called while a research is in_progress.
@@ -107,6 +112,26 @@ def _serialize_dt(value):
return value.isoformat() if value is not None else None
+def _timestamp_order_key(column):
+ """Compare SQLite UTC timestamps at their full stored precision.
+
+ ``utcnow()`` stores three fractional digits; bound datetimes store six.
+ Padding the fraction makes equal instants compare equal without rounding
+ away microseconds (as SQLite's date/time functions would).
+ """
+ stored = cast(column, String)
+ return (
+ func.substr(stored, 1, 19, type_=String)
+ + "."
+ + func.substr(
+ func.substr(stored, 21, type_=String) + "000000",
+ 1,
+ 6,
+ type_=String,
+ )
+ )
+
+
class ChatService:
"""Service for managing chat conversations and messages."""
@@ -514,7 +539,7 @@ class ChatService:
Pagination is SQL-level via per-table LIMIT + Python merge: each
table fetches at most ``limit`` rows ordered by created_at DESC,
- the two streams are merged on the (timestamp, kind) sort key, and
+ the two streams are merged on (timestamp, sequence, kind, id), and
the latest ``limit`` are returned in ASC order so the client
renders oldest→newest as before.
@@ -528,81 +553,119 @@ class ChatService:
session_id: ID of the session
limit: Maximum number of (merged) entries to return
offset: Number of entries to skip (DESC-ordered slice index)
- before_created_at: Optional ISO timestamp cursor — return only
+ before_created_at: Optional timezone-aware ISO timestamp — return only
entries strictly older than this. Useful for cursor-based
"load older" pagination instead of offset arithmetic.
+ before_id: Optional ID of an entry at the cursor timestamp in this
+ session. Resolves its sequence and kind to break timestamp ties;
+ requires before_created_at. Missing/deleted entries are invalid.
Returns:
List of message + step data dictionaries, ordered by
created_at ascending.
+
+ Raises:
+ ChatCursorError: The cursor is malformed, lacks a timezone, or
+ identifies no matching boundary entry in this session.
"""
+ if before_id and not before_created_at:
+ raise ChatCursorError("before_id requires before_created_at")
+ cutoff = None
+ if before_created_at:
+ if not isinstance(before_created_at, str):
+ raise ChatCursorError(
+ "before_created_at must be an ISO timestamp with a timezone"
+ )
+ try:
+ cutoff = datetime.fromisoformat(
+ before_created_at.replace("Z", "+00:00")
+ )
+ cutoff = (
+ cutoff.astimezone(UTC)
+ if cutoff.utcoffset() is not None
+ else None
+ )
+ except (ValueError, OverflowError) as exc:
+ raise ChatCursorError(
+ "before_created_at must be an ISO timestamp with a timezone"
+ ) from exc
+ if cutoff is None:
+ raise ChatCursorError(
+ "before_created_at must be an ISO timestamp with a timezone"
+ )
+
try:
with get_user_db_session(self.username) as db:
msg_q = db.query(ChatMessage).filter_by(session_id=session_id)
step_q = db.query(ChatProgressStep).filter_by(
session_id=session_id
)
+ msg_timestamp = _timestamp_order_key(ChatMessage.created_at)
+ step_timestamp = _timestamp_order_key(
+ ChatProgressStep.created_at
+ )
- if before_created_at:
- try:
- cutoff = datetime.fromisoformat(
- before_created_at.replace("Z", "+00:00")
+ if cutoff is not None:
+ cutoff_key = cutoff.replace(tzinfo=None).isoformat(
+ sep=" ", timespec="microseconds"
+ )
+ if before_id:
+ # UUID order is unrelated to the sequence ordering
+ # used by the page. Resolve the boundary in this session
+ # and compare the same complete key as ORDER BY/merge.
+ # Steps have their own ID namespace in the response.
+ is_step = before_id.startswith("step-")
+ cursor_model = (
+ ChatProgressStep if is_step else ChatMessage
)
- except ValueError:
- # (#6938: the cursor is a raw query param.)
- from ..web.routers.notes import _log_value_preview
-
- logger.warning(
- "Invalid before_created_at cursor: {} — ignoring.",
- _log_value_preview(before_created_at),
+ cursor_id = before_id[5:] if is_step else before_id
+ cursor_entry = (
+ db.query(cursor_model)
+ .filter_by(session_id=session_id, id=cursor_id)
+ .first()
)
- else:
- # Composite cursor: when `before_id` is also
- # supplied, the filter becomes
- # created_at < cutoff
- # OR (created_at = cutoff AND id < before_id)
- # which prevents same-millisecond rows at the
- # page boundary from being silently dropped on
- # "Load older" pagination. With a bare timestamp
- # cursor we fall back to strict `<` for
- # backwards-compat with older clients.
- if before_id:
- msg_q = msg_q.filter(
- or_(
- ChatMessage.created_at < cutoff,
- and_(
- ChatMessage.created_at == cutoff,
- ChatMessage.id < before_id,
- ),
- )
+ if (
+ cursor_entry is None
+ or cursor_entry.created_at != cutoff
+ ):
+ raise ChatCursorError( # noqa: TRY301 - bypasses DB error logging below
+ "before_id must identify an entry in this session "
+ "at before_created_at"
)
- # ChatProgressStep ids are integers but
- # message ids are UUID strings; using the
- # bare `<` operator on string ids gives a
- # stable lexicographic tie-break, and
- # progress-step rows tie-break by their
- # own integer id (id < int(before_id) is
- # not safe because before_id is the UUID of
- # a chat message, not a step). For steps,
- # drop the equality branch so duplicates
- # rather than drops occur on tie — the
- # client-side dedup catches them.
- step_q = step_q.filter(
- ChatProgressStep.created_at <= cutoff
- )
- else:
- msg_q = msg_q.filter(
- ChatMessage.created_at < cutoff
+ cursor_key = (
+ cutoff_key,
+ cursor_entry.sequence_number,
+ 0 if is_step else 1,
+ cursor_id,
+ )
+ msg_q = msg_q.filter(
+ tuple_(
+ msg_timestamp,
+ ChatMessage.sequence_number,
+ literal(1),
+ ChatMessage.id,
)
- step_q = step_q.filter(
- ChatProgressStep.created_at < cutoff
+ < cursor_key
+ )
+ step_q = step_q.filter(
+ tuple_(
+ step_timestamp,
+ ChatProgressStep.sequence_number,
+ literal(0),
+ ChatProgressStep.id,
)
+ < cursor_key
+ )
+ else:
+ msg_q = msg_q.filter(msg_timestamp < cutoff_key)
+ step_q = step_q.filter(step_timestamp < cutoff_key)
# Pull at most ``limit`` rows from EACH table in DESC
# order. The merged window is at most 2 * limit rows
# (one extreme: all from one table), which we trim to
- # ``limit`` after the Python merge. This bounds the SQL
- # work and avoids the old .all() cliff at large N.
+ # ``limit`` after the Python merge. This bounds rows loaded
+ # into Python; SQLite still sorts this session's matching rows
+ # to normalize timestamps with different stored precision.
fetch_n = limit + offset
# Secondary ORDER BY on sequence_number stabilises rows
# whose created_at collide at SQLite's millisecond
@@ -612,16 +675,18 @@ class ChatService:
# though sequence_number is monotonic.
messages = (
msg_q.order_by(
- ChatMessage.created_at.desc(),
+ msg_timestamp.desc(),
ChatMessage.sequence_number.desc(),
+ ChatMessage.id.desc(),
)
.limit(fetch_n)
.all()
)
steps = (
step_q.order_by(
- ChatProgressStep.created_at.desc(),
+ step_timestamp.desc(),
ChatProgressStep.sequence_number.desc(),
+ ChatProgressStep.id.desc(),
)
.limit(fetch_n)
.all()
@@ -657,17 +722,20 @@ class ChatService:
)
# Sort DESC by (created_at, sequence_number,
- # step-before-message on tie), take the newest
+ # step-before-message on tie, id), take the newest
# [offset:offset+limit] slice, then flip to ASC so the
# client still renders oldest→newest. Including
# sequence_number in the Python tie-break mirrors the
# SQL ORDER BY above and prevents same-timestamp messages
- # from rendering out of insertion order.
+ # from rendering out of insertion order. The final ID breaks
+ # ties between steps from different research runs, which can
+ # share both a timestamp and their per-research sequence.
merged.sort(
key=lambda m: (
m["created_at"] or "",
m.get("sequence_number") or 0,
0 if m["message_type"] == "step" else 1,
+ m["id"],
),
reverse=True,
)
@@ -675,6 +743,8 @@ class ChatService:
window.reverse()
return window
+ except ChatCursorError:
+ raise
except DB_EXCEPTIONS:
# Re-raise so the route returns HTTP 500 instead of a
# misleading 200 + []. An empty list here would be
@@ -1359,19 +1429,28 @@ class ChatService:
if settings_snapshot:
from ..config.llm_config import get_llm
from ..config.thread_settings import get_setting_from_snapshot
+ from ..security.log_sanitizer import strip_control_chars
if get_setting_from_snapshot(
"chat.llm_title_generation",
False,
settings_snapshot=settings_snapshot,
):
- timeout = float(
- get_setting_from_snapshot(
- "chat.title_llm_timeout_seconds",
- _DEFAULT_TITLE_LLM_TIMEOUT_SECONDS,
- settings_snapshot=settings_snapshot,
+ try:
+ timeout = float(
+ get_setting_from_snapshot(
+ "chat.title_llm_timeout_seconds",
+ _DEFAULT_TITLE_LLM_TIMEOUT_SECONDS,
+ settings_snapshot=settings_snapshot,
+ )
)
- )
+ except (TypeError, ValueError, OverflowError):
+ timeout = 0
+ if not isfinite(timeout) or timeout <= 0:
+ logger.warning(
+ "Invalid title-generation timeout; falling back to truncation"
+ )
+ return self._fallback_title(query)
# Run the blocking invoke in a worker thread so the request
# thread isn't parked past `timeout` by an unresponsive LLM.
# `with ThreadPoolExecutor(...) as pool:` would call
@@ -1398,16 +1477,12 @@ class ChatService:
timeout,
)
return self._fallback_title(query)
- # Strip CR/LF before storing: the title is later
- # interpolated into loguru f-strings (e.g. the
- # "title already set" log line above) — an embedded
- # newline forges what looks like a second log entry
- # in aggregators. Also keeps document.title /
- # chatTitle.textContent visually clean.
+ # Store generated titles on one line and remove control
+ # characters while preserving visible Unicode.
title = (
- str(response.content)
- .replace("\n", " ")
- .replace("\r", " ")
+ strip_control_chars(
+ " ".join(str(response.content).splitlines())
+ )
.strip()
.strip("\"'")[:100]
)
diff --git a/src/local_deep_research/web/routers/chat.py b/src/local_deep_research/web/routers/chat.py
index 620394e6ca..bb729d536e 100644
--- a/src/local_deep_research/web/routers/chat.py
+++ b/src/local_deep_research/web/routers/chat.py
@@ -31,6 +31,7 @@ from ...chat.service import (
ArchiveBlockedError,
AttemptInProgress,
AttemptNotFound,
+ ChatCursorError,
ChatService,
ChatSessionNotFound,
DB_EXCEPTIONS,
@@ -742,6 +743,16 @@ async def get_messages(
}
)
+ except ChatCursorError:
+ return JSONResponse(
+ {
+ "success": False,
+ "error": "Invalid pagination cursor. before_created_at must "
+ "include a timezone; before_id must identify an entry in "
+ "this session at before_created_at.",
+ },
+ status_code=400,
+ )
except ROUTE_EXCEPTIONS:
logger.exception("Error getting chat messages")
return JSONResponse(
diff --git a/tests/chat/test_chat_api.py b/tests/chat/test_chat_api.py
index 7af73293b6..3457246d7e 100644
--- a/tests/chat/test_chat_api.py
+++ b/tests/chat/test_chat_api.py
@@ -119,6 +119,86 @@ class TestGenerateTitleEndpoint:
class TestChatMessageAPI:
"""Tests for chat message endpoints."""
+ def test_invalid_cursors_return_400_and_valid_paging_still_works(
+ self, authenticated_client
+ ):
+ response = authenticated_client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "Pagination control"},
+ content_type="application/json",
+ )
+ assert response.status_code == 200
+ session_id = json.loads(response.data)["session_id"]
+ url = f"/api/chat/sessions/{session_id}/messages"
+
+ for cursor in (
+ {"before_created_at": "not-a-date"},
+ {"before_created_at": "2026-01-01"},
+ {"before_created_at": "2026-01-01T12:00:00"},
+ {"before_created_at": "0001-01-01T00:00:00+01:00"},
+ {"before_id": "message-id"},
+ {"before_created_at": "", "before_id": "message-id"},
+ {
+ "before_created_at": "2026-01-01T12:00:00+00:00",
+ "before_id": "message-id",
+ },
+ ):
+ response = authenticated_client.get(url, query_string=cursor)
+ assert response.status_code == 400, cursor
+ assert json.loads(response.data) == {
+ "success": False,
+ "error": "Invalid pagination cursor. before_created_at must "
+ "include a timezone; before_id must identify an entry in "
+ "this session at before_created_at.",
+ }
+
+ for cursor in (
+ {},
+ {"before_created_at": ""},
+ {"before_created_at": "2026-01-01T12:00:00Z"},
+ {"before_created_at": "2026-01-01T13:00:00+01:00"},
+ ):
+ response = authenticated_client.get(url, query_string=cursor)
+ assert response.status_code == 200, cursor
+ data = json.loads(response.data)
+ assert data["success"] is True
+ assert data["messages"] == []
+ assert data["has_more"] is False
+
+ # An actual server-issued composite cursor still advances normally.
+ for content in ("older message", "newer message"):
+ response = authenticated_client.post(
+ url,
+ json={"content": content, "trigger_research": False},
+ content_type="application/json",
+ )
+ assert response.status_code == 200
+ response = authenticated_client.get(url, query_string={"limit": 1})
+ assert response.status_code == 200
+ newest = json.loads(response.data)
+ assert newest["has_more"] is True
+ boundary = newest["messages"][0]
+ assert boundary["content"] == "newer message"
+ response = authenticated_client.get(
+ url,
+ query_string={
+ "limit": 1,
+ "before_created_at": boundary["created_at"],
+ "before_id": boundary["id"],
+ },
+ )
+ assert response.status_code == 200
+ older = json.loads(response.data)
+ assert [m["content"] for m in older["messages"]] == ["older message"]
+ assert older["has_more"] is False
+
+ # Session existence is checked before cursor validation.
+ response = authenticated_client.get(
+ "/api/chat/sessions/does-not-exist/messages",
+ query_string={"before_created_at": "not-a-date"},
+ )
+ assert response.status_code == 404
+
def test_send_message_without_research(self, authenticated_client):
"""Test sending a message without triggering research."""
# Create a session first
diff --git a/tests/chat/test_chat_service_contracts.py b/tests/chat/test_chat_service_contracts.py
index f81a005810..7191cb6859 100644
--- a/tests/chat/test_chat_service_contracts.py
+++ b/tests/chat/test_chat_service_contracts.py
@@ -40,7 +40,7 @@ from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock, patch
import pytest
-from sqlalchemy import create_engine, event
+from sqlalchemy import create_engine, event, text
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.orm import sessionmaker
@@ -48,6 +48,7 @@ from local_deep_research.chat.service import (
ArchiveBlockedError,
AttemptInProgress,
AttemptNotFound,
+ ChatCursorError,
ChatService,
ChatSessionNotFound,
)
@@ -451,16 +452,6 @@ class TestSessionOwnership:
# 2. Message ordering and cursor pagination
# ---------------------------------------------------------------------
-#: Both cursor defects share one root cause, so they share one reason
-#: string: the ``try/except ValueError`` in ``get_session_messages`` wraps
-#: only ``datetime.fromisoformat``, and the filters live in its ``else:``
-#: branch. A cursor the service cannot use is therefore dropped rather
-#: than reported, and the query runs completely unfiltered.
-_CURSOR_DEFECT = (
- "get_session_messages silently ignores an unusable cursor and serves "
- "the newest page instead of signalling a bad request"
-)
-
_ISO = "2026-03-01T12:00:00+00:00"
@@ -593,6 +584,97 @@ class TestMessageOrdering:
class TestCursorPagination:
+ @pytest.mark.parametrize("composite", [False, True])
+ def test_cursor_preserves_mixed_timestamp_precision(
+ self, user_dbs, composite
+ ):
+ service = user_dbs.service(OWNER)
+ session_id = service.create_session(initial_query="timestamp precision")
+ for message_id, sequence, stamp in (
+ ("microsecond", 1, "2026-01-01 12:00:00.123001"),
+ ("millisecond", 3, "2026-01-01 12:00:00.123"),
+ ("padded", 2, "2026-01-01 12:00:00.123000"),
+ ):
+ seed_message_at(
+ user_dbs,
+ OWNER,
+ session_id,
+ message_id,
+ _at(0),
+ sequence,
+ message_id,
+ )
+ # Reproduce both SQL utcnow() and bound-datetime storage forms.
+ with user_dbs.raw(OWNER) as db:
+ db.execute(
+ text(
+ "UPDATE chat_messages SET created_at = :stamp WHERE id = :id"
+ ),
+ {"stamp": stamp, "id": message_id},
+ )
+ db.commit()
+ latest = service.get_session_messages(session_id, limit=1)
+ assert latest[0]["id"] == "microsecond"
+ cursor = {"before_created_at": latest[0]["created_at"]}
+ if composite:
+ cursor["before_id"] = latest[0]["id"]
+ older = service.get_session_messages(session_id, limit=1, **cursor)
+ assert older[0]["id"] == "millisecond"
+ cursor = {"before_created_at": older[0]["created_at"]}
+ if composite:
+ cursor["before_id"] = older[0]["id"]
+ oldest = service.get_session_messages(session_id, limit=1, **cursor)
+ assert [m["id"] for m in oldest] == (["padded"] if composite else [])
+
+ def test_composite_cursor_follows_sequence_with_nonmonotonic_ids(
+ self, user_dbs
+ ):
+ service = user_dbs.service(OWNER)
+ session_id = service.create_session(initial_query="UUID order")
+ for message_id, sequence in (("z", 1), ("a", 2), ("m", 3)):
+ seed_message_at(
+ user_dbs,
+ OWNER,
+ session_id,
+ message_id,
+ _at(0),
+ sequence,
+ f"message {sequence}",
+ )
+
+ cursor = {}
+ seen = []
+ for _ in range(4):
+ page = service.get_session_messages(session_id, limit=1, **cursor)
+ if not page:
+ break
+ seen.append(page[0]["content"])
+ cursor = {
+ "before_created_at": page[0]["created_at"],
+ "before_id": page[0]["id"],
+ }
+ assert seen == ["message 3", "message 2", "message 1"]
+
+ def test_composite_cursor_advances_past_progress_step(self, user_dbs):
+ service = user_dbs.service(OWNER)
+ session_id = service.create_session(initial_query="step cursor")
+ seed_research(user_dbs, OWNER, "step-research", session_id)
+ seed_message_at(
+ user_dbs, OWNER, session_id, "question", _at(0), 1, "question"
+ )
+ seed_step_at(
+ user_dbs, OWNER, session_id, "step-research", "progress", _at(1), 1
+ )
+ newest = service.get_session_messages(session_id, limit=1)
+ assert newest[0]["id"] == "step-progress"
+ older = service.get_session_messages(
+ session_id,
+ limit=1,
+ before_created_at=newest[0]["created_at"],
+ before_id=newest[0]["id"],
+ )
+ assert [m["content"] for m in older] == ["question"]
+
def test_a_valid_cursor_returns_strictly_older_entries(self, paged_session):
"""Positive control for the whole cursor mechanism."""
service, session_id, _ids = paged_session
@@ -665,12 +747,8 @@ class TestCursorPagination:
)
assert timestamp_only == []
- def test_composite_cursor_re_serves_boundary_progress_steps(self, user_dbs):
- """Documented asymmetry: with ``before_id`` the step query relaxes
- to ``created_at <= cutoff`` because a message UUID cannot tie-break
- an integer step sequence. Steps at the boundary are therefore
- duplicated (client-side dedup is the stated mitigation) rather
- than dropped. Pinned so the trade-off cannot change unnoticed."""
+ def test_composite_cursor_keeps_step_before_message_on_tie(self, user_dbs):
+ """At equal timestamps/sequences, the step precedes the message."""
service = user_dbs.service(OWNER)
session_id = service.create_session(initial_query="step boundary")
research_id = "research-step-boundary"
@@ -697,10 +775,101 @@ class TestCursorPagination:
before_created_at=step_created_at.isoformat(),
before_id="after-step",
)
- # The step at the cutoff is re-served (<=), the message at the
- # cutoff is correctly excluded (id tie-break).
+ # The earlier step is included; the cursor message is excluded.
assert [m["content"] for m in page] == ["boundary step"]
+ @pytest.mark.parametrize("page_size", [1, 2, 4])
+ def test_composite_cursor_walks_mixed_ties_once(self, user_dbs, page_size):
+ service = user_dbs.service(OWNER)
+ session_id = service.create_session(initial_query="mixed boundaries")
+ for research_id in ("run-1", "run-2"):
+ seed_research(
+ user_dbs,
+ OWNER,
+ research_id,
+ session_id,
+ status=ResearchStatus.COMPLETED,
+ )
+ for message_id, sequence in (("z", 1), ("a", 2), ("m", 3)):
+ seed_message_at(
+ user_dbs,
+ OWNER,
+ session_id,
+ message_id,
+ _at(0),
+ sequence,
+ message_id,
+ )
+ for research_id, step_id, sequence, stamp in (
+ ("run-1", "q", 1, _at(0)),
+ ("run-2", "p", 1, _at(0)),
+ ("run-1", "r", 2, _at(0)),
+ ("run-1", "old", 3, _at(-1)),
+ ):
+ seed_step_at(
+ user_dbs,
+ OWNER,
+ session_id,
+ research_id,
+ step_id,
+ stamp,
+ sequence,
+ )
+ expected = ["step-old", "step-p", "step-q", "z", "step-r", "a", "m"]
+ assert [
+ m["id"] for m in service.get_session_messages(session_id)
+ ] == expected
+ seen = []
+ cursor = {}
+ for _ in range(len(expected) + 1):
+ page = service.get_session_messages(
+ session_id, limit=page_size, **cursor
+ )
+ if not page:
+ break
+ seen = [m["id"] for m in page] + seen
+ cursor = {
+ "before_created_at": page[0]["created_at"],
+ "before_id": page[0]["id"],
+ }
+ else:
+ pytest.fail("cursor did not reach the end of history")
+ assert seen == expected
+
+ @pytest.mark.parametrize(
+ "invalid_boundary",
+ ["missing", "deleted", "other_session", "wrong_time"],
+ )
+ def test_composite_cursor_rejects_unusable_boundary(
+ self, user_dbs, invalid_boundary
+ ):
+ service = user_dbs.service(OWNER)
+ session_id = service.create_session(initial_query="cursor owner")
+ other_id = service.create_session(initial_query="other session")
+ seed_message_at(
+ user_dbs,
+ OWNER,
+ other_id if invalid_boundary == "other_session" else session_id,
+ "boundary",
+ _at(0),
+ 1,
+ "boundary",
+ )
+ if invalid_boundary == "deleted":
+ with user_dbs.raw(OWNER) as db:
+ db.delete(db.get(ChatMessage, "boundary"))
+ db.commit()
+ with pytest.raises(ChatCursorError, match="must identify an entry"):
+ service.get_session_messages(
+ session_id,
+ before_created_at=_at(
+ 1 if invalid_boundary == "wrong_time" else 0
+ ).isoformat(),
+ before_id="step-missing"
+ if invalid_boundary == "missing"
+ else "boundary",
+ )
+
@pytest.mark.parametrize(
"bad_cursor",
[
@@ -716,122 +885,70 @@ class TestCursorPagination:
"locale-formatted",
],
)
- @pytest.mark.xfail(strict=True, reason=_CURSOR_DEFECT)
def test_an_unusable_cursor_is_reported_rather_than_dropped(
self, paged_session, bad_cursor
):
- """An unparseable cursor should be a caller error, not a silent
- no-op. Today it is swallowed (WARNING log only) and the query
- runs unfiltered."""
+ """An unparseable cursor is a caller error, never an unfiltered page."""
service, session_id, _ids = paged_session
- with pytest.raises(ValueError):
+ with pytest.raises(ChatCursorError):
service.get_session_messages(
session_id, limit=2, before_created_at=bad_cursor
)
- def test_blast_radius_an_unusable_cursor_re_serves_the_newest_page(
- self, paged_session
- ):
- """Mechanism + consequence, pinned as current behaviour.
-
- The result is byte-identical to the no-cursor call, so the caller
- has no way to tell "no older entries" from "your cursor was
- rejected". Combined with the router's ``has_more`` peek (which is
- computed from this same page and stays true), a client's "load
- older" loop re-renders the newest window indefinitely instead of
- terminating.
- """
+ def test_rejected_cursors_do_not_change_valid_paging(self, paged_session):
service, session_id, _ids = paged_session
-
- no_cursor = service.get_session_messages(session_id, limit=2)
- assert [m["content"] for m in no_cursor] == ["m4", "m5"]
-
+ newest = service.get_session_messages(session_id, limit=2)
+ assert [m["content"] for m in newest] == ["m4", "m5"]
for bad_cursor in ("not-a-date", "2026", "3/1/2026, 12:00:00 PM"):
- dropped = service.get_session_messages(
- session_id, limit=2, before_created_at=bad_cursor
- )
- assert dropped == no_cursor, bad_cursor
-
- # There are older entries, so this is not "the page happens to be
- # the same because the cursor was at the start".
+ with pytest.raises(ChatCursorError):
+ service.get_session_messages(
+ session_id, limit=2, before_created_at=bad_cursor
+ )
+ assert service.get_session_messages(session_id, limit=2) == newest
assert len(service.get_session_messages(session_id)) == 6
- # The unfiltered page fills the limit, which is what the router
- # turns into has_more=True -> the client asks again with the same
- # rejected cursor and gets the same page.
- peek = service.get_session_messages(
- session_id, limit=3, before_created_at="not-a-date"
- )
- assert len(peek) == 3
-
def test_an_empty_cursor_means_no_cursor(self, paged_session):
- """Distinct from the defect above: an empty string is falsy, so it
- never reaches the parse at all. The router already normalises ""
- to None, so "no cursor supplied" is the correct reading -- pinned
- here so it is not mistaken for the swallow path."""
+ """The router normalises an empty string to None; the service
+ treats both as an absent cursor."""
service, session_id, _ids = paged_session
assert service.get_session_messages(
session_id, limit=2, before_created_at=""
) == service.get_session_messages(session_id, limit=2)
- @pytest.mark.xfail(strict=True, reason=_CURSOR_DEFECT)
def test_before_id_without_a_timestamp_is_reported_rather_than_dropped(
self, paged_session
):
- """``before_id`` alone is discarded with no log line at all -- the
- WARNING only fires when ``before_created_at`` is present-but-bad,
- so this variant is invisible in production logs."""
service, session_id, ids = paged_session
- newest = service.get_session_messages(session_id, limit=2)
+ with pytest.raises(ChatCursorError, match="requires before_created_at"):
+ service.get_session_messages(session_id, limit=2, before_id=ids[4])
- page = service.get_session_messages(
- session_id, limit=2, before_id=ids[4]
- )
- assert page != newest
-
- def test_blast_radius_before_id_alone_is_discarded_without_a_log(
+ def test_empty_timestamp_does_not_enable_an_id_only_cursor(
self, paged_session
):
- """Current behaviour, pinned: identical to passing no cursor."""
service, session_id, ids = paged_session
-
- assert service.get_session_messages(
- session_id, limit=2, before_id=ids[4]
- ) == service.get_session_messages(session_id, limit=2)
+ with pytest.raises(ChatCursorError, match="requires before_created_at"):
+ service.get_session_messages(
+ session_id, limit=2, before_id=ids[4], before_created_at=""
+ )
@pytest.mark.parametrize(
"naive_cursor",
["2026-03-01", "2026-03-01T12:00:00", "2026-03-01T12:00:00.000000"],
)
- def test_blast_radius_a_valid_but_naive_cursor_escapes_the_guard(
+ def test_naive_cursor_is_rejected_before_database_binding(
self, paged_session, naive_cursor
):
- """The third failure mode, and the one the guard does not even
- see: these parse cleanly, so the ``except ValueError`` never runs.
- The naive datetime then reaches ``UtcDateTime.process_bind_param``,
- which raises ``ValueError('naive datetime is disallowed')`` from
- inside the query. ``ValueError`` is in ``DB_EXCEPTIONS``, so it is
- logged and **re-raised** -- the router maps it to HTTP 500.
-
- So one query parameter has three contradictory outcomes: silently
- ignored (unparseable), silently ignored with no log (``before_id``
- alone), or a 500 (valid-but-naive). None of them is a 400.
- """
service, session_id, _ids = paged_session
-
- # Positive control: the same instant WITH an offset works.
assert (
service.get_session_messages(
session_id, limit=2, before_created_at=_ISO
)
== []
)
-
- with pytest.raises(Exception) as excinfo:
+ with pytest.raises(ChatCursorError, match="timezone"):
service.get_session_messages(
session_id, limit=2, before_created_at=naive_cursor
)
- assert "naive datetime is disallowed" in str(excinfo.value)
# ---------------------------------------------------------------------
@@ -1447,12 +1564,6 @@ _TITLE_SNAPSHOT = {
"chat.title_llm_timeout_seconds": 5,
}
-_LOG_INJECTION_DEFECT = (
- "_generate_title strips only CR/LF, so U+2028, U+0085, VT, FF and NUL "
- "survive into a title that is interpolated into loguru f-strings and "
- "split by any consumer using str.splitlines()"
-)
-
@pytest.fixture
def titled(user_dbs):
@@ -1589,46 +1700,32 @@ class TestTitleGeneration:
("\x0c", "form-feed"),
],
)
- @pytest.mark.xfail(strict=True, reason=_LOG_INJECTION_DEFECT)
def test_all_line_breaking_characters_are_stripped(
self, titled, separator, name
):
- """``str.splitlines()`` treats every one of these as a line break,
- so any log consumer that splits lines sees a forged second entry
- -- the exact outcome the CR/LF strip exists to prevent."""
+ """Generated titles are stored as one display line."""
service, session_id = titled
- with _llm_returning(f"Title{separator}ERROR forged log line"):
+ with _llm_returning(f"Title{separator}Second line"):
result = service.regenerate_title_with_llm(
session_id, "original query", _TITLE_SNAPSHOT
)
- assert len(result.splitlines()) == 1, name
+ assert result == "Title Second line", name
- def test_blast_radius_non_crlf_control_characters_reach_the_title(
+ def test_generated_title_does_not_store_control_characters(
self, user_dbs, titled
):
- """Current behaviour, pinned.
-
- The stored title is later interpolated into a loguru f-string by
- ``regenerate_title_with_llm``'s "title already set" branch, so
- these characters are written straight into the log stream.
- """
service, session_id = titled
- hostile = "Title\u2028ERROR forged\x00\x1b[2J"
- with _llm_returning(hostile):
+ with _llm_returning("Title\u2028Second line\x00\x1b[2J"):
result = service.regenerate_title_with_llm(
session_id, "original query", _TITLE_SNAPSHOT
)
-
- assert "\u2028" in result
- assert "\x00" in result
- assert "\x1b" in result
- assert len(result.splitlines()) == 2
+ assert "\u2028" not in result
+ assert "\x00" not in result
+ assert "\x1b" not in result
+ assert len(result.splitlines()) == 1
with user_dbs.raw(OWNER) as db:
- stored = (
- db.query(ChatSession).filter_by(id=session_id).first().title
- )
+ stored = db.get(ChatSession, session_id).title
assert stored == result
- # Still bounded, so this is a sanitisation gap and not a size one.
assert len(stored) <= 100
def test_a_slow_llm_falls_back_to_truncation_within_the_timeout(
@@ -1717,15 +1814,6 @@ class TestTitleGeneration:
)
assert llm.invoke.call_count == 0
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "the float() coercion of chat.title_llm_timeout_seconds sits "
- "OUTSIDE _generate_title's try/except, so a non-numeric stored "
- "setting escapes the documented fall-back-to-truncation "
- "guarantee and reaches the caller as an uncaught ValueError"
- ),
- )
def test_a_non_numeric_timeout_setting_still_falls_back(self, titled):
service, session_id = titled
snapshot = dict(_TITLE_SNAPSHOT)
@@ -1738,19 +1826,33 @@ class TestTitleGeneration:
== "original query"
)
- def test_blast_radius_a_non_numeric_timeout_setting_propagates(
+ @pytest.mark.parametrize(
+ "timeout", ["not-a-number", "nan", "inf", None, 0, -1]
+ )
+ def test_invalid_timeout_does_not_construct_a_provider(self, timeout):
+ service = ChatService(OWNER)
+ snapshot = dict(_TITLE_SNAPSHOT)
+ snapshot["chat.title_llm_timeout_seconds"] = timeout
+ with patch("local_deep_research.config.llm_config.get_llm") as factory:
+ assert (
+ service._generate_title("original query", snapshot)
+ == "original query"
+ )
+ factory.assert_not_called()
+
+ def test_numeric_string_timeout_and_visible_unicode_are_preserved(
self, titled
):
- """Current behaviour, pinned: the only statement in the LLM branch
- not covered by the ``except Exception`` fall-back."""
service, session_id = titled
snapshot = dict(_TITLE_SNAPSHOT)
- snapshot["chat.title_llm_timeout_seconds"] = "not-a-number"
- with _llm_returning("Machine Written"):
- with pytest.raises(ValueError, match="could not convert string"):
+ snapshot["chat.title_llm_timeout_seconds"] = "2.5"
+ with _llm_returning("Résumé 東京 😀"):
+ assert (
service.regenerate_title_with_llm(
session_id, "original query", snapshot
)
+ == "Résumé 東京 😀"
+ )
def test_the_creation_path_never_calls_the_llm(self, user_dbs):
"""``create_session`` must stay synchronous-and-cheap; LLM titling
diff --git a/tests/database/test_model_constraint_contracts.py b/tests/database/test_model_constraint_contracts.py
index ae5f76d3ac..9a99bad0a3 100644
--- a/tests/database/test_model_constraint_contracts.py
+++ b/tests/database/test_model_constraint_contracts.py
@@ -791,37 +791,19 @@ def test_naive_datetime_raises_inside_the_query_not_at_parse(db):
assert "naive datetime is disallowed" in str(excinfo.value)
-def test_chat_pagination_cursor_without_a_timezone_is_a_500(
+def test_chat_pagination_rejects_unusable_cursors_before_query_binding(
engine, monkeypatch
):
- """DEFECT: ``ChatService.get_session_messages`` guards the PARSE but
- the QUERY.
-
- ``before_created_at`` comes straight off the query string
- (web/routers/chat.py). ``datetime.fromisoformat`` happily returns a
- NAIVE datetime for a cursor with no offset, so the ``except
- ValueError`` around the parse never fires; the value is then bound
- into a ``UtcDateTime`` comparison and raises there instead, where
- nothing catches it.
- """
+ """Invalid client input must not become a UtcDateTime binding error."""
from local_deep_research.chat import service as chat_service
_patch_user_db_session(monkeypatch, chat_service, engine)
svc = chat_service.ChatService("cursor-user")
session_id = svc.create_session(title="cursor")
- # A malformed cursor IS handled -- the guard works for its own case.
- assert (
- svc.get_session_messages(session_id, before_created_at="not-a-date")
- == []
- )
-
- # A well-formed but tz-less cursor is not.
- with pytest.raises(StatementError) as excinfo:
- svc.get_session_messages(
- session_id, before_created_at="2026-01-01T00:00:00"
- )
- assert "naive datetime is disallowed" in str(excinfo.value)
+ for cursor in ("not-a-date", "2026-01-01T00:00:00"):
+ with pytest.raises(chat_service.ChatCursorError):
+ svc.get_session_messages(session_id, before_created_at=cursor)
# The same instant with an offset is fine.
assert (
diff --git a/tests/web/test_pagination_clamping_census.py b/tests/web/test_pagination_clamping_census.py
index 76318d37bf..1f6d105420 100644
--- a/tests/web/test_pagination_clamping_census.py
+++ b/tests/web/test_pagination_clamping_census.py
@@ -45,7 +45,7 @@ import pytest
import sqlalchemy.orm as sa_orm
from starlette.datastructures import QueryParams
-from local_deep_research.chat.service import ChatService
+from local_deep_research.chat.service import ChatCursorError, ChatService
from local_deep_research.database.models import (
ChatMessage,
ChatRole,
@@ -374,10 +374,10 @@ class TestChatMessagesClamp:
"""The route does NOT validate ``before_created_at`` itself.
It forwards the raw string; ``ChatService.get_session_messages``
- parses it with ``datetime.fromisoformat`` and logs-and-ignores a
- bad one (pinned in TestCursorPagination below). Recorded here so
- the split of responsibility is explicit: moving validation into the
- route must update both places.
+ parses it with ``datetime.fromisoformat`` and rejects a bad one
+ (pinned in TestCursorPagination below). This recording service
+ deliberately only observes forwarding; real-service HTTP tests
+ verify the resulting 400 response.
"""
resp = client.get(
f"/api/chat/sessions/abc/messages?before_created_at={cursor}"
@@ -726,48 +726,36 @@ class TestCursorPagination:
@pytest.mark.parametrize(
"cursor", ["not-a-timestamp", "2026-13-45T00:00:00", "0", "banana"]
)
- def test_malformed_cursor_is_ignored_rather_than_rejected(
+ def test_malformed_cursor_is_rejected(
self, setup_database_for_all_tests, cursor
):
- """A cursor that will not parse is dropped, not honoured.
-
- ``datetime.fromisoformat`` raises, the service logs a warning and
- falls through WITHOUT applying any filter — so the caller silently
- gets the NEWEST page instead of an error. A "load older" loop that
- corrupts its cursor therefore re-serves page 1 forever rather than
- failing fast. Pinned as the current contract, with the loop hazard
- recorded; the route (TestChatMessagesClamp) does not validate it
- either, so this is the only validation there is.
- """
+ """A malformed cursor never silently returns the newest page."""
SessionLocal = setup_database_for_all_tests
service = ChatService(username=f"u_{uuid.uuid4().hex[:8]}")
with _service_db(SessionLocal):
with SessionLocal() as db:
session_id, _ids, _base = self._seed(db)
- page = service.get_session_messages(
- session_id, limit=10, before_created_at=cursor
- )
+ with pytest.raises(ChatCursorError):
+ service.get_session_messages(
+ session_id, limit=10, before_created_at=cursor
+ )
+ page = service.get_session_messages(session_id, limit=10)
assert [m["content"] for m in page] == ["m0", "m1", "m2", "m3", "m4"]
- def test_before_id_without_a_timestamp_is_silently_ignored(
+ def test_before_id_without_a_timestamp_is_rejected(
self, setup_database_for_all_tests
):
- """``before_id`` alone does nothing — it is only a tie-breaker.
-
- The composite-cursor filter is built inside the
- ``if before_created_at:`` branch, so a client that remembers only
- the id half of the cursor gets an unfiltered newest page with no
- signal that its cursor was discarded.
- """
+ """The id is a tie-breaker and requires the timestamp half."""
SessionLocal = setup_database_for_all_tests
service = ChatService(username=f"u_{uuid.uuid4().hex[:8]}")
with _service_db(SessionLocal):
with SessionLocal() as db:
session_id, ids, _base = self._seed(db)
- page = service.get_session_messages(
- session_id, limit=10, before_id=ids[0]
- )
- assert len(page) == 5
+ with pytest.raises(ChatCursorError):
+ service.get_session_messages(
+ session_id, limit=10, before_id=ids[0]
+ )
+ assert len(service.get_session_messages(session_id, limit=10)) == 5
def test_composite_cursor_keeps_same_timestamp_rows_from_being_lost(
self, setup_database_for_all_tests
@@ -776,7 +764,7 @@ class TestCursorPagination:
With a bare timestamp cursor the ``created_at < cutoff`` filter
drops every row at the boundary instant; adding ``before_id``
- widens it to ``created_at = cutoff AND id < before_id`` so the
+ resolves its sequence/kind and includes the earlier tied entries so the
page boundary loses nothing.
"""
SessionLocal = setup_database_for_all_tests
diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.py
index bcb79c34a6..aeb8e425bc 100644
--- a/tests/web/test_route_table_parity.py
+++ b/tests/web/test_route_table_parity.py
@@ -1671,6 +1671,10 @@ 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 = {
+ # 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.
+ ("GET", "/api/chat/sessions/{}/messages"): [400],
# Counterpart of the 302 entry above; same single behaviour.
("GET", "/auth/change-password"): [401],
("GET", "/news/health"): [401],