From 6a6627ee1b774aafaa02a9de9705b044bdd3ae46 Mon Sep 17 00:00:00 2001 From: anor Date: Sun, 22 Nov 2026 17:03:03 +1000 Subject: [PATCH] =?UTF-8?q?fix(=D0=BE=D0=B1=D1=85=D0=BE=D0=B4):=20=D1=81?= =?UTF-8?q?=D0=B1=D0=BE=D0=B9=20=D1=81=D0=B5=D1=82=D0=B8=20=D0=BD=D0=B5=20?= =?UTF-8?q?=D1=81=D0=BD=D0=B8=D0=BC=D0=B0=D0=B5=D1=82=20=D0=BE=D0=B6=D0=B8?= =?UTF-8?q?=D0=B4=D0=B0=D0=BD=D0=B8=D1=8F,=20=D0=B7=D0=B4=D0=BE=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D1=8C=D0=B5=20=D0=BA=D1=80=D0=B0=D1=81=D0=BD=D0=B5?= =?UTF-8?q?=D0=B5=D1=82=20=D0=BF=D1=80=D0=B8=20=D1=81=D0=B1=D0=BE=D1=8F?= =?UTF-8?q?=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Уход зоны доказывается только успешно прочитанным списком зон субъекта: при сбое списка зон или периодов ожидания остаются. last_success пишется только при пустом списке сбоев, попытка отмечается отдельно. Health-проверка zone_scan краснеет от сбоев и от возраста свыше 36 часов, в журнале сторожа виден возраст обхода. Проверки: три ветки на выдуманных данных, мутации ловятся. Co-Authored-By: Claude Code --- health_checks.py | 17 +++++- scripts/fgis_zone_scan.py | 60 ++++++++++++++------ tests/test_fgis_zone_scan.py | 107 ++++++++++++++++++++++++++++++++++- tests/test_health_checks.py | 38 +++++++++++++ 4 files changed, 200 insertions(+), 22 deletions(-) diff --git a/health_checks.py b/health_checks.py index 468fd16..3541a4a 100644 --- a/health_checks.py +++ b/health_checks.py @@ -764,10 +764,19 @@ def check_zone_scan() -> Check: "/data_fast/smeta-web-data/_external/zone_scan_state.json")) try: 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 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() ok = age <= 36 * 3600 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"] _write_log("%s %s %s" % ( 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: notify(checks) except Exception: # noqa: BLE001 — тревога побочна diff --git a/scripts/fgis_zone_scan.py b/scripts/fgis_zone_scan.py index 9df3788..60ef57b 100644 --- a/scripts/fgis_zone_scan.py +++ b/scripts/fgis_zone_scan.py @@ -29,8 +29,14 @@ def _period_rank(key: str) -> tuple[int, int]: 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} adds, removes = [], [] 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( dict(latest).get(keep_rank, "")): removes.append(e) - zones = set(portal) - for e in existing: - if (int(e["subject_id"]), int(e["zone_id"])) not in zones: - removes.append(e) + if zones_by_subject is not None: + for e in existing: + sid, zid = int(e["subject_id"]), int(e["zone_id"]) + if sid in zones_by_subject and zid not in zones_by_subject[sid]: + removes.append(e) return adds, removes @@ -77,46 +84,63 @@ def main() -> int: 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.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: try: zones = fc.price_zones(s["id"]) except Exception as e: # noqa: BLE001 — сеть: не проверено, ожидания не меняем 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: try: portal[(s["id"], z["id"])] = fc.periods(z["id"]) except Exception as e: # noqa: BLE001 failures.append(f"periods {s['id']}/{z['id']}: {type(e).__name__}") - adds, removes = plan(existing, portal, known) - checked = added = 0 + adds, removes = plan(existing, portal, known, zones_by_subject=zones_by_subject) + checked = downloaded = expectations_added = 0 for add in adds: sid, zid = add["subject_id"], add["zone_id"] pid = next(p["id"] for p in portal[(sid, zid)] if _period_key(p.get("name", "")) == add["period"]) try: ext_pull.pull_split_form(sid, zid, pid) + downloaded += 1 except Exception as e: # noqa: BLE001 text = str(e) if "404" in text: add.update(zone_name=None, reason="на портале ФГИС ЦС форм за период нет (проверено " + datetime.now(timezone.utc).strftime("%Y-%m-%d") + ")") - existing.append(add); added += 1 + existing.append(add); expectations_added += 1 else: failures.append(f"form {sid}/{zid}/{pid}: {type(e).__name__}") checked += 1 existing = [e for e in existing if e not in removes] stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if not a.dry_run: - tmp = expect_path.with_suffix(".tmp") - tmp.write_text(json.dumps(existing, ensure_ascii=False, indent=1), encoding="utf-8") - tmp.replace(expect_path) - state_path.write_text(json.dumps({"last_success": stamp, "zones": len(portal), - "added": added, "removed": len(removes), - "failures": failures}, ensure_ascii=False), encoding="utf-8") - line = (f"{stamp} зон={len(portal)} добавлено={added} снято={len(removes)} " - + ("без изменений" if not added and not removes else "изменения") + if expectations_added or removes: + tmp = expect_path.with_suffix(".tmp") + tmp.write_text(json.dumps(existing, ensure_ascii=False, indent=1), encoding="utf-8") + tmp.replace(expect_path) + previous = {} + if state_path.exists(): + try: + 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 "")) with open(a.log, "a", encoding="utf-8") as f: f.write(line + "\n") diff --git a/tests/test_fgis_zone_scan.py b/tests/test_fgis_zone_scan.py index 0461c01..814c9d3 100644 --- a/tests/test_fgis_zone_scan.py +++ b/tests/test_fgis_zone_scan.py @@ -1,5 +1,8 @@ """Планировщик ожиданий ежедневного обхода зон (22.11.2026).""" +import json +import sqlite3 import sys +import types from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) 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(): 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 + + +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"] diff --git a/tests/test_health_checks.py b/tests/test_health_checks.py index 6918e5f..8c02c8d 100644 --- a/tests/test_health_checks.py +++ b/tests/test_health_checks.py @@ -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] assert "снят с расписания" 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