fix(ТСН): сторож базы сообщает, если состояние загрузок не читается

Находка зайки: сбой чтения state.json проглатывался с pending=0, и сигнал «база
отстала от разобранного» исчезал без следа. Теперь нечитаемое состояние — находка
problem («отставание проверить не удалось»), а пустая дата загрузки не роняет
сравнение и не прячет сигнал.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
anor
2026-11-18 04:35:37 +10:00
co-authored by Claude Code
parent 70597599dc
commit 7a51900a49
2 changed files with 37 additions and 6 deletions
+12 -6
View File
@@ -412,12 +412,18 @@ def check_tsn_ref(seen: dict) -> tuple[list[dict], dict]:
pending = 0
try:
import ext_state
for key, rec in (ext_state.load_state().get("sources", {})
.get("niac_tsn", {}).items()):
if isinstance(rec, dict) and rec.get("extract_ok") and rec.get("fetched_at", "") > built:
pending += 1
except Exception: # noqa: BLE001 — состояние недоступно: не повод молчать
pending = 0
state = ext_state.load_state()
except Exception as e: # noqa: BLE001 — состояние недоступно: молчать нельзя
findings.append({"source": "tsn_ref", "level": "problem",
"message": f"состояние загрузок не читается ({type(e).__name__}) — "
"отставание базы ТСН проверить не удалось"})
return findings, seen
for _key, rec in (state.get("sources", {}).get("niac_tsn") or {}).items():
# fetched_at может быть пустым/None: сравнение со строкой тогда падало и
# прятало сигнал отставания
fetched = rec.get("fetched_at") or "" if isinstance(rec, dict) else ""
if isinstance(rec, dict) and rec.get("extract_ok") and fetched and fetched > built:
pending += 1
if pending:
findings.append({"source": "tsn_ref", "level": "update",
"message": f"{pending} документ(ов) разобраны после сборки базы "
+25
View File
@@ -99,3 +99,28 @@ def test_tsn_stage_served_when_db_ok(monkeypatch):
monkeypatch.setattr(tsn_ref, "latest_release", lambda: {"built_at": "2026-11-18T00:00:00Z"})
st = ext_status.tsn_stage()
assert st["status"] == "served" and "10" in st["label"]
def test_unreadable_state_is_reported_not_swallowed(monkeypatch):
"""Состояние загрузок не читается — про отставание базы проверить нельзя; молчать нельзя."""
import ext_state
monkeypatch.setattr(tsn_ref, "_problem_of", lambda path=None: None)
monkeypatch.setattr(tsn_ref, "latest_release", lambda: {"built_at": "2026-11-18T00:00:00Z"})
def boom():
raise OSError("state.json битый")
monkeypatch.setattr(ext_state, "load_state", boom)
findings, _ = ext_check.check_tsn_ref({})
assert findings and findings[0]["level"] == "problem", findings
assert "состояние" in findings[0]["message"].lower() or "не читается" in findings[0]["message"].lower()
def test_record_without_date_does_not_break_compare(monkeypatch):
"""fetched_at=None не должен ронять сравнение и прятать сигнал отставания."""
import ext_state
monkeypatch.setattr(tsn_ref, "_problem_of", lambda path=None: None)
monkeypatch.setattr(tsn_ref, "latest_release", lambda: {"built_at": "2026-11-18T00:00:00Z"})
monkeypatch.setattr(ext_state, "load_state", lambda: {"sources": {"niac_tsn": {
"x": {"extract_ok": True, "fetched_at": None}}}})
findings, _ = ext_check.check_tsn_ref({})
assert findings == []