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(queue): preserve JSON-string research metadata (#7219)

LearningCircuitc803d3435cd8
diff --git a/changelog.d/7214.bugfix.md b/changelog.d/7214.bugfix.md
new file mode 100644
index 0000000000..3c4b05945e
--- /dev/null
+++ b/changelog.d/7214.bugfix.md
@@ -0,0 +1 @@
+Preserve saved research settings and submission metadata when a queued error or termination update encounters metadata stored as a JSON string, and retain the malformed-metadata fallback when oversized integers or excessively nested JSON cannot be decoded.
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.py
index db29951776..a4937936d1 100644
--- a/src/local_deep_research/web/queue/processor_v2.py
+++ b/src/local_deep_research/web/queue/processor_v2.py
@@ -44,6 +44,7 @@ from ..routes.research_validation import (
)
from ..research_state import get_user_research_start_lock
from ..services.research_service import (
+ _parse_research_metadata,
clamp_user_max_concurrent,
run_research_process,
start_research_process,
@@ -2004,9 +2005,7 @@ class QueueProcessorV2:
research.error_message = op_data.get("error_message")
incoming_meta = op_data.get("metadata")
existing_meta = research.research_meta
- if isinstance(existing_meta, dict) and isinstance(
- incoming_meta, dict
- ):
+ if isinstance(incoming_meta, dict):
# Merge, never wholesale-replace: a bare
# {"terminated_at": ...} from handle_termination
# must not wipe the row's settings_snapshot (and
@@ -2014,7 +2013,11 @@ class QueueProcessorV2:
# resolves report.uncited_sources_mode from.
# Callers that already merged (the failure path)
# are unaffected: re-merging is idempotent.
- merged_meta = dict(existing_meta)
+ # Read legacy JSON-string metadata using the
+ # same normalization as completion updates.
+ merged_meta = _parse_research_metadata(
+ existing_meta
+ )
merged_meta.update(incoming_meta)
research.research_meta = merged_meta
else:
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 9282c4e7e8..34d39dc04a 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -260,7 +260,11 @@ def _parse_research_metadata(research_meta) -> dict:
try:
parsed = json.loads(research_meta)
return dict(parsed) if isinstance(parsed, dict) else {}
- except json.JSONDecodeError:
+ except (ValueError, RecursionError):
+ # JSONDecodeError is a ValueError, but the decoder's integer
+ # digit limit raises a plain ValueError. Keep the same fallback
+ # for unreadable legacy metadata, including nesting beyond the
+ # decoder's recursion limit.
logger.exception("Failed to parse research_meta as JSON")
return {}
return {}
diff --git a/tests/web/queue/test_processor_v2.py b/tests/web/queue/test_processor_v2.py
index cd62356bac..39e1e85aad 100644
--- a/tests/web/queue/test_processor_v2.py
+++ b/tests/web/queue/test_processor_v2.py
@@ -10,9 +10,13 @@ Tests cover:
- Error handling
"""
+import json
+import sys
import threading
from unittest.mock import Mock, MagicMock, patch
+import pytest
+
class TestQueueProcessorV2Init:
"""Tests for QueueProcessorV2 initialization."""
@@ -425,10 +429,23 @@ class TestErrorUpdateMergesMetadata:
snapshot back-fill closed.
"""
+ @pytest.fixture
+ def bounded_json_integer_decoder(self):
+ """Exercise the decoder limit even when the process disables it."""
+ previous = sys.get_int_max_str_digits()
+ sys.set_int_max_str_digits(4300)
+ try:
+ yield
+ finally:
+ sys.set_int_max_str_digits(previous)
+
+ @pytest.mark.parametrize(
+ "storage_format", ["native", "legacy_text", "json_string"]
+ )
def test_termination_update_preserves_snapshot_and_submission(
- self, tmp_path
+ self, tmp_path, storage_format
):
- from sqlalchemy import create_engine
+ from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from local_deep_research.constants import ResearchStatus
@@ -446,6 +463,11 @@ class TestErrorUpdateMergesMetadata:
try:
snapshot = {"report.uncited_sources_mode": {"value": "strict"}}
submission = {"chat_session_id": "sess"}
+ original_meta = {
+ "submission": submission,
+ "settings_snapshot": snapshot,
+ "terminated_at": "earlier value",
+ }
sess.add(
ResearchHistory(
id="r-term-1",
@@ -453,14 +475,25 @@ class TestErrorUpdateMergesMetadata:
mode="quick",
status=ResearchStatus.IN_PROGRESS,
created_at="2026-01-01T00:00:00+00:00",
- research_meta={
- "submission": submission,
- "settings_snapshot": snapshot,
- },
+ research_meta=original_meta,
)
)
sess.commit()
+ if storage_format != "native":
+ stored = json.dumps(original_meta)
+ if storage_format == "json_string":
+ stored = json.dumps(stored)
+ sess.execute(
+ text(
+ "UPDATE research_history SET research_meta=:metadata "
+ "WHERE id=:research_id"
+ ),
+ {"metadata": stored, "research_id": "r-term-1"},
+ )
+ sess.commit()
+ sess.expire_all()
+
processor = QueueProcessorV2()
processor.queue_error_update(
username="testuser",
@@ -477,6 +510,7 @@ class TestErrorUpdateMergesMetadata:
== 1
)
+ sess.expire_all()
row = sess.query(ResearchHistory).filter_by(id="r-term-1").first()
assert row.status == ResearchStatus.SUSPENDED
assert (
@@ -490,8 +524,31 @@ class TestErrorUpdateMergesMetadata:
sess.close()
engine.dispose()
- def test_error_update_still_applies_without_existing_meta(self, tmp_path):
- """Rows with no prior meta degrade to the incoming dict."""
+ @pytest.mark.usefixtures("bounded_json_integer_decoder")
+ @pytest.mark.parametrize(
+ "existing_meta",
+ [
+ None,
+ "not valid JSON",
+ "null",
+ '"scalar"',
+ "[]",
+ 7,
+ [],
+ pytest.param(
+ '{"count":' + "1" * 6000 + "}",
+ id="json-integer-limit",
+ ),
+ pytest.param(
+ "[" * 16000 + "0" + "]" * 16000,
+ id="json-nesting-limit",
+ ),
+ ],
+ )
+ def test_error_update_still_applies_without_existing_meta(
+ self, tmp_path, existing_meta
+ ):
+ """Absent, malformed, or non-object metadata uses the incoming dict."""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
@@ -515,7 +572,7 @@ class TestErrorUpdateMergesMetadata:
mode="quick",
status=ResearchStatus.IN_PROGRESS,
created_at="2026-01-01T00:00:00+00:00",
- research_meta=None,
+ research_meta=existing_meta,
)
)
sess.commit()
@@ -536,6 +593,7 @@ class TestErrorUpdateMergesMetadata:
== 1
)
+ sess.expire_all()
row = sess.query(ResearchHistory).filter_by(id="r-term-2").first()
assert row.status == ResearchStatus.FAILED
assert row.research_meta == {"phase": "error"}