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(journal-quality): stream OpenAlex partitions instead of buffering (#5505)

Dhruv Diwakirti058a3ce6bd12
diff --git a/changelog.d/4383.bugfix.md b/changelog.d/4383.bugfix.md
new file mode 100644
index 0000000000..9a4f07d19d
--- /dev/null
+++ b/changelog.d/4383.bugfix.md
@@ -0,0 +1 @@
+Decode OpenAlex snapshot partitions record by record so the journal-quality download no longer holds a whole partition in memory, which could exhaust RAM on smaller hosts and leave the container thrashing in swap.
diff --git a/src/local_deep_research/journal_quality/data_sources/_openalex_common.py b/src/local_deep_research/journal_quality/data_sources/_openalex_common.py
index 65f7f0dcc0..0d369cbddd 100644
--- a/src/local_deep_research/journal_quality/data_sources/_openalex_common.py
+++ b/src/local_deep_research/journal_quality/data_sources/_openalex_common.py
@@ -85,7 +85,7 @@ def iter_partitions(
timeout: int = 120,
max_retries: int = _PARTITION_MAX_RETRIES,
backoff_times: tuple = _PARTITION_BACKOFF_SECONDS,
-) -> Iterator[Tuple[int, int, list[dict]]]:
+) -> Iterator[Tuple[int, int, Iterator[dict]]]:
"""Download each partition, yielding ``(idx, total_parts, records)``.
Shared between ``openalex.py`` and ``institutions.py`` so the
@@ -97,6 +97,11 @@ def iter_partitions(
invocations — those need caller-specific state (running record
count, schema-drift counters) that doesn't belong in the helper.
+ ``records`` decodes lazily and is valid only until this generator
+ is advanced — the gzip handle closes and the tmp file is removed
+ when the next partition is requested, so consume it in place.
+ Deferring it raises ``ValueError: I/O operation on closed file``.
+
Args:
entries: ``manifest["files"]`` — each dict has ``url``
starting with ``s3://openalex/``.
@@ -126,10 +131,31 @@ def iter_partitions(
malformed_total = 0
total_parts = len(entries)
+ def decode(fh, idx: int) -> Iterator[dict]:
+ nonlocal malformed_total
+ for line in fh:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ rec = json.loads(line)
+ except (json.JSONDecodeError, ValueError):
+ malformed_total += 1
+ if malformed_total <= 10:
+ logger.warning(
+ f"{label} partition {idx}: skipping malformed JSON line"
+ )
+ elif malformed_total == 11:
+ logger.warning(
+ f"{label} partition {idx}: further "
+ "malformed lines suppressed"
+ )
+ continue
+ yield rec
+
for idx, entry in enumerate(entries):
part_url = s3_to_https(entry["url"])
tmp_part = data_dir / f".{file_prefix}_part_{idx}.gz"
- records: list[dict] = []
try:
# consume_body=True: an OpenAlex S3 partition is ~10 MB
@@ -148,33 +174,15 @@ def iter_partitions(
)
resp.raise_for_status()
tmp_part.write_bytes(resp.content)
+ # Unpin the compressed body; the suspended frame would
+ # otherwise hold it until the caller drains the partition.
+ del resp
with gzip.open(tmp_part, "rt", encoding="utf-8") as fh:
- for line in fh:
- line = line.strip()
- if not line:
- continue
- try:
- rec = json.loads(line)
- except (json.JSONDecodeError, ValueError):
- malformed_total += 1
- if malformed_total <= 10:
- logger.warning(
- f"{label} partition {idx}: skipping "
- f"malformed JSON line"
- )
- elif malformed_total == 11:
- logger.warning(
- f"{label} partition {idx}: further "
- "malformed lines suppressed"
- )
- continue
- records.append(rec)
+ yield idx, total_parts, decode(fh, idx)
finally:
tmp_part.unlink(missing_ok=True)
- yield idx, total_parts, records
-
if malformed_total:
logger.warning(
f"{label}: {malformed_total:,} malformed lines skipped across "
diff --git a/tests/journal_quality/test_openalex_common.py b/tests/journal_quality/test_openalex_common.py
index 0ad3bf1b07..54ba28fbfc 100644
--- a/tests/journal_quality/test_openalex_common.py
+++ b/tests/journal_quality/test_openalex_common.py
@@ -10,10 +10,13 @@ from __future__ import annotations
import gzip
import io
+import json
+from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
+from local_deep_research.journal_quality.data_sources import _openalex_common
from local_deep_research.journal_quality.data_sources._openalex_common import (
iter_partitions,
validate_manifest_entries,
@@ -71,23 +74,96 @@ class TestIterPartitions:
]
safe_get = MagicMock(side_effect=[_response(p) for p in parts])
- result = list(
- iter_partitions(
+ result = [
+ (idx, total, [r["id"] for r in records])
+ for idx, total, records in iter_partitions(
entries,
tmp_path,
file_prefix="t",
label="test",
safe_get=safe_get,
)
+ ]
+
+ assert result == [(0, 2, ["S1", "S2"]), (1, 2, ["S3"])]
+
+ def test_records_decode_lazily(self, tmp_path, monkeypatch):
+ """Records decode on demand, not all up front (#4383).
+
+ Counts decodes rather than sampling heap size so the assertion
+ is deterministic.
+ """
+ decoded = 0
+
+ def counting_loads(line, *args, **kwargs):
+ nonlocal decoded
+ decoded += 1
+ return json.loads(line, *args, **kwargs)
+
+ # Patch the module's binding, not stdlib json — an unrelated
+ # decode in the same worker would inflate the counts.
+ monkeypatch.setattr(
+ _openalex_common,
+ "json",
+ SimpleNamespace(
+ loads=counting_loads,
+ JSONDecodeError=json.JSONDecodeError,
+ ),
)
- assert len(result) == 2
- idx0, total0, recs0 = result[0]
- idx1, total1, recs1 = result[1]
- assert (idx0, total0) == (0, 2)
- assert (idx1, total1) == (1, 2)
- assert [r["id"] for r in recs0] == ["S1", "S2"]
- assert [r["id"] for r in recs1] == ["S3"]
+ entries = [{"url": "s3://openalex/data/jsonl/sources/part_0.gz"}]
+ safe_get = MagicMock(
+ return_value=_response(
+ _gz_lines([b'{"id": "S%d"}' % n for n in range(50)])
+ )
+ )
+
+ partitions = 0
+ for _idx, _total, records in iter_partitions(
+ entries,
+ tmp_path,
+ file_prefix="lazy_test",
+ label="test",
+ safe_get=safe_get,
+ ):
+ partitions += 1
+ stream = iter(records)
+ assert next(stream)["id"] == "S0"
+ assert decoded == 1
+ assert next(stream)["id"] == "S1"
+ assert decoded == 2
+
+ rest = [r["id"] for r in stream]
+ assert rest[-1] == "S49"
+ assert decoded == 50
+
+ assert partitions == 1
+
+ def test_records_expire_when_generator_advances(self, tmp_path):
+ """Stashing a partition's records fails loudly, not silently."""
+ entries = [
+ {"url": "s3://openalex/data/jsonl/sources/part_0.gz"},
+ {"url": "s3://openalex/data/jsonl/sources/part_1.gz"},
+ ]
+ parts = [
+ _gz_lines([b'{"id": "S1"}']),
+ _gz_lines([b'{"id": "S2"}']),
+ ]
+ safe_get = MagicMock(side_effect=[_response(p) for p in parts])
+
+ stashed = [
+ records
+ for _idx, _total, records in iter_partitions(
+ entries,
+ tmp_path,
+ file_prefix="expired_test",
+ label="test",
+ safe_get=safe_get,
+ )
+ ]
+
+ with pytest.raises(ValueError, match="closed file"):
+ list(stashed[0])
def test_cleans_up_tmp_files(self, tmp_path):
"""Temp partition files must be deleted after each partition."""
@@ -241,16 +317,15 @@ class TestIterPartitions:
lines = [b'{"id": "GOOD"}'] + [b"garbage {{"] * 15
safe_get = MagicMock(return_value=_response(_gz_lines(lines)))
- result = list(
- iter_partitions(
+ result = [
+ [r["id"] for r in records]
+ for _idx, _total, records in iter_partitions(
entries,
tmp_path,
file_prefix="malformed_test",
label="test",
safe_get=safe_get,
)
- )
+ ]
- assert len(result) == 1
- _, _, recs = result[0]
- assert [r["id"] for r in recs] == ["GOOD"]
+ assert result == [["GOOD"]]