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(logs): tie-break equal-timestamp log ordering by ResearchLog.id (#4661)

LearningCircuit84ce9a660499
diff --git a/changelog.d/+research-logs-tie-break-ordering.bugfix.md b/changelog.d/+research-logs-tie-break-ordering.bugfix.md
new file mode 100644
index 0000000000..95f3474c9e
--- /dev/null
+++ b/changelog.d/+research-logs-tie-break-ordering.bugfix.md
@@ -0,0 +1 @@
+Make research-log ordering deterministic when rows share a timestamp. ``ResearchLog.timestamp`` is not unique, so ``order_by(timestamp.desc()).limit(N)`` left the rows surviving a shared-timestamp boundary SQL-undefined — under dense logging the newest-N tail (and the "latest milestone" lookup) could vary between requests. Add ``ResearchLog.id`` as a tie-break across all three log-ordering sites (the ``/api/research/<id>/logs`` route, the ``get_logs_for_research`` helper behind ``/history/logs``, and the latest-milestone query). Follow-up to #4645.
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index c1261e6efd..f2424a8ac9 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -150,16 +150,24 @@ def get_logs_for_research(research_id, limit: int | None = None):
if limit is not None:
# Take the newest ``limit`` rows from the DB, then flip back
# to oldest-first ordering for the caller. Avoids loading
- # the entire table when only the tail is wanted.
+ # the entire table when only the tail is wanted. ``id`` is the
+ # tie-break: timestamps are not unique, so without it the rows
+ # surviving ``.limit()`` at a shared-timestamp boundary would
+ # be SQL-undefined.
log_results = list(
reversed(
- query.order_by(ResearchLog.timestamp.desc())
+ query.order_by(
+ ResearchLog.timestamp.desc(),
+ ResearchLog.id.desc(),
+ )
.limit(limit)
.all()
)
)
else:
- log_results = query.order_by(ResearchLog.timestamp.asc()).all()
+ log_results = query.order_by(
+ ResearchLog.timestamp.asc(), ResearchLog.id.asc()
+ ).all()
logs = []
for result in log_results:
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index aec60b9944..41b4d2fc34 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -1481,13 +1481,21 @@ def get_research_logs(research_id):
research_id=research_id
)
if limit is None:
- log_results = log_query.order_by(ResearchLog.timestamp).all()
+ log_results = log_query.order_by(
+ ResearchLog.timestamp, ResearchLog.id
+ ).all()
else:
# Take the newest ``limit`` rows at the SQL layer, then flip
# back to oldest-first so the response ordering is unchanged.
+ # ``id`` is the tie-break: timestamps are not unique, so without
+ # it the rows that survive ``.limit()`` at a shared-timestamp
+ # boundary would be SQL-undefined.
log_results = list(
reversed(
- log_query.order_by(ResearchLog.timestamp.desc())
+ log_query.order_by(
+ ResearchLog.timestamp.desc(),
+ ResearchLog.id.desc(),
+ )
.limit(limit)
.all()
)
@@ -1769,7 +1777,11 @@ def get_research_status(research_id):
milestone_log = (
db_session.query(ResearchLog)
.filter_by(research_id=research_id, level="MILESTONE")
- .order_by(ResearchLog.timestamp.desc())
+ # id tie-breaks equal timestamps so "latest" is
+ # deterministic (the most recently inserted milestone).
+ .order_by(
+ ResearchLog.timestamp.desc(), ResearchLog.id.desc()
+ )
.first()
)
if milestone_log:
diff --git a/tests/web/models/test_database.py b/tests/web/models/test_database.py
index 423c83bcab..d5401620d4 100644
--- a/tests/web/models/test_database.py
+++ b/tests/web/models/test_database.py
@@ -304,6 +304,66 @@ class TestGetLogsForResearch:
session.close()
engine.dispose()
+ def test_get_logs_with_limit_tie_breaks_equal_timestamps_by_id(self):
+ """When rows share an identical timestamp, ``id`` is the tie-break so
+ the newest ``limit`` selection is deterministic.
+
+ ``timestamp`` is not unique, so ``order_by(timestamp.desc()).limit(N)``
+ alone leaves the rows surviving the boundary SQL-undefined. All 10 rows
+ here share one timestamp; Log i has id i+1, so the newest 3 by id are
+ Log 7/8/9, returned oldest-first.
+ """
+ from datetime import datetime, timezone
+
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+
+ from local_deep_research.database.models import Base, ResearchLog
+ from local_deep_research.web.models.database import (
+ get_logs_for_research,
+ )
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ shared_time = datetime(2025, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
+ for i in range(10):
+ session.add(
+ ResearchLog(
+ research_id="test-rid",
+ timestamp=shared_time,
+ message=f"Log {i}",
+ module="test",
+ function="test",
+ line_no=i,
+ level="INFO",
+ )
+ )
+ session.commit()
+
+ try:
+ with patch(
+ "local_deep_research.web.models.database.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__ = Mock(
+ return_value=session
+ )
+ mock_get_session.return_value.__exit__ = Mock(
+ return_value=False
+ )
+
+ result = get_logs_for_research("test-rid", limit=3)
+
+ assert [r["message"] for r in result] == [
+ "Log 7",
+ "Log 8",
+ "Log 9",
+ ]
+ finally:
+ session.close()
+ engine.dispose()
+
def test_get_logs_without_limit_does_not_call_limit(self):
"""When limit is None, the function preserves legacy behaviour and
does not invoke .limit() on the query (returns every row, asc)."""
diff --git a/tests/web/routes/test_research_routes.py b/tests/web/routes/test_research_routes.py
index 9d96da0d87..8406adaf7b 100644
--- a/tests/web/routes/test_research_routes.py
+++ b/tests/web/routes/test_research_routes.py
@@ -420,13 +420,18 @@ class TestGetResearchLogsApi:
assert response.status_code == 404, response.status_code
@staticmethod
- def _seed_real_session(num_logs):
+ def _seed_real_session(num_logs, same_timestamp=False):
"""Build an in-memory SQLite session with one ResearchHistory row
- (id ``test-rid``) and ``num_logs`` ResearchLog rows at 1-minute
- intervals (messages ``Log 0``..``Log N-1``, oldest first). Returns the
- live session so the route is driven through real SQL — a mocked query
- chain returns a fixed list regardless of ``desc()``/``limit()`` and so
- cannot prove the newest-N ordering.
+ (id ``test-rid``) and ``num_logs`` ResearchLog rows (messages
+ ``Log 0``..``Log N-1``, inserted oldest-first so the autoincrement
+ ``id`` rises with the message index). Returns the live session so the
+ route is driven through real SQL — a mocked query chain returns a fixed
+ list regardless of ``desc()``/``limit()`` and so cannot prove the
+ newest-N ordering.
+
+ Rows are spaced 1 minute apart unless ``same_timestamp`` is set, in
+ which case every row shares one timestamp — used to prove the ``id``
+ tie-break makes the newest-N selection deterministic.
"""
from datetime import datetime, timedelta, timezone
@@ -454,10 +459,11 @@ class TestGetResearchLogsApi:
)
base_time = datetime(2025, 1, 1, tzinfo=timezone.utc)
for i in range(num_logs):
+ offset = timedelta(0) if same_timestamp else timedelta(minutes=i)
session.add(
ResearchLog(
research_id="test-rid",
- timestamp=base_time + timedelta(minutes=i),
+ timestamp=base_time + offset,
message=f"Log {i}",
module="test",
function="test",
@@ -560,6 +566,22 @@ class TestGetResearchLogsApi:
finally:
self._close_session(session)
+ def test_tie_break_on_equal_timestamps_is_deterministic(
+ self, authenticated_client
+ ):
+ """When rows share a timestamp, ``id`` tie-breaks so ?limit selects the
+ highest-id (most recently inserted) rows deterministically — without
+ the secondary key the surviving rows at the boundary are SQL-undefined.
+ Log i has id i+1, so newest-3-by-id is Log 7/8/9, oldest-first."""
+ session = self._seed_real_session(10, same_timestamp=True)
+ try:
+ resp = self._get_logs(authenticated_client, session, "?limit=3")
+ assert resp.status_code == 200, resp.status_code
+ messages = [r["message"] for r in resp.get_json()]
+ assert messages == ["Log 7", "Log 8", "Log 9"]
+ finally:
+ self._close_session(session)
+
class TestGetResearchStatusApi:
"""Tests for /api/research/<id>/status endpoint."""
@@ -581,6 +603,49 @@ class TestGetResearchStatusApi:
)
assert response.status_code == 404, response.status_code
+ def test_latest_milestone_tie_breaks_equal_timestamps_by_id(
+ self, authenticated_client
+ ):
+ """The /status latest-milestone ``.first()`` picks the highest-id
+ milestone among rows sharing the latest timestamp — deterministic,
+ not the SQL-undefined arbitrary row the prior single-key order_by
+ allowed. Driven through real SQL so the ``id`` tie-break is exercised
+ (a mocked ``.first()`` would ignore the order_by and pass regardless).
+ """
+ from datetime import datetime, timezone
+
+ from local_deep_research.database.models import ResearchLog
+
+ # Reuse the real-session seeding (research row, no INFO logs), then add
+ # 3 MILESTONE rows sharing one timestamp; ids rise with insertion so
+ # "Milestone 2" is the highest-id (most recently inserted) one.
+ session = TestGetResearchLogsApi._seed_real_session(0)
+ shared_time = datetime(2025, 1, 1, tzinfo=timezone.utc)
+ for i in range(3):
+ session.add(
+ ResearchLog(
+ research_id="test-rid",
+ timestamp=shared_time,
+ message=f"Milestone {i}",
+ module="test",
+ function="test",
+ line_no=i,
+ level="MILESTONE",
+ )
+ )
+ session.commit()
+ try:
+ with patch(f"{_RR}.get_user_db_session") as mock_db:
+ mock_db.return_value.__enter__ = lambda s: session
+ mock_db.return_value.__exit__ = MagicMock(return_value=False)
+ resp = authenticated_client.get(
+ f"{RESEARCH_PREFIX}/api/research/test-rid/status"
+ )
+ assert resp.status_code == 200, resp.status_code
+ assert resp.get_json()["log_entry"]["message"] == "Milestone 2"
+ finally:
+ TestGetResearchLogsApi._close_session(session)
+
class TestQueueStatusApi:
"""Tests for queue status API endpoints."""