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:
+11
-5
@@ -133,8 +133,11 @@ def _rebuild_host_cache(target: Path, report: dict) -> None:
|
||||
|
||||
|
||||
def activate(snapshot_xlsx: os.PathLike | str, *, target_file: Path | None = None,
|
||||
force: bool = False) -> dict:
|
||||
"""Активировать снапшот (под ext_lock, через временную копию). Возвращает отчёт."""
|
||||
force: bool = False, subject: int | None = None, zone: int | None = None,
|
||||
period_id: int | None = None) -> dict:
|
||||
"""Активировать снапшот (под ext_lock, через временную копию). Возвращает отчёт.
|
||||
subject/zone/period_id пишутся в st['active'] — по ним чекер понимает, какой период
|
||||
реально стои́т в движке (сигнал «пора применить» не должен глохнуть от авто-закачки)."""
|
||||
snapshot_xlsx = Path(snapshot_xlsx)
|
||||
target = Path(target_file) if target_file else _target_file()
|
||||
|
||||
@@ -167,7 +170,7 @@ def activate(snapshot_xlsx: os.PathLike | str, *, target_file: Path | None = Non
|
||||
report["activated"] = True
|
||||
|
||||
_rebuild_host_cache(target, report)
|
||||
_record_active(target, v_new)
|
||||
_record_active(target, v_new, subject, zone, period_id)
|
||||
report["restart_reminder"] = ("Данные заменены и кэш пересобран. Перезапусти сервис, "
|
||||
"чтобы host-процесс тоже перечитал файл.")
|
||||
return report
|
||||
@@ -180,11 +183,13 @@ def _backup_current(target: Path) -> None:
|
||||
key=str(target.resolve()), url="(local active file)")
|
||||
|
||||
|
||||
def _record_active(target: Path, verify: dict) -> None:
|
||||
def _record_active(target: Path, verify: dict, subject: int | None = None,
|
||||
zone: int | None = None, period_id: int | None = None) -> None:
|
||||
with ext_state.update_state() as st:
|
||||
st.setdefault("active", {})["fgis_split_form"] = {
|
||||
"target": str(target), "sha256": ext_state.sha256_file(target),
|
||||
"codes": verify.get("codes"), "activated_at": ext_state._utcnow(),
|
||||
"subject": subject, "zone": zone, "period_id": period_id,
|
||||
}
|
||||
|
||||
|
||||
@@ -204,7 +209,8 @@ def main(argv=None) -> int:
|
||||
return 2
|
||||
|
||||
target_file = _target_file(args.target_dir)
|
||||
rep = activate(snap, target_file=target_file, force=args.force)
|
||||
rep = activate(snap, target_file=target_file, force=args.force,
|
||||
subject=args.subject, zone=args.zone, period_id=args.period)
|
||||
print(json.dumps(rep, ensure_ascii=False, indent=2))
|
||||
return 0 if rep.get("activated") else 1
|
||||
|
||||
|
||||
+63
-17
@@ -109,8 +109,18 @@ def check_xsd(seen: dict, *, client=None) -> tuple[list[dict], dict]:
|
||||
return findings, seen
|
||||
|
||||
|
||||
def _apply_action(subject_id: int, zone_id: int, period_id: int) -> str:
|
||||
return (f"python3 ext_pull.py --source all --subject {subject_id} --zone {zone_id} "
|
||||
f"--period {period_id} && python3 ext_apply.py --subject {subject_id} "
|
||||
f"--zone {zone_id} --period {period_id}")
|
||||
|
||||
|
||||
def check_fgis(regions: list[int], seen: dict, *, client=None) -> tuple[list[dict], dict]:
|
||||
"""Новый период по каждой зоне сконфигурированных регионов. Дедуп через seen."""
|
||||
"""Денежный сигнал ДВИЖКУ: пора ли применить новый период к активному файлу движка.
|
||||
База сравнения — ПРИМЕНЁННЫЙ период (st['active'], пишет ext_apply), НЕ скачанный: иначе
|
||||
рекуррентная авто-закачка корпуса заглушила бы сигнал «пора применить» и движок молча считал
|
||||
бы по старым ценам. Движковую зону сигналим update (письмо), корпусные регионы — info-сводка
|
||||
(авто-закачка подтянет), не письмо (иначе 86 регионов = завал оператора)."""
|
||||
findings: list[dict] = []
|
||||
if not fc.alive(client=client):
|
||||
findings.append({"source": "fgis", "level": "problem",
|
||||
@@ -118,7 +128,28 @@ def check_fgis(regions: list[int], seen: dict, *, client=None) -> tuple[list[dic
|
||||
return findings, seen
|
||||
reported = seen.get("fgis_periods_reported", {})
|
||||
state = ext_state.load_state() # ЧТЕНИЕ, не запись
|
||||
active_all = state.get("sources", {}).get("fgis_split_form", {})
|
||||
pulled_all = state.get("sources", {}).get("fgis_split_form", {})
|
||||
engine = state.get("active", {}).get("fgis_split_form") or {}
|
||||
engine_key = (f"{engine['subject']}/{engine['zone']}"
|
||||
if engine.get("subject") is not None and engine.get("zone") is not None else None)
|
||||
engine_period = engine.get("period_id")
|
||||
|
||||
def _engine_gap(subject_id, zone_id, zname, lp):
|
||||
"""update-находка, если движку применён период старее latest (дедуп: одно письмо на период)."""
|
||||
key = f"{subject_id}/{zone_id}"
|
||||
if engine_period is not None and lp["id"] > engine_period:
|
||||
if reported.get(key) != lp["id"]:
|
||||
findings.append({
|
||||
"source": "fgis_split_form", "level": "update",
|
||||
"message": (f"Движку применён период {engine_period}, доступен новее "
|
||||
f"«{lp['name']}» (id {lp['id']}) для «{zname}» — примени."),
|
||||
"action": _apply_action(subject_id, zone_id, lp["id"])})
|
||||
reported[key] = lp["id"]
|
||||
else:
|
||||
reported.pop(key, None) # движок на latest → сброс метки (откат применения снова доложит)
|
||||
|
||||
corpus_pending = 0
|
||||
engine_seen = False
|
||||
for subject_id in regions:
|
||||
try:
|
||||
zones = fc.price_zones(subject_id, client=client)
|
||||
@@ -137,21 +168,36 @@ def check_fgis(regions: list[int], seen: dict, *, client=None) -> tuple[list[dic
|
||||
continue
|
||||
if not lp:
|
||||
continue
|
||||
active = (active_all.get(key) or {}).get("period_id")
|
||||
if lp["id"] == active:
|
||||
reported.pop(key, None) # синхронно → сбрасываем метку, чтобы откат снова доложился
|
||||
continue
|
||||
if reported.get(key) != lp["id"]:
|
||||
findings.append({
|
||||
"source": "fgis_split_form", "level": "update",
|
||||
"message": f"Новый период «{lp['name']}» (id {lp['id']}) для «{z['name']}»; "
|
||||
f"активен id {active}",
|
||||
"action": (f"python3 ext_pull.py --source all --subject {subject_id} "
|
||||
f"--zone {zone_id} --period {lp['id']} && "
|
||||
f"python3 ext_apply.py --subject {subject_id} --zone {zone_id} "
|
||||
f"--period {lp['id']}"),
|
||||
})
|
||||
reported[key] = lp["id"]
|
||||
if key == engine_key:
|
||||
engine_seen = True
|
||||
_engine_gap(subject_id, zone_id, z["name"], lp)
|
||||
else: # корпус: считаем «ждут скачивания» для сводки (авто-pull подтянет)
|
||||
pulled = (pulled_all.get(key) or {}).get("period_id")
|
||||
if lp["id"] != pulled:
|
||||
corpus_pending += 1
|
||||
|
||||
if engine_key and not engine_seen: # движковая зона вне списка мониторинга — проверяем отдельно
|
||||
try:
|
||||
lp = fc.latest_period(engine["zone"], client=client)
|
||||
if lp:
|
||||
_engine_gap(engine["subject"], engine["zone"], engine_key, lp)
|
||||
except ext_fetch.FetchError as e:
|
||||
findings.append({"source": "fgis", "level": "problem",
|
||||
"message": f"движковая зона {engine['zone']}: ошибка периодов: {e}"})
|
||||
|
||||
if corpus_pending:
|
||||
findings.append({"source": "fgis_corpus", "level": "info",
|
||||
"message": f"Регионов/зон с периодом новее скачанного: {corpus_pending} "
|
||||
f"(авто-закачка корпуса подтянет)"})
|
||||
if engine_key is None: # движку ещё ничего не применяли — данные из дефолтного файла
|
||||
if not reported.get("_engine_unset"):
|
||||
findings.append({"source": "fgis_split_form", "level": "update",
|
||||
"message": "Движку ещё не применён ни один регион ФГИС — цены берутся из "
|
||||
"дефолтного файла. Выбери регион и примени (ext_pull … && ext_apply …)."})
|
||||
reported["_engine_unset"] = True
|
||||
else:
|
||||
reported.pop("_engine_unset", None)
|
||||
|
||||
seen["fgis_periods_reported"] = reported
|
||||
return findings, seen
|
||||
|
||||
|
||||
+32
-20
@@ -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" # письмо ушло с новостью
|
||||
|
||||
Reference in New Issue
Block a user