~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(db): tolerate malformed legacy research JSON (#7012)
Ziyang Guocebb95279461
diff --git a/changelog.d/6533.bugfix.md b/changelog.d/6533.bugfix.mdnew file mode 100644index 0000000000..914d90607b--- /dev/null+++ b/changelog.d/6533.bugfix.md@@ -0,0 +1 @@+Legacy research rows with unparseable JSON in `progress_log` or `research_meta` now load with the damaged field absent, so one row no longer breaks the status endpoint or hides the entire history list. JSON writes and subscription filters retain their stored format.diff --git a/src/local_deep_research/database/models/research.py b/src/local_deep_research/database/models/research.pyindex 17688ead0b..ca9a78dcfc 100644--- a/src/local_deep_research/database/models/research.py+++ b/src/local_deep_research/database/models/research.py@@ -3,7 +3,9 @@ Core research models for tasks, queries, and results."""import enum+import json+from loguru import loggerfrom sqlalchemy import (JSON,Column,@@ -17,6 +19,8 @@ from sqlalchemy import (text,)from sqlalchemy.orm import relationship+from sqlalchemy.sql import operators+from sqlalchemy.types import TypeDecoratorfrom sqlalchemy_utc import UtcDateTime, utcnow@@ -24,6 +28,66 @@ from ...constants import ResearchStatusfrom .base import Base+class LenientJSON(TypeDecorator):+ """Read malformed legacy JSON text as absent without changing writes.++ Releases before v0.5 persisted this column as TEXT through+ ``json.dumps``, and the stock ``JSON`` result processor raises+ ``JSONDecodeError`` while such a row is being loaded whenever the stored+ text is not valid JSON (the empty string from an interrupted write, a+ truncated ``json.dumps`` output, a ``str(dict)`` repr). That raise+ happens during the query, above every handler ``try``, so+ ``GET /history/status/{research_id}`` answered 500 for the row instead of+ degrading to an empty log or metadata (#6533, #7017). A malformed+ ``research_meta`` value could also make one row take down the entire+ history list.++ Reads therefore return ``None`` for an unparseable value — the absent+ value readers of both columns already handle — and the load can no+ longer fail. Writes are untouched: the stock ``JSON`` bind path still+ serializes Python objects, so the DDL and the stored format are+ unchanged and no migration is needed.+ """++ impl = JSON+ cache_ok = True++ def coerce_compared_value(self, op, value):+ # TypeDecorator otherwise JSON-encodes a LIKE pattern as a JSON+ # string. Subscription lookups compare against the stored TEXT form,+ # so their pattern must be bound as an ordinary SQL string. Delegate+ # other operators to JSON to preserve its key/index coercion rules.+ if op in (+ operators.like_op,+ operators.not_like_op,+ operators.ilike_op,+ operators.not_ilike_op,+ ):+ return String()+ return self.impl.coerce_compared_value(op, value)++ def result_processor(self, dialect, coltype):+ def process(value):+ # Only TEXT carriers need decoding. A backend with a native+ # JSON type hands back an already-parsed object — list, dict,+ # or a scalar such as 5 / true / null — and must not be fed to+ # json.loads, which would reject the non-string scalars and+ # turn a perfectly valid value into None. LDR ships on+ # SQLite/SQLCipher only, so this is defensive, not load-bearing.+ if not isinstance(value, (str, bytes, bytearray)):+ return value+ try:+ return json.loads(value)+ except (TypeError, ValueError):+ logger.warning(+ "Unparseable JSON value in a research_history column; "+ "treating it as absent"+ )+ return None++ return process++class ResearchTask(Base):"""Main research tasks that users create.@@ -270,9 +334,9 @@ class ResearchHistory(Base):# Report content stored in databasereport_content = Column(Text)# Additional metadata about the research.- research_meta = Column(JSON)+ research_meta = Column(LenientJSON)# Latest progress log message.- progress_log = Column(JSON)+ progress_log = Column(LenientJSON)# Current progress of the research (as a percentage).progress = Column(Integer)# Title of the research report.diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.pyindex 6ba5ddc212..a76bb643ad 100644--- a/src/local_deep_research/web/routers/research.py+++ b/src/local_deep_research/web/routers/research.py@@ -1548,6 +1548,20 @@ def terminate_research(else:current_log = []+ # The column is a log LIST, but a JSON column accepts any shape+ # and the reader hands one back verbatim: a legacy TEXT scalar+ # ('true') parses to a bool here, and a value the driver already+ # decoded arrives as an int. Appending to either raises+ # AttributeError outside the try above — one malformed scalar+ # would turn a Stop request into a 500. A non-list is not a log;+ # start a fresh one instead of failing the request.+ if not isinstance(current_log, list):+ logger.warning(+ "Ignoring a non-list progress_log for research {}",+ research_id,+ )+ current_log = []+current_log.append(log_entry)research.progress_log = current_logresearch.status = ResearchStatus.SUSPENDEDdiff --git a/tests/database/schema_change_rule.py b/tests/database/schema_change_rule.pyindex a831d36477..9786bf2b43 100644--- a/tests/database/schema_change_rule.py+++ b/tests/database/schema_change_rule.py@@ -38,6 +38,9 @@ when a comment, a docstring or a line wrap moves, and neither Alembic nor``create_all()`` can see any of those. :func:`drop_comment_only_edits`lets the callers filter those out before asking :func:`violations`, sothe gate fires on changes that can actually reach a user's database.+The callers also exclude one byte-exact, schema-neutral JSON reader edit+from #7012. Its SQLite column DDL is checked separately; any later edit+changes the blob and again requires a migration."""import ast@@ -86,6 +89,31 @@ VERSIONS_DIR = "versions"MIN_REVISIONS = 30MIN_MODEL_FILES = 20+# #7012 replaces only the read processor for these two JSON columns. The+# decorator still emits SQL JSON and does not change the bind path. These+# exact before/after blobs are reviewed as schema-neutral; any further edit+# to research.py changes its blob and again requires a migration. The live+# SQLite DDL is pinned in test_research_models.py.+_SCHEMA_NEUTRAL_MODEL_EDIT = {+ "src/local_deep_research/database/models/research.py": (+ "17688ead0b4210d9e5e82db4e851f3de516aad7b",+ "ca9a78dcfc5bc631ce74b4cca60a025edf652171",+ ),+}+++def drop_proven_schema_neutral_edits(+ changes: dict, before_blobs: dict, after_blobs: dict+) -> dict:+ """Exempt only byte-exact model edits proven not to alter emitted DDL."""+ kept = [+ path+ for path in changes["edited"]+ if (before_blobs.get(path), after_blobs.get(path))+ != _SCHEMA_NEUTRAL_MODEL_EDIT.get(path)+ ]+ return {**changes, "edited": kept}+def is_revision(path: str) -> bool:"""Is ``path`` an Alembic revision file rather than migration plumbing?diff --git a/tests/database/test_migration_chain_integrity.py b/tests/database/test_migration_chain_integrity.pyindex a3cc0993e2..4fc1507f16 100644--- a/tests/database/test_migration_chain_integrity.py+++ b/tests/database/test_migration_chain_integrity.py@@ -101,6 +101,7 @@ from tests.database.schema_change_rule import (MODELS_SUBTREE,classify,drop_comment_only_edits,+ drop_proven_schema_neutral_edits,is_revision,violations,)@@ -803,6 +804,28 @@ def test_the_schema_change_rule_is_pinned_without_touching_git():assert len(violations(nothing, unparseable)) == 1+def test_schema_neutral_json_reader_exception_is_byte_exact():+ """A later model edit must not inherit #7012's no-migration exception."""+ path = "src/local_deep_research/database/models/research.py"+ before = {path: "17688ead0b4210d9e5e82db4e851f3de516aad7b"}+ after = {path: "ca9a78dcfc5bc631ce74b4cca60a025edf652171"}+ exact = classify(before, after)+ assert (+ drop_proven_schema_neutral_edits(exact, before, after)["edited"] == []+ )++ later = {path: "different-model-blob"}+ assert drop_proven_schema_neutral_edits(+ classify(before, later), before, later+ )["edited"] == [path]+ other_path = "src/local_deep_research/database/models/other.py"+ other_before = {other_path: before[path]}+ other_after = {other_path: after[path]}+ assert drop_proven_schema_neutral_edits(+ classify(other_before, other_after), other_before, other_after+ )["edited"] == [other_path]++def test_only_files_alembic_can_load_as_revisions_count_as_revisions():"""``is_revision`` itself, since both halves of the rule turn on it.@@ -968,12 +991,12 @@ def test_this_branch_edits_no_revision_and_migrates_every_model_change():)read_pair = _source_pair_reader(base, "HEAD")- model_changes = drop_comment_only_edits(- classify(- _source_file_blobs(base, source_files),- _source_file_blobs("HEAD", source_files),- ),- read_pair,+ model_before = _source_file_blobs(base, source_files)+ model_after = _source_file_blobs("HEAD", source_files)+ model_changes = drop_proven_schema_neutral_edits(+ drop_comment_only_edits(classify(model_before, model_after), read_pair),+ model_before,+ model_after,)revision_changes = drop_comment_only_edits(classify(revisions_before, _blobs_under("HEAD", MIGRATIONS_SUBTREE)),diff --git a/tests/database/test_research_models.py b/tests/database/test_research_models.pyindex cf80256bac..3f4a56dc63 100644--- a/tests/database/test_research_models.py+++ b/tests/database/test_research_models.py@@ -1,10 +1,11 @@"""Tests for research-related database models."""+import jsonimport uuidfrom datetime import datetime, timezoneimport pytest-from sqlalchemy import create_engine+from sqlalchemy import create_engine, textfrom sqlalchemy.orm import sessionmakerfrom local_deep_research.database.models import (@@ -134,6 +135,233 @@ class TestResearchModels:assert len(saved.progress_log["steps"]) == 4assert saved.progress_log["current_step"] == 4+ @pytest.mark.parametrize(+ "stored_log",+ [+ "{'steps': []}", # str(dict) repr, never valid JSON+ "", # empty TEXT from an interrupted legacy write+ "{truncated", # truncated json.dumps output+ ],+ ids=["str-repr", "empty-string", "truncated"],+ )+ def test_progress_log_unparseable_legacy_row_loads_as_absent(+ self, session, stored_log+ ):+ """A legacy TEXT row that is not valid JSON must not break the load.++ The stock ``JSON`` result processor raised ``JSONDecodeError``+ while the row was being loaded, above every handler ``try``, so+ ``GET /history/status/{research_id}`` answered 500 for such a row+ instead of degrading to an empty log (#6533). The column now reads+ the value as ``None`` — the "no log" value every reader already+ handles — and the load succeeds.+ """+ research_id = f"legacy-{stored_log[:6] or 'empty'}"+ session.execute(+ text(+ "INSERT INTO research_history "+ "(id, query, mode, status, created_at, progress_log) "+ "VALUES (:id, :query, :mode, :status, :created_at, :log)"+ ),+ {+ "id": research_id,+ "query": "legacy row",+ "mode": "detailed",+ "status": "completed",+ "created_at": "2024-01-01T12:00:00",+ "log": stored_log,+ },+ )+ session.commit()++ loaded = (+ session.query(ResearchHistory).filter_by(id=research_id).first()+ )++ assert loaded is not None+ assert loaded.progress_log is None+ # What the status endpoint does with the value: an empty log.+ assert json.loads(loaded.progress_log or "[]") == []++ @pytest.mark.parametrize(+ "stored_meta",+ ["{'subscription': ", "", "{truncated"],+ ids=["str-repr", "empty-string", "truncated"],+ )+ def test_research_meta_unparseable_row_does_not_hide_history(+ self, session, stored_meta+ ):+ """One corrupt legacy metadata cell must not break row or list loads."""+ bad_id = f"legacy-meta-{stored_meta[:6] or 'empty'}"+ session.execute(+ text(+ "INSERT INTO research_history "+ "(id, query, mode, status, created_at, research_meta) "+ "VALUES (:id, :query, :mode, :status, :created_at, :meta)"+ ),+ {+ "id": bad_id,+ "query": "corrupt legacy row",+ "mode": "detailed",+ "status": "completed",+ "created_at": "2024-01-01T12:00:00",+ "meta": stored_meta,+ },+ )+ good = ResearchHistory(+ id="good-neighbor",+ query="intact row",+ mode="detailed",+ status="completed",+ created_at="2024-01-02T12:00:00",+ research_meta={"headline": "still visible"},+ )+ session.add(good)+ session.commit()++ bad = session.query(ResearchHistory).filter_by(id=bad_id).first()+ assert bad is not None+ assert bad.research_meta is None+ # The history endpoint selects this column for every listed row.+ rows = session.query(+ ResearchHistory.id, ResearchHistory.research_meta+ ).all()+ assert {row.id: row.research_meta for row in rows} == {+ bad_id: None,+ "good-neighbor": {"headline": "still visible"},+ }++ def test_research_meta_subscription_like_filter_keeps_stored_format(+ self, session+ ):+ """The news subscription lookup still matches JSON's TEXT form."""+ session.add(+ ResearchHistory(+ id="subscription-match",+ query="subscription run",+ mode="detailed",+ status="completed",+ created_at="2024-01-01T12:00:00",+ research_meta={"subscription_id": "sub-42"},+ )+ )+ session.commit()++ matched = (+ session.query(ResearchHistory.id)+ .filter(+ ResearchHistory.research_meta.like(+ '%"subscription_id": "sub-42"%', escape="\\"+ )+ )+ .all()+ )+ assert [row.id for row in matched] == ["subscription-match"]++ indexed = (+ session.query(ResearchHistory.id)+ .filter(+ ResearchHistory.research_meta["subscription_id"].as_string()+ == "sub-42"+ )+ .all()+ )+ assert [row.id for row in indexed] == ["subscription-match"]++ def test_lenient_json_keeps_sqlite_column_types(self, session):+ """The read decorator must not need a schema migration."""+ types = {+ row.name: row.type+ for row in session.execute(+ text("PRAGMA table_info(research_history)")+ )+ }+ assert types["progress_log"] == "JSON"+ assert types["research_meta"] == "JSON"++ @pytest.mark.parametrize(+ "stored_scalar",+ [5, 0, True, False],+ ids=["int", "zero", "true", "false"],+ )+ def test_lenient_json_passes_a_native_scalar_carrier_through(+ self, session, stored_scalar+ ):+ """A scalar the driver already decoded is returned untouched.++ ``progress_log`` is ``JSON``-declared, so an ORM write of a scalar+ binds ``json.dumps(scalar)`` and SQLite's NUMERIC affinity stores+ ``5`` / ``0`` as integers, handing the result processor a real+ ``int``. Feeding that to ``json.loads`` raises ``TypeError``, which+ the first cut of this gate caught and turned into ``None`` — a+ perfectly valid value silently replaced by the absent one. The gate+ now decodes only TEXT/BLOB carriers and passes everything else+ through.++ No writer stores a scalar (all four write sites assign a list), so+ the malformed-row cases above cannot reach this branch: they pass+ equally on the old code, and this case does not.+ """+ research_id = f"scalar-{stored_scalar!r}"+ session.add(+ ResearchHistory(+ id=research_id,+ query="scalar carrier",+ mode="detailed",+ status="completed",+ created_at="2024-01-01T12:00:00",+ progress_log=stored_scalar,+ )+ )+ session.commit()++ loaded = (+ session.query(ResearchHistory).filter_by(id=research_id).first()+ )++ assert loaded is not None+ assert loaded.progress_log == stored_scalar+ assert loaded.progress_log is not None++ @pytest.mark.parametrize(+ "carrier",+ [b"[]", bytearray(b"[]")],+ ids=["bytes", "bytearray"],+ )+ def test_lenient_json_decodes_binary_carriers(self, carrier):+ """Every binary TEXT carrier is decoded, not passed through raw.++ The gate's job on these is the same as on ``str``: SQLite hands+ back ``bytes`` for a BLOB-stored value, and that value still has to+ reach the reader as the parsed log.+ """+ from local_deep_research.database.models.research import LenientJSON++ process = LenientJSON().result_processor(None, None)++ assert process(carrier) == []++ def test_lenient_json_passes_a_decoded_object_through_untouched(self):+ """Anything that is not a TEXT carrier is returned exactly as given.++ A backend with a native JSON type hands the processor a parsed+ object (list, dict) or a scalar (``5``, ``True``); ``memoryview``+ is a value no SQLite driver emits for a JSON column but is the same+ case — an already-decoded object the gate must not reinterpret.+ Feeding any of them to ``json.loads`` raises ``TypeError``, which+ the first cut of this gate caught and turned into ``None``.+ """+ from local_deep_research.database.models.research import LenientJSON++ process = LenientJSON().result_processor(None, None)++ assert process([{"time": "t"}]) == [{"time": "t"}]+ assert process({"a": 1}) == {"a": 1}+ assert process(None) is None+ assert process(5) == 5+ assert process(True) is True+ assert bytes(process(memoryview(b"..."))) == b"..."+def test_research_task_creation(self, session):"""Test ResearchTask model."""task = ResearchTask(diff --git a/tests/database/test_upgrade_from_pre_migration_install.py b/tests/database/test_upgrade_from_pre_migration_install.pyindex 6e31a84d2c..7fa434427c 100644--- a/tests/database/test_upgrade_from_pre_migration_install.py+++ b/tests/database/test_upgrade_from_pre_migration_install.py@@ -117,6 +117,7 @@ from tests.database.schema_change_rule import (MODELS_SUBTREE,classify,drop_comment_only_edits,+ drop_proven_schema_neutral_edits,violations,)@@ -583,8 +584,13 @@ def test_pr_edits_no_shipped_revision_and_ships_a_migration():classify(revisions_before, _tracked_files("HEAD", MIGRATIONS_SUBTREE)),read_pair,)- model_changes = drop_comment_only_edits(- classify(models_before, _guarded_model_files("HEAD")), read_pair+ models_after = _guarded_model_files("HEAD")+ model_changes = drop_proven_schema_neutral_edits(+ drop_comment_only_edits(+ classify(models_before, models_after), read_pair+ ),+ models_before,+ models_after,)problems = violations(model_changes, revision_changes)diff --git a/tests/web/routers/test_research_mutating_route_effects.py b/tests/web/routers/test_research_mutating_route_effects.pyindex 8094cc4bc4..51c3fc895b 100644--- a/tests/web/routers/test_research_mutating_route_effects.py+++ b/tests/web/routers/test_research_mutating_route_effects.py@@ -302,6 +302,45 @@ def test_terminate_recovers_from_an_unparseable_progress_log(assert len(row.progress_log) == 1+ "stored_log", ["true", 5], ids=["text-scalar", "numeric-carrier"]+)+def test_terminate_recovers_from_a_non_list_progress_log(+ authenticated_client, db, stored_log+):+ """A JSON column accepts any shape, and Stop must not care.++ ``progress_log`` is a ``JSON`` column, so nothing constrains it to a+ list: a legacy TEXT ``"true"`` parses to a bool, and a value the driver+ already decoded arrives as an int (SQLite's NUMERIC affinity stores+ ``json.dumps(5)`` as an integer). Either one reached+ ``current_log.append`` in the parse arm, raising ``AttributeError``+ outside the ``try`` -- so a single odd row turned Stop into a 500 and+ left the run alive. The column is a log or it is nothing; a non-list+ starts a fresh log instead of failing the request.++ The unparseable case above stops one branch earlier (the ``except``),+ so neither test covers the other's path.+ """+ row = _add_research(+ db, "res-1", status="in_progress", progress_log=stored_log+ )+ cleanup = MagicMock()++ with _patch_session(db):+ for patcher in _terminate_mocks(active=True, cleanup=cleanup):+ patcher.start()+ try:+ response = authenticated_client.post("/api/terminate/res-1")+ finally:+ patch.stopall()++ assert response.status_code == 200, response.text[:300]+ assert isinstance(row.progress_log, list)+ assert len(row.progress_log) == 1+ assert row.status == "suspended"++def test_terminate_during_the_spawn_grace_window_leaves_queue_state_alone(authenticated_client, db):