fix(ext): денежный сигнал чекера — по применённому периоду, не по скачанному

Money-safety: под авто-закачкой всех регионов (выбор оператора) прежний check_fgis замолчал
бы про «пора применить к движку» — он сравнивал latest со СКАЧАННЫМ периодом (st['sources']),
а авто-pull его подтягивает → движок молча считал бы по старым ценам.

- ext_apply: активация пишет subject/zone/period_id в st['active'] (что реально стои́т в движке).
- check_fgis: сравнивает latest с ПРИМЕНЁННЫМ периодом движковой зоны (st['active']). Сигнал
  «примени» (update, письмо) не глохнет от авто-закачки. Корпусные регионы (не движковая зона)
  → одна info-сводка «N ждут скачивания» (авто-pull подтянет), а не 86 писем.
- Движку ещё ничего не применяли → разовый сигнал «выбери регион и примени».
- Движковая зона вне списка мониторинга → проверяется отдельно (сигнал не теряется).
- Тесты переписаны под применённый-период; добавлен ключевой red-green
  test_autopull_does_not_silence_apply_signal (скачано=latest, применено старое → сигнал жив).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-07-18 11:57:50 +10:00
co-authored by Claude Opus 4.8
parent 5606e933e9
commit f985495232
3 changed files with 106 additions and 42 deletions
+32 -20
View File
@@ -42,26 +42,43 @@ def _mock_pravo(monkeypatch, new_docs):
monkeypatch.setattr(pc, "new_since", lambda seen, max_pages=8, client=None: new_docs)
def _set_engine(subject=323, zone=191, period=426):
"""Обозначить движковую зону + применённый период (st['active']). База денежного сигнала."""
with es.update_state() as st:
st.setdefault("active", {})["fgis_split_form"] = {
"subject": subject, "zone": zone, "period_id": period}
def test_new_period_produces_finding_with_action(_tmp, monkeypatch):
_mock_fgis(monkeypatch, latest=426)
_mock_pravo(monkeypatch, [])
# активен период 425 → 426 новее
with es.update_state() as st:
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 425}}
_set_engine(period=425) # движку применён 425 → latest 426 новее → сигнал «примени»
rep = ec.run_check(regions=[323], notify=False)
ups = [f for f in rep["findings"] if f["source"] == "fgis_split_form"]
assert len(ups) == 1 and "426" in ups[0]["message"] and "ext_pull.py" in ups[0]["action"]
assert len(ups) == 1 and "426" in ups[0]["message"] and "ext_apply.py" in ups[0]["action"]
def test_no_finding_when_period_is_active(_tmp, monkeypatch):
_mock_fgis(monkeypatch, latest=426)
_mock_pravo(monkeypatch, [])
with es.update_state() as st:
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}}
_set_engine(period=426) # движок уже на latest → тишина
rep = ec.run_check(regions=[323], notify=False)
assert not [f for f in rep["findings"] if f["source"] == "fgis_split_form"]
def test_autopull_does_not_silence_apply_signal(_tmp, monkeypatch):
"""КЛЮЧ money-safety: авто-закачка обновила ПУЛЛ (sources) до latest, но движок применён на
старом периоде → сигнал «пора применить» ДОЛЖЕН остаться (иначе движок молча по старым ценам)."""
_mock_fgis(monkeypatch, latest=430)
_mock_pravo(monkeypatch, [])
_set_engine(period=426) # движок на 426
with es.update_state() as st:
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 430}} # авто-pull подтянул 430
rep = ec.run_check(regions=[323], notify=False)
ups = [f for f in rep["findings"] if f["source"] == "fgis_split_form" and f["level"] == "update"]
assert len(ups) == 1 and "430" in ups[0]["message"] # не заглушено скачанным 430
def test_checker_does_not_mutate_state_json(_tmp, monkeypatch):
"""КЛЮЧЕВОЙ ИНВАРИАНТ: прогон чекера НЕ меняет state.json ни на байт."""
_mock_fgis(monkeypatch, latest=999) # заведомо новый период
@@ -128,8 +145,7 @@ def test_notify_failure_keeps_findings_for_retry(_tmp, monkeypatch):
_mock_fgis(monkeypatch, latest=430)
_mock_pravo(monkeypatch, [])
monkeypatch.setenv("OPERATOR_EMAIL", "") # адреса нет → _notify вернёт False при updates
with es.update_state() as st:
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 425}}
_set_engine(period=425) # движок на 425, latest 430 → сигнал «примени»
rep = ec.run_check(regions=[323], notify=True)
assert rep["notify_ok"] is False
# дедуп НЕ сохранён → на следующем прогоне находка повторится
@@ -139,16 +155,14 @@ def test_notify_failure_keeps_findings_for_retry(_tmp, monkeypatch):
def test_rollback_reports_again(_tmp, monkeypatch):
"""MEDIUM-фикс: применили период → синхронно (нет доклада, метка снята) → откат → снова доклад."""
"""MEDIUM-фикс: движок на latest → синхронно (нет доклада, метка снята) → откат ПРИМЕНЕНИЯ →
снова доклад (по применённому периоду, а не скачанному)."""
_mock_fgis(monkeypatch, latest=426)
_mock_pravo(monkeypatch, [])
with es.update_state() as st:
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}} # активен = latest
_set_engine(period=426) # применён = latest
ec.run_check(regions=[323], notify=False) # синхронно → нет находки
assert not es.load_watch_seen().get("fgis_periods_reported", {}).get("323/191")
# откат: активным стал 425 (а latest всё ещё 426)
with es.update_state() as st:
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 425}}
_set_engine(period=425) # откат применения → 425
rep = ec.run_check(regions=[323], notify=False)
assert any(f["source"] == "fgis_split_form" and "426" in f["message"] for f in rep["findings"])
@@ -210,8 +224,7 @@ def test_crash_midcheck_does_not_mark_undelivered_finding(_tmp, monkeypatch):
monkeypatch.setattr(fc, "price_zones", lambda s, client=None:
[{"id": 191, "name": "зона A"}, {"id": 999, "name": "зона B"}])
_mock_pravo(monkeypatch, [])
with es.update_state() as st:
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}} # активен 426
_set_engine(subject=323, zone=191, period=426) # 191 — движковая зона, применён 426
# ключ fgis_periods_reported УЖЕ есть (метка другой зоны) → reported = ссылка ВНУТРЬ seen,
# значит reported[323/191]=430 мутирует seen in-place ДО краха (иначе баг не воспроизводится).
es.save_watch_seen({"fgis_periods_reported": {"999/000": 1}})
@@ -266,10 +279,9 @@ def test_notify_called_only_with_findings(_tmp, monkeypatch):
import email_service
monkeypatch.setattr(email_service, "send_operator_digest",
lambda to, subj, html: calls.append((to, subj)) or True)
with es.update_state() as st:
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}}
ec.run_check(regions=[323], notify=True) # нет новостей
_set_engine(period=426) # движок синхронен с latest → нет новостей
ec.run_check(regions=[323], notify=True)
assert calls == []
_mock_fgis(monkeypatch, latest=430) # теперь новый период
_mock_fgis(monkeypatch, latest=430) # latest вырос, движок всё на 426 → «примени»
ec.run_check(regions=[323], notify=True)
assert len(calls) == 1 and calls[0][0] == "op@test" # письмо ушло с новостью