fix(обход): сбой сети не снимает ожидания, здоровье краснеет при сбоях

Уход зоны доказывается только успешно прочитанным списком зон субъекта:
при сбое списка зон или периодов ожидания остаются. last_success пишется
только при пустом списке сбоев, попытка отмечается отдельно. Health-проверка
zone_scan краснеет от сбоев и от возраста свыше 36 часов, в журнале сторожа
виден возраст обхода. Проверки: три ветки на выдуманных данных, мутации
ловятся.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
anor
2026-11-22 17:03:03 +10:00
co-authored by Claude Code
parent 34123a092b
commit 6a6627ee1b
4 changed files with 200 additions and 22 deletions
+14 -3
View File
@@ -764,10 +764,19 @@ def check_zone_scan() -> Check:
"/data_fast/smeta-web-data/_external/zone_scan_state.json")) "/data_fast/smeta-web-data/_external/zone_scan_state.json"))
try: try:
data = json.loads(path.read_text(encoding="utf-8")) data = json.loads(path.read_text(encoding="utf-8"))
stamp = data.get("last_success") or ""
when = datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
except Exception as e: # noqa: BLE001 except Exception as e: # noqa: BLE001
return Check("zone_scan", False, f"отметки обхода нет: {type(e).__name__}") return Check("zone_scan", False, f"отметки обхода нет: {type(e).__name__}")
failures = data.get("failures") or []
if failures:
return Check("zone_scan", False,
"последний обход со сбоями: " + "; ".join(map(str, failures))[:200])
stamp = data.get("last_success") or ""
if not stamp:
return Check("zone_scan", False, "успешного обхода ещё не было")
try:
when = datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
except ValueError:
return Check("zone_scan", False, f"отметка обхода не разбирается: {stamp}")
age = (datetime.now(timezone.utc) - when).total_seconds() age = (datetime.now(timezone.utc) - when).total_seconds()
ok = age <= 36 * 3600 ok = age <= 36 * 3600
return Check("zone_scan", ok, f"последний обход {stamp}, возраст {age/3600:.1f} ч") return Check("zone_scan", ok, f"последний обход {stamp}, возраст {age/3600:.1f} ч")
@@ -964,7 +973,9 @@ def main(argv: list | None = None) -> list:
сломано = [c for c in bad if getattr(c, "level", "") != "warn"] сломано = [c for c in bad if getattr(c, "level", "") != "warn"]
_write_log("%s %s %s" % ( _write_log("%s %s %s" % (
stamp, "ПОЛОМКА" if сломано else ("ВНИМАНИЕ" if bad else "OK"), stamp, "ПОЛОМКА" if сломано else ("ВНИМАНИЕ" if bad else "OK"),
"; ".join(f"{c.name}={'ok' if c.ok else c.detail}" for c in checks))) "; ".join(
f"{c.name}={c.detail if (not c.ok or c.name == 'zone_scan') else 'ok'}"
for c in checks)))
try: try:
notify(checks) notify(checks)
except Exception: # noqa: BLE001 — тревога побочна except Exception: # noqa: BLE001 — тревога побочна
+42 -18
View File
@@ -29,8 +29,14 @@ def _period_rank(key: str) -> tuple[int, int]:
def plan(existing: list[dict], portal: dict[tuple[int, int], list[dict]], def plan(existing: list[dict], portal: dict[tuple[int, int], list[dict]],
known: set[tuple[int, int, int]], horizon: int = 2) -> tuple[list[dict], list[dict]]: known: set[tuple[int, int, int]], horizon: int = 2,
"""Вернуть (добавить, снять) для ожиданий. Чистая функция — без сети и базы.""" zones_by_subject: dict[int, set[int]] | None = None) -> tuple[list[dict], list[dict]]:
"""Вернуть (добавить, снять) для ожиданий. Чистая функция — без сети и базы.
zones_by_subject — только успешно прочитанные списки зон. Уход зоны доказывается
лишь тогда, когда список её субъекта прочитан и зоны в нём нет; при сбое сети
субъекта в словаре нет, и его ожидания остаются нетронутыми.
"""
have = {(int(e["subject_id"]), int(e["zone_id"]), e["period"]) for e in existing} have = {(int(e["subject_id"]), int(e["zone_id"]), e["period"]) for e in existing}
adds, removes = [], [] adds, removes = [], []
for (sid, zid), periods in portal.items(): for (sid, zid), periods in portal.items():
@@ -48,10 +54,11 @@ def plan(existing: list[dict], portal: dict[tuple[int, int], list[dict]],
if keep_rank is not None and _period_rank(e["period"]) < _period_rank( if keep_rank is not None and _period_rank(e["period"]) < _period_rank(
dict(latest).get(keep_rank, "")): dict(latest).get(keep_rank, "")):
removes.append(e) removes.append(e)
zones = set(portal) if zones_by_subject is not None:
for e in existing: for e in existing:
if (int(e["subject_id"]), int(e["zone_id"])) not in zones: sid, zid = int(e["subject_id"]), int(e["zone_id"])
removes.append(e) if sid in zones_by_subject and zid not in zones_by_subject[sid]:
removes.append(e)
return adds, removes return adds, removes
@@ -77,46 +84,63 @@ def main() -> int:
known = {(int(s), int(z), int(p)) for s, z, p in known = {(int(s), int(z), int(p)) for s, z, p in
con.execute("select subject_id,zone_id,period_id from zone_snapshots")} con.execute("select subject_id,zone_id,period_id from zone_snapshots")}
con.close() con.close()
subjects = fc.country_subjects() zones_by_subject = {}
try:
subjects = fc.country_subjects()
except Exception as e: # noqa: BLE001 — сеть: не проверено, ожидания не меняем
failures.append(f"subjects: {type(e).__name__}"); subjects = []
for s in subjects: for s in subjects:
try: try:
zones = fc.price_zones(s["id"]) zones = fc.price_zones(s["id"])
except Exception as e: # noqa: BLE001 — сеть: не проверено, ожидания не меняем except Exception as e: # noqa: BLE001 — сеть: не проверено, ожидания не меняем
failures.append(f"zones {s['id']}: {type(e).__name__}"); continue failures.append(f"zones {s['id']}: {type(e).__name__}"); continue
zones_by_subject[s["id"]] = {z["id"] for z in zones}
for z in zones: for z in zones:
try: try:
portal[(s["id"], z["id"])] = fc.periods(z["id"]) portal[(s["id"], z["id"])] = fc.periods(z["id"])
except Exception as e: # noqa: BLE001 except Exception as e: # noqa: BLE001
failures.append(f"periods {s['id']}/{z['id']}: {type(e).__name__}") failures.append(f"periods {s['id']}/{z['id']}: {type(e).__name__}")
adds, removes = plan(existing, portal, known) adds, removes = plan(existing, portal, known, zones_by_subject=zones_by_subject)
checked = added = 0 checked = downloaded = expectations_added = 0
for add in adds: for add in adds:
sid, zid = add["subject_id"], add["zone_id"] sid, zid = add["subject_id"], add["zone_id"]
pid = next(p["id"] for p in portal[(sid, zid)] pid = next(p["id"] for p in portal[(sid, zid)]
if _period_key(p.get("name", "")) == add["period"]) if _period_key(p.get("name", "")) == add["period"])
try: try:
ext_pull.pull_split_form(sid, zid, pid) ext_pull.pull_split_form(sid, zid, pid)
downloaded += 1
except Exception as e: # noqa: BLE001 except Exception as e: # noqa: BLE001
text = str(e) text = str(e)
if "404" in text: if "404" in text:
add.update(zone_name=None, add.update(zone_name=None,
reason="на портале ФГИС ЦС форм за период нет (проверено " reason="на портале ФГИС ЦС форм за период нет (проверено "
+ datetime.now(timezone.utc).strftime("%Y-%m-%d") + ")") + datetime.now(timezone.utc).strftime("%Y-%m-%d") + ")")
existing.append(add); added += 1 existing.append(add); expectations_added += 1
else: else:
failures.append(f"form {sid}/{zid}/{pid}: {type(e).__name__}") failures.append(f"form {sid}/{zid}/{pid}: {type(e).__name__}")
checked += 1 checked += 1
existing = [e for e in existing if e not in removes] existing = [e for e in existing if e not in removes]
stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
if not a.dry_run: if not a.dry_run:
tmp = expect_path.with_suffix(".tmp") if expectations_added or removes:
tmp.write_text(json.dumps(existing, ensure_ascii=False, indent=1), encoding="utf-8") tmp = expect_path.with_suffix(".tmp")
tmp.replace(expect_path) tmp.write_text(json.dumps(existing, ensure_ascii=False, indent=1), encoding="utf-8")
state_path.write_text(json.dumps({"last_success": stamp, "zones": len(portal), tmp.replace(expect_path)
"added": added, "removed": len(removes), previous = {}
"failures": failures}, ensure_ascii=False), encoding="utf-8") if state_path.exists():
line = (f"{stamp} зон={len(portal)} добавлено={added} снято={len(removes)} " try:
+ ("без изменений" if not added and not removes else "изменения") previous = json.loads(state_path.read_text(encoding="utf-8"))
except Exception: # noqa: BLE001 — битая отметка не отменяет сам обход
previous = {}
state_path.write_text(json.dumps({
"last_attempt": stamp,
"last_success": stamp if not failures else previous.get("last_success"),
"zones": len(portal), "new_periods": checked, "downloaded": downloaded,
"expectations_added": expectations_added, "removed": len(removes),
"failures": failures}, ensure_ascii=False), encoding="utf-8")
line = (f"{stamp} зон={len(portal)} новых={checked} добавлено={downloaded} "
f"ожиданий={expectations_added} снято={len(removes)} "
+ ("без изменений" if not checked and not removes else "изменения")
+ (f" сбоев={len(failures)}" if failures else "")) + (f" сбоев={len(failures)}" if failures else ""))
with open(a.log, "a", encoding="utf-8") as f: with open(a.log, "a", encoding="utf-8") as f:
f.write(line + "\n") f.write(line + "\n")
+106 -1
View File
@@ -1,5 +1,8 @@
"""Планировщик ожиданий ежедневного обхода зон (22.11.2026).""" """Планировщик ожиданий ежедневного обхода зон (22.11.2026)."""
import json
import sqlite3
import sys import sys
import types
from pathlib import Path from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
import fgis_zone_scan as z # noqa: E402 import fgis_zone_scan as z # noqa: E402
@@ -26,5 +29,107 @@ def test_old_expectation_removed_by_horizon():
def test_zone_gone_removes_all_its_expectations(): def test_zone_gone_removes_all_its_expectations():
ex = [{"subject_id": 999, "zone_id": 1, "period": "2025-Q1"}] ex = [{"subject_id": 999, "zone_id": 1, "period": "2025-Q1"}]
_, rem = z.plan(ex, PORTAL, known=set(), horizon=2) _, rem = z.plan(ex, PORTAL, known=set(), horizon=2, zones_by_subject={999: set()})
assert ex[0] in rem assert ex[0] in rem
def test_network_failure_keeps_expectations():
"""Сбой периодов не доказывает уход зоны: ожидание остаётся."""
ex = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1"}]
_, rem = z.plan(ex, {}, known=set(), horizon=2, zones_by_subject={1: {7}})
assert rem == []
def test_unknown_subject_keeps_expectations():
"""Список зон субъекта не прочитан — трогать его ожидания нельзя."""
ex = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1"}]
_, rem = z.plan(ex, {}, known=set(), horizon=2, zones_by_subject={})
assert rem == []
def _scan_stand(tmp_path, monkeypatch, periods, known=(), expect=None,
pull_error=None, fail_periods=False, fail_subjects=False):
db = tmp_path / "fgis.sqlite"
con = sqlite3.connect(db)
con.execute("create table zone_snapshots(subject_id int, zone_id int, period_id int)")
con.executemany("insert into zone_snapshots values (?,?,?)", known)
con.commit()
con.close()
class Client:
def country_subjects(self):
if fail_subjects:
raise RuntimeError("сеть недоступна")
return [{"id": 1}]
def price_zones(self, sid):
return [{"id": 7}]
def periods(self, zid):
if fail_periods:
raise RuntimeError("таймаут")
return periods
def pull_split_form(sid, zid, pid):
if pull_error:
raise RuntimeError(pull_error)
monkeypatch.setitem(sys.modules, "fgis_client", Client())
monkeypatch.setitem(sys.modules, "ext_pull",
types.SimpleNamespace(pull_split_form=pull_split_form))
expect_path = tmp_path / "expect.json"
if expect is not None:
expect_path.write_text(json.dumps(expect, ensure_ascii=False), encoding="utf-8")
state_path = tmp_path / "state.json"
log_path = tmp_path / "scan.log"
monkeypatch.setenv("SCAN_LOCK", str(tmp_path / "scan.lock"))
monkeypatch.delenv("OPERATOR_EMAIL", raising=False)
monkeypatch.setattr(sys, "argv", [
"fgis_zone_scan.py", "--expect", str(expect_path), "--state", str(state_path),
"--log", str(log_path), "--db", str(db)])
code = z.main()
return code, expect_path, state_path, log_path
def test_new_period_is_added_and_run_marked_success(tmp_path, monkeypatch):
periods = [p(1, "1 квартал 2025"), p(2, "2 квартал 2025"), p(3, "3 квартал 2025"),
p(4, "4 квартал 2025 г."), p(5, "1 квартал 2026 г.")]
code, expect, state, log = _scan_stand(
tmp_path, monkeypatch, periods, known={(1, 7, 4)}, expect=[])
assert code == 0
assert "добавлено=1" in log.read_text(encoding="utf-8")
data = json.loads(state.read_text(encoding="utf-8"))
assert data["failures"] == [] and data["last_success"]
def test_expired_expectation_is_removed(tmp_path, monkeypatch):
periods = [p(1, "1 квартал 2025"), p(2, "2 квартал 2025"), p(3, "3 квартал 2025"),
p(4, "4 квартал 2025 г."), p(5, "1 квартал 2026 г.")]
old = [{"subject_id": 1, "zone_id": 7, "period": "2024-Q1", "reason": "старое"}]
code, expect, state, log = _scan_stand(
tmp_path, monkeypatch, periods, known={(1, 7, 3), (1, 7, 4), (1, 7, 5)}, expect=old)
assert code == 0
assert "снято=1" in log.read_text(encoding="utf-8")
assert json.loads(expect.read_text(encoding="utf-8")) == []
def test_network_failure_keeps_files_and_marks_no_success(tmp_path, monkeypatch):
old = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1", "reason": "нет форм"}]
before = json.dumps(old, ensure_ascii=False)
code, expect, state, log = _scan_stand(
tmp_path, monkeypatch, [], expect=old, fail_periods=True)
assert code == 1
assert expect.read_text(encoding="utf-8") == before
data = json.loads(state.read_text(encoding="utf-8"))
assert data["failures"] and not data.get("last_success")
assert "сбоев=1" in log.read_text(encoding="utf-8")
def test_country_list_failure_keeps_expectations(tmp_path, monkeypatch):
old = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1"}]
before = json.dumps(old, ensure_ascii=False)
code, expect, state, log = _scan_stand(
tmp_path, monkeypatch, [], expect=old, fail_subjects=True)
assert code == 1
assert expect.read_text(encoding="utf-8") == before
assert json.loads(state.read_text(encoding="utf-8"))["failures"]
+38
View File
@@ -715,3 +715,41 @@ def test_old_canaries_are_marked_as_retired():
head = open(os.path.join(ROOT, "scripts", name), encoding="utf-8").read()[:1500] head = open(os.path.join(ROOT, "scripts", name), encoding="utf-8").read()[:1500]
assert "снят с расписания" in head, name assert "снят с расписания" in head, name
assert "health_checks.py" in head, name assert "health_checks.py" in head, name
# --- Д. Свежесть ежедневного обхода зон ФГИС -----------------------------------
def _zone_state(tmp_path, monkeypatch, **state):
from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc)
state.setdefault("last_success", (now - timedelta(hours=1)).strftime("%Y-%m-%dT%H:%M:%SZ"))
path = tmp_path / "zone_state.json"
path.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
monkeypatch.setenv("ZONE_SCAN_STATE", str(path))
return path
def test_zone_scan_fresh_success_is_green(env, tmp_path, monkeypatch):
_, h, _ = env
_zone_state(tmp_path, monkeypatch, last_attempt="2026-11-22T06:00:00Z", failures=[])
c = h.check_zone_scan()
assert c.ok and c.name == "zone_scan"
assert "возраст" in c.detail
def test_zone_scan_stale_success_is_red(env, tmp_path, monkeypatch):
from datetime import datetime, timedelta, timezone
_, h, _ = env
old = (datetime.now(timezone.utc) - timedelta(hours=40)).strftime("%Y-%m-%dT%H:%M:%SZ")
_zone_state(tmp_path, monkeypatch, last_success=old, failures=[])
c = h.check_zone_scan()
assert not c.ok and "возраст" in c.detail
def test_zone_scan_failed_last_run_is_red(env, tmp_path, monkeypatch):
_, h, _ = env
_zone_state(tmp_path, monkeypatch, last_attempt="2026-11-22T06:00:00Z",
failures=["periods 1/7: Timeout"])
c = h.check_zone_scan()
assert not c.ok
assert "сбоями" in c.detail and "periods 1/7" in c.detail