fix(ext): money-safety фиксы Fable в активации/скачивании (Фаза 1)

ext_apply: verify+ГЕЙТ теперь по КОДАМ И ЦЕНАМ (файл чужой зоны с теми же кодами, но ценами
в разы — ловим по медианному отношению; сдвиг колонок/битые цены — по доле распознанных);
activate под ext_lock через temp-copy (нет TOCTOU verify↔подмена); пересборка fgis_cache.pkl
НА ХОСТЕ после подмены (иначе Docker-агент падал на ro-записи кэша); аудит активного среза в
state; надёжный target (SMETA_PROJECT_DIR, не относительный); чистим служебное поле в отчёте.
ext_pull: verify скачанного ДО регистрации (обрезанные HTTP-200), FetchError вместо SystemExit,
вежливая пауза между запросами. ext_lock реентрантна. 43 теста.
This commit is contained in:
anor
2026-07-18 01:45:43 +10:00
parent 3a92013600
commit 09c4a0ccd5
5 changed files with 243 additions and 132 deletions
+143 -81
View File
@@ -1,123 +1,191 @@
"""ext_apply — осознанная активация снапшота ФГИС для движка (срез 1.3).
"""ext_apply — осознанная активация снапшота ФГИС для движка (срез 1.3 + фиксы Fable).
Заменяет рабочий fgis_split_form.xlsx (его ест estimate_contract) новым снапшотом ТОЛЬКО
после проверок, с диффом на экране и защитой от аномалий (fail-loud). Никаких тихих
перезаписей денежных данных. НЕ рестартит сервис — только напоминает.
после проверок, с диффом и защитой от аномалий (fail-loud). Никаких тихих перезаписей
денежных данных. НЕ рестартит сервис.
Порядок: verify(new) → если есть текущий: verify(old)+diff+гейт → бэкап старого в снапшот
→ атомарная подмена target → (по --yes) удалить fgis_cache.pkl → напомнить рестарт.
Money-safety (найдено Fable):
- verify и гейт смотрят не только на КОДЫ, но и на ЦЕНЫ (файл чужой зоны/со сдвинутой
колонкой цен имеет те же коды, но другие цены → ловим по медианному отношению);
- активация под ext_lock + через временную копию (verify и подмена — один и тот же
неизменяемый файл; окна TOCTOU нет);
- после подмены пересобираем fgis_cache.pkl НА ХОСТЕ (иначе Docker-агент упал бы, пытаясь
записать кэш на ro-mount);
- активный срез фиксируется в state.json (аудиторский след «по чему считали»).
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import tempfile
from pathlib import Path
import ext_state
MIN_CODES = 1000 # реальная сплит-форма ~43k строк; <1000 = явно битый файл
REMOVED_RATIO_GATE = 0.30 # исчезло >30% кодов → аномалия, требуется --force
MIN_CODES = 1000
REMOVED_RATIO_GATE = 0.30 # исчезло >30% кодов → аномалия
PRICE_MEDIAN_LOW = 0.5 # медианное отношение цен new/old вне [0.5, 2.0] → аномалия
PRICE_MEDIAN_HIGH = 2.0
PRICE_EXTREME_FRAC_GATE = 0.20 # >20% позиций с изменением цены >2× → аномалия
MIN_PRICED_FRAC = 0.90 # <90% строк без положительной цены → битый файл
def _target_file() -> Path:
"""Куда активируем: fgis_split_form.xlsx рядом с движком (estimate_contract._SR_ROOT)."""
try:
import estimate_contract as ec
return Path(ec._SR_ROOT) / "fgis_split_form.xlsx"
except Exception:
return Path(os.environ.get("SMETA_RAILWAY", "../smeta-railway")) / "fgis_split_form.xlsx"
def _target_file(target_dir: str | None = None) -> Path:
"""Куда активируем: fgis_split_form.xlsx в каталоге движка (тот же, что монтируется агенту)."""
if target_dir:
return (Path(target_dir) / "fgis_split_form.xlsx").resolve()
# Единый источник каталога движка — SMETA_PROJECT_DIR (как в claude_bridge/search_engine),
# дефолт ~/smeta-railway; НЕ относительный (cwd-мина), .resolve().
base = os.environ.get("SMETA_PROJECT_DIR") or os.path.expanduser("~/smeta-railway")
return (Path(base) / "fgis_split_form.xlsx").resolve()
def read_codes(xlsx_path: os.PathLike | str) -> set[str]:
"""Множество кодов ресурсов из первой колонки (read-only, для больших файлов)."""
def _is_num(v) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool)
def _read_rows(xlsx_path: os.PathLike | str) -> dict[str, float]:
"""{код(колонка A) → максимальная числовая цена в строке}. Один проход, read-only."""
import openpyxl
wb = openpyxl.load_workbook(str(xlsx_path), read_only=True, data_only=True)
try:
ws = wb.active
codes: set[str] = set()
for i, row in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True)):
if i == 0:
continue # шапка
v = row[0]
if v is not None and str(v).strip():
codes.add(str(v).strip())
return codes
rows: dict[str, float] = {}
for i, row in enumerate(ws.iter_rows(values_only=True)):
if i == 0 or not row:
continue
code = row[0]
if code is None or not str(code).strip():
continue
nums = [v for v in row[1:] if _is_num(v) and v > 0]
rows[str(code).strip()] = max(nums) if nums else 0.0
return rows
finally:
wb.close()
def verify_snapshot(xlsx_path: os.PathLike | str) -> dict:
"""Структурная проверка: openpyxl открывает, кодов ≥ порога. Возвращает {ok, codes, errors}."""
"""Структура + наличие цен. {ok, codes, priced_frac, errors, _rows}."""
errors = []
try:
codes = read_codes(xlsx_path)
rows = _read_rows(xlsx_path)
except Exception as e: # noqa: BLE001 — битый xlsx не должен доехать до движка
return {"ok": False, "codes": 0, "errors": [f"не открывается как xlsx: {type(e).__name__}: {e}"]}
if len(codes) < MIN_CODES:
errors.append(f"кодов {len(codes)} < {MIN_CODES} — подозрительно мало (битый/частичный?)")
return {"ok": not errors, "codes": len(codes), "errors": errors, "_codes": codes}
n = len(rows)
priced = sum(1 for p in rows.values() if p > 0)
priced_frac = round(priced / n, 4) if n else 0.0
if n < MIN_CODES:
errors.append(f"кодов {n} < {MIN_CODES} — подозрительно мало (битый/частичный?)")
if priced_frac < MIN_PRICED_FRAC:
errors.append(f"строк с ценой {priced_frac*100:.0f}% < {MIN_PRICED_FRAC*100:.0f}% "
f"— цены не распознаны (не тот файл/сдвиг колонок?)")
return {"ok": not errors, "codes": n, "priced_frac": priced_frac, "errors": errors, "_rows": rows}
def diff_codes(old_codes: set[str], new_codes: set[str]) -> dict:
added = new_codes - old_codes
removed = old_codes - new_codes
removed_ratio = (len(removed) / len(old_codes)) if old_codes else 0.0
def diff_rows(old_rows: dict[str, float], new_rows: dict[str, float]) -> dict:
"""Дифф по кодам И по ценам общих кодов."""
old_c, new_c = set(old_rows), set(new_rows)
removed = old_c - new_c
added = new_c - old_c
common = old_c & new_c
ratios = sorted(new_rows[c] / old_rows[c] for c in common if old_rows[c] > 0 and new_rows[c] > 0)
median_ratio = ratios[len(ratios) // 2] if ratios else None
extreme = sum(1 for r in ratios if r > 2.0 or r < 0.5)
extreme_frac = round(extreme / len(ratios), 4) if ratios else 0.0
return {
"added": len(added), "removed": len(removed), "common": len(old_codes & new_codes),
"removed_ratio": round(removed_ratio, 4),
"sample_removed": sorted(list(removed))[:10],
"sample_added": sorted(list(added))[:10],
"added": len(added), "removed": len(removed), "common": len(common),
"removed_ratio": round(len(removed) / len(old_c), 4) if old_c else 0.0,
"price_median_ratio": round(median_ratio, 4) if median_ratio is not None else None,
"price_extreme_frac": extreme_frac,
"sample_removed": sorted(removed)[:10],
}
def _anomaly_reason(d: dict) -> str | None:
if d["removed_ratio"] > REMOVED_RATIO_GATE:
return (f"исчезло {d['removed']} кодов ({d['removed_ratio']*100:.0f}% > "
f"{REMOVED_RATIO_GATE*100:.0f}%). Примеры: {d['sample_removed']}")
mr = d["price_median_ratio"]
if mr is not None and not (PRICE_MEDIAN_LOW <= mr <= PRICE_MEDIAN_HIGH):
return (f"медианное изменение цен ×{mr} вне [{PRICE_MEDIAN_LOW}, {PRICE_MEDIAN_HIGH}] "
f"— возможно не тот регион/квартал или сдвиг колонок цен")
if d["price_extreme_frac"] > PRICE_EXTREME_FRAC_GATE:
return (f"{d['price_extreme_frac']*100:.0f}% позиций изменились в цене >2× "
f"(> {PRICE_EXTREME_FRAC_GATE*100:.0f}%) — аномально")
return None
def _rebuild_host_cache(target: Path, report: dict) -> None:
"""Пересобрать fgis_cache.pkl НА ХОСТЕ (rw), чтобы Docker-агент не падал на ro-записи кэша
(pkl станет новее xlsx → контейнеры читают кэш, не пере-парсят, не пишут)."""
try:
from smeta_railway.data.fgis import load_fgis
cache = target.parent / "fgis_cache.pkl"
load_fgis(str(target), str(cache))
report["cache_rebuilt"] = True
except Exception as e: # noqa: BLE001
report["cache_warning"] = (f"НЕ удалось пересобрать fgis_cache.pkl ({type(e).__name__}: {e}). "
f"Собери вручную на хосте (иначе агент пере-парсит каждый раз): "
f"python3 -c \"from smeta_railway.data.fgis import load_fgis; "
f"load_fgis('{target}','{target.parent/'fgis_cache.pkl'}')\"")
def activate(snapshot_xlsx: os.PathLike | str, *, target_file: Path | None = None,
force: bool = False, drop_cache: bool = False) -> dict:
"""Активировать снапшот. Возвращает отчёт. При аномалии без force — {activated: False}."""
force: bool = False) -> dict:
"""Активировать снапшот (под ext_lock, через временную копию). Возвращает отчёт."""
snapshot_xlsx = Path(snapshot_xlsx)
target = Path(target_file) if target_file else _target_file()
v_new = verify_snapshot(snapshot_xlsx)
if not v_new["ok"]:
return {"activated": False, "reason": "новый снапшот не прошёл verify", "verify_new": v_new}
with ext_state.ext_lock():
# Временная неизменяемая копия снапшота: verify И подмена — один и тот же файл (нет TOCTOU).
with tempfile.TemporaryDirectory(dir=str(target.parent)) as td:
staged = Path(td) / "candidate.xlsx"
ext_state._atomic_copy(snapshot_xlsx, staged)
report = {"target": str(target), "verify_new": {k: v for k, v in v_new.items() if k != "_codes"}}
v_new = verify_snapshot(staged)
if not v_new["ok"]:
return {"activated": False, "reason": "новый снапшот не прошёл verify",
"verify_new": {k: v for k, v in v_new.items() if k != "_rows"}}
if target.exists():
v_old = verify_snapshot(target)
d = diff_codes(v_old.get("_codes", set()), v_new["_codes"])
report["diff"] = d
report["verify_old"] = {k: v for k, v in v_old.items() if k != "_codes"}
if d["removed_ratio"] > REMOVED_RATIO_GATE and not force:
report["activated"] = False
report["reason"] = (f"АНОМАЛИЯ: исчезло {d['removed']} кодов "
f"({d['removed_ratio']*100:.0f}% > {REMOVED_RATIO_GATE*100:.0f}%). "
f"Примеры: {d['sample_removed']}. Нужен --force, если это ожидаемо.")
return report
# бэкап текущего рядом (в снапшоты), чтобы не потерять то, что реально стояло
_backup_current(target)
report = {"target": str(target),
"verify_new": {k: v for k, v in v_new.items() if k != "_rows"}}
# атомарная подмена (staging в каталоге движка + os.replace)
ext_state._atomic_copy(snapshot_xlsx, target)
report["activated"] = True
if target.exists():
v_old = verify_snapshot(target)
d = diff_rows(v_old.get("_rows", {}), v_new["_rows"])
report["diff"] = d
reason = _anomaly_reason(d)
if reason and not force:
report["activated"] = False
report["reason"] = f"АНОМАЛИЯ: {reason}. Нужен --force, если это ожидаемо."
return report
_backup_current(target) # сохранить то, что реально стояло (не потерять)
cache = target.parent / "fgis_cache.pkl"
if cache.exists():
if drop_cache:
cache.unlink()
report["cache_dropped"] = True
else:
report["cache_warning"] = (f"fgis_cache.pkl не удалён — движок продолжит читать СТАРЫЙ "
f"кэш! Перезапусти с --yes или удали вручную: {cache}")
report["restart_reminder"] = "Данные заменены. Перезапусти сервис, чтобы движок перечитал файл."
return report
ext_state._atomic_copy(staged, target)
report["activated"] = True
_rebuild_host_cache(target, report)
_record_active(target, v_new)
report["restart_reminder"] = ("Данные заменены и кэш пересобран. Перезапусти сервис, "
"чтобы host-процесс тоже перечитал файл.")
return report
def _backup_current(target: Path) -> None:
"""Сохранить текущий рабочий файл в снапшоты как «что реально стояло» (не потерять)."""
dest_dir = ext_state.ext_dir() / "snapshots/fgis/activated_backup"
# ключ по пути target — прод и тестовые (--target-dir) цепочки ревизий не смешиваются
ext_state.register_snapshot(dest_dir, target, source="activated_backup",
key="fgis_split_form.xlsx", url="(local active file)")
key=str(target.resolve()), url="(local active file)")
def _record_active(target: Path, verify: dict) -> 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(),
}
def main(argv=None) -> int:
@@ -127,23 +195,17 @@ def main(argv=None) -> int:
ap.add_argument("--period", type=int, required=True)
ap.add_argument("--target-dir", help="куда активировать (по умолч. каталог движка); для теста — копия")
ap.add_argument("--force", action="store_true", help="активировать несмотря на аномалию диффа")
ap.add_argument("--yes", action="store_true", help="разрешить удаление fgis_cache.pkl")
args = ap.parse_args(argv)
snap = (ext_state.ext_dir() / "snapshots/fgis/split_form"
/ str(args.subject) / str(args.zone) / str(args.period) / "fgis_split_form.xlsx")
if not snap.exists():
print(f"снапшот не найден: {snap}\nсначала: python3 ext_pull.py --source split_form "
f"--subject {args.subject} --zone {args.zone} --period {args.period}", file=sys.stderr)
print(f"снапшот не найден: {snap}", file=sys.stderr)
return 2
target_file = None
if args.target_dir:
target_file = Path(args.target_dir) / "fgis_split_form.xlsx"
rep = activate(snap, target_file=target_file, force=args.force, drop_cache=args.yes)
import json as _json
print(_json.dumps(rep, ensure_ascii=False, indent=2))
target_file = _target_file(args.target_dir)
rep = activate(snap, target_file=target_file, force=args.force)
print(json.dumps(rep, ensure_ascii=False, indent=2))
return 0 if rep.get("activated") else 1
+26 -1
View File
@@ -17,12 +17,32 @@ import json
import os
import sys
import tempfile
import time
from pathlib import Path
import ext_fetch
import ext_state
import fgis_client as fc
SNAP = "snapshots/fgis"
POLITE_PAUSE_S = 1.5 # пауза между запросами при обходах (вежливость к гос-API, анти-429)
def _verify_xlsx(path: Path, min_rows: int) -> None:
"""Лёгкая проверка скачанного xlsx ДО регистрации: открывается + строк ≥ min.
Ловит server-side обрезанные HTTP-200 выгрузки, которые прошли по размеру (баг Fable)."""
import openpyxl
try:
wb = openpyxl.load_workbook(str(path), read_only=True)
try:
ws = wb.active
n = sum(1 for _ in ws.iter_rows(min_col=1, max_col=1, values_only=True))
finally:
wb.close()
except Exception as e: # noqa: BLE001
raise ext_fetch.FetchError(f"скачанный файл не открывается как xlsx: {type(e).__name__}: {e}")
if n < min_rows:
raise ext_fetch.FetchError(f"скачано строк {n} < {min_rows} — обрезанная выгрузка?")
def _snap_dir(kind: str, subject_id: int, zone_id: int, period_id: int) -> Path:
@@ -44,7 +64,7 @@ def _resolve_period(zone_id: int, period_id: int | None) -> int:
return period_id
lp = fc.latest_period(zone_id)
if not lp:
raise SystemExit(f"нет периодов для зоны {zone_id}")
raise ext_fetch.FetchError(f"нет периодов для зоны {zone_id}") # не SystemExit из библиотеки
return lp["id"]
@@ -54,6 +74,7 @@ def pull_split_form(subject_id: int, zone_id: int, period_id: int | None = None)
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / "fgis_split_form.xlsx"
res = fc.download_split_form(period_id, zone_id, tmp)
_verify_xlsx(tmp, min_rows=1000) # битое/обрезанное не регистрируем
meta = ext_state.register_snapshot(
dest_dir, tmp, source="fgis_split_form", key=f"{subject_id}/{zone_id}/{period_id}",
url=fc.BASE + "/api/EstimatedPrice/BuildingResources/ExportSplitForm",
@@ -68,6 +89,7 @@ def pull_indices(subject_id: int, zone_id: int, period_id: int | None = None) ->
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / "fgis_indices_gosr.xlsx"
fc.download_indices(period_id, zone_id, tmp)
_verify_xlsx(tmp, min_rows=50) # индексы ГОСР — сотни строк; обрезанное не регистрируем
meta = ext_state.register_snapshot(
dest_dir, tmp, source="fgis_indices_gosr", key=f"{subject_id}/{zone_id}/{period_id}",
url=fc.BASE + "/api/IndicesForResourcesGroups/GenerateCustomReport",
@@ -99,8 +121,11 @@ def pull_all_for_subject(subject_id: int, period_id: int | None = None) -> list[
out = []
for zone_id in _zones_of(subject_id):
out.append(pull_split_form(subject_id, zone_id, period_id))
time.sleep(POLITE_PAUSE_S) # вежливость к гос-API (анти-429)
out.append(pull_indices(subject_id, zone_id, period_id))
time.sleep(POLITE_PAUSE_S)
out.append(pull_salary(subject_id, zone_id, period_id))
time.sleep(POLITE_PAUSE_S)
return out
+21 -9
View File
@@ -104,20 +104,32 @@ def sha256_file(path: os.PathLike | str) -> str:
return h.hexdigest()
_lock_fd = None
_lock_depth = 0
@contextmanager
def ext_lock():
"""Межпроцессная блокировка (flock) для сериализации pull/apply над общим хранилищем."""
d = ext_dir()
d.mkdir(parents=True, exist_ok=True)
fd = os.open(str(d / ".lock"), os.O_CREAT | os.O_RDWR, 0o644)
"""Межпроцессная блокировка (flock) для сериализации pull/apply над общим хранилищем.
РЕЕНТРАНТНА в пределах процесса (activate держит лок и вызывает register_snapshot,
который тоже берёт ext_lock — вложенный вход не дедлочит и не отпускает лок раньше)."""
global _lock_fd, _lock_depth
if _lock_depth == 0:
d = ext_dir()
d.mkdir(parents=True, exist_ok=True)
_lock_fd = os.open(str(d / ".lock"), os.O_CREAT | os.O_RDWR, 0o644)
fcntl.flock(_lock_fd, fcntl.LOCK_EX)
_lock_depth += 1
try:
fcntl.flock(fd, fcntl.LOCK_EX)
yield
finally:
try:
fcntl.flock(fd, fcntl.LOCK_UN)
finally:
os.close(fd)
_lock_depth -= 1
if _lock_depth == 0:
try:
fcntl.flock(_lock_fd, fcntl.LOCK_UN)
finally:
os.close(_lock_fd)
_lock_fd = None
# --- state.json (пишут pull/apply, всегда под ext_lock) ---
+51 -41
View File
@@ -1,6 +1,7 @@
"""Срез 1.3: verify + diff + активация. Гейт аномалий (fail-loud) — red-green первым.
Синтетические xlsx с кодами в колонке A (без сети, без реального ФГИС-файла).
"""Срез 1.3 (+ money-safety фиксы Fable): verify+diff по КОДАМ И ЦЕНАМ, гейт аномалий,
temp-verify, пересборка кэша, аудит. red-green на гейтах (удаление кодов И скачок цен).
"""
import json
import sys
from pathlib import Path
@@ -10,13 +11,13 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import ext_apply as ea # noqa: E402
def _make_xlsx(path, codes):
def _make_xlsx(path, codes, price=100.0):
import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["Код", "Наименование", "Цена"]) # шапка
ws.append(["Код", "Наименование", "Цена"])
for c in codes:
ws.append([c, "материал", 100.0])
ws.append([c, "материал", price])
wb.save(str(path))
@@ -24,12 +25,23 @@ def _codes(n, prefix="M"):
return [f"{prefix}-{i:05d}" for i in range(n)]
def test_verify_ok_and_too_small(tmp_path):
@pytest.fixture(autouse=True)
def _env(monkeypatch, tmp_path):
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "_ext"))
# не звать реальный движок в юнит-тестах — проверяем факт вызова отдельно
monkeypatch.setattr(ea, "_rebuild_host_cache",
lambda target, report: report.__setitem__("cache_rebuilt", True))
def test_verify_ok_small_and_priceless(tmp_path):
big = tmp_path / "big.xlsx"; _make_xlsx(big, _codes(1200))
assert ea.verify_snapshot(big)["ok"] is True
small = tmp_path / "small.xlsx"; _make_xlsx(small, _codes(10))
r = ea.verify_snapshot(small)
assert r["ok"] is False and "мало" in r["errors"][0]
assert ea.verify_snapshot(small)["ok"] is False
# цены отсутствуют (0) → тоже не ok
priceless = tmp_path / "pl.xlsx"; _make_xlsx(priceless, _codes(1200), price=0.0)
r = ea.verify_snapshot(priceless)
assert r["ok"] is False and any("цен" in e for e in r["errors"])
def test_verify_rejects_non_xlsx(tmp_path):
@@ -37,52 +49,50 @@ def test_verify_rejects_non_xlsx(tmp_path):
assert ea.verify_snapshot(bad)["ok"] is False
def test_diff_codes_ratio():
d = ea.diff_codes(set(_codes(100)), set(_codes(80)) | set(_codes(5, "NEW")))
assert d["removed"] == 20 and d["added"] == 5
assert d["removed_ratio"] == 0.2
def test_diff_rows_codes_and_prices():
old = {c: 100.0 for c in _codes(100)}
new = {c: 100.0 for c in _codes(80)}
new.update({c: 100.0 for c in _codes(5, "NEW")})
d = ea.diff_rows(old, new)
assert d["removed"] == 20 and d["added"] == 5 and d["price_median_ratio"] == 1.0
def test_fresh_activate_creates_target(tmp_path):
def test_fresh_activate_creates_target_and_records(tmp_path):
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(1200))
tdir = tmp_path / "railway"; tdir.mkdir()
rep = ea.activate(snap, target_file=tdir / "fgis_split_form.xlsx")
assert rep["activated"] is True
assert rep["activated"] is True and rep.get("cache_rebuilt") is True
assert (tdir / "fgis_split_form.xlsx").exists()
# аудит активного среза в state
import ext_state as es
assert es.load_state()["active"]["fgis_split_form"]["codes"] == 1200
def test_gate_blocks_massive_removal_without_force(tmp_path, monkeypatch):
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "_ext"))
def test_gate_blocks_massive_code_removal(tmp_path):
tdir = tmp_path / "railway"; tdir.mkdir()
target = tdir / "fgis_split_form.xlsx"
_make_xlsx(target, _codes(2000)) # текущий: 2000 кодов
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(2000)[:1200]) # новый: пропало 40%
target = tdir / "fgis_split_form.xlsx"; _make_xlsx(target, _codes(2000))
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(2000)[:1200]) # -40% кодов
rep = ea.activate(snap, target_file=target)
assert rep["activated"] is False and "АНОМАЛИЯ" in rep["reason"]
# целевой файл НЕ тронут (всё ещё 1200 кодов)
assert len(ea.read_codes(target)) == 2000
assert rep["activated"] is False and "исчезло" in rep["reason"]
assert len(ea._read_rows(target)) == 2000 # target цел
def test_gate_overridden_by_force(tmp_path, monkeypatch):
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "_ext"))
def test_gate_blocks_price_explosion(tmp_path):
"""Файл с теми же кодами, но ценами в разы — не тот регион/сдвиг колонок (money-safety)."""
tdir = tmp_path / "railway"; tdir.mkdir()
target = tdir / "fgis_split_form.xlsx"
_make_xlsx(target, _codes(2000))
target = tdir / "fgis_split_form.xlsx"; _make_xlsx(target, _codes(1500), price=100.0)
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(1500), price=600.0) # ×6
rep = ea.activate(snap, target_file=target)
assert rep["activated"] is False and "цен" in rep["reason"]
# target не тронут — цена осталась 100
assert list(ea._read_rows(target).values())[0] == 100.0
def test_gate_overridden_by_force_and_backup(tmp_path):
tdir = tmp_path / "railway"; tdir.mkdir()
target = tdir / "fgis_split_form.xlsx"; _make_xlsx(target, _codes(2000))
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(2000)[:1200])
rep = ea.activate(snap, target_file=target, force=True)
assert rep["activated"] is True
assert len(ea.read_codes(target)) == 1200 # применилось
# старый забэкаплен в снапшоты (не потерян)
assert rep["activated"] is True and len(ea._read_rows(target)) == 1200
backups = list((tmp_path / "_ext/snapshots/fgis/activated_backup").glob("*.xlsx"))
assert backups and len(ea.read_codes(backups[0])) == 2000
def test_cache_warning_without_yes(tmp_path, monkeypatch):
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "_ext"))
tdir = tmp_path / "railway"; tdir.mkdir()
(tdir / "fgis_cache.pkl").write_bytes(b"cache")
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(1200))
rep = ea.activate(snap, target_file=tdir / "fgis_split_form.xlsx")
assert "cache_warning" in rep and (tdir / "fgis_cache.pkl").exists() # не удалён без --yes
rep2 = ea.activate(snap, target_file=tdir / "fgis_split_form.xlsx", drop_cache=True)
assert rep2.get("cache_dropped") is True and not (tdir / "fgis_cache.pkl").exists()
assert backups and len(ea._read_rows(backups[0])) == 2000 # старое не потеряно
+2
View File
@@ -19,6 +19,8 @@ def _mock_downloads(monkeypatch, content=b"FAKE-XLSX-" + b"x" * 2000):
monkeypatch.setattr(fc, "salary_registry", lambda z, p, client=None: {"total": 3, "items": [{"code": "1-100-1"}]})
monkeypatch.setattr(fc, "latest_period", lambda z, client=None: {"id": 426, "name": "2 кв 2026"})
monkeypatch.setattr(fc, "price_zones", lambda s, client=None: [{"id": 191, "name": "город Москва"}])
# _verify_xlsx покрыт отдельно; здесь мок-контент не настоящий xlsx — нейтрализуем
monkeypatch.setattr(ep, "_verify_xlsx", lambda p, min_rows: None)
def test_pull_split_form_creates_snapshot_and_state(monkeypatch, tmp_path):