diff --git a/scripts/deploy.sh b/scripts/deploy.sh index 6812c20..70e8ddb 100644 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -24,6 +24,14 @@ if ! python3 -m py_compile ./*.py; then exit 1 fi +# Регресс-гейт (money-math + скоуп сессий) ДО рестарта. Красный → откат, прод не трогаем. +# Детерминированные инварианты сметы: занижение итога/потеря чужой изоляции = блок деплоя. +if ! python3 scripts/regression_gate.py; then + echo "[$(date)] ERROR: регресс-гейт КРАСНЫЙ — откат на $PREV, рестарт НЕ выполнялся" + git reset --hard "$PREV" + exit 1 +fi + sudo systemctl restart smeta-web sleep 4 diff --git a/scripts/regression_gate.py b/scripts/regression_gate.py new file mode 100644 index 0000000..8cc921a --- /dev/null +++ b/scripts/regression_gate.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Регресс-гейт (срез ядра 3.1/3.2) — детерминированная проверка «money-math» +ПЕРЕД прод-рестартом. Standalone: только stdlib + pydantic (уже стоит для FastAPI), +БЕЗ pytest — чтобы гейт работал на прод-сервере без доп. зависимостей. + +Что проверяет (то, что при поломке молча занизит/исказит смету): + 1. Верификатор инвариантов estimate_verify: чистая смета ok; мутация → конкретная ошибка. + 2. Самосогласованность Summary .gge (ФОТ = ЗП рабочих + машинистов). + 3. KEYSTONE known-answer: LLM-контракт → strict-движок → verify даёт итог ДО КОПЕЙКИ (4380.0). + 4. Скоуп операций сессий: нельзя переименовать/удалить чужой диалог. + +Вызов: python3 scripts/regression_gate.py (exit 0 = зелёно, exit 1 = блокировать деплой) +Fail-loud: любой провал печатает FAIL и роняет процесс — deploy.sh обязан прерваться. +""" +import os +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT.parent / "smeta-railway" / "src")) + +_fails: list[str] = [] + + +def check(name: str, cond: bool, detail: str = ""): + mark = "ok " if cond else "FAIL" + print(f" [{mark}] {name}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + _fails.append(name + (f": {detail}" if detail else "")) + + +def gate_verifier(): + import estimate_verify as ev + clean = { + "positions": [ + {"code": "01-01-001-01", "name": "A", "unit": "м3", "qty": 2.0, + "unit_cost": 100.0, "total": 200.0, "norm_base": "ГЭСН"}, + {"code": "05-01-001-02", "name": "B", "unit": "м3", "qty": 3.0, + "unit_cost": 50.0, "total": 150.0, "norm_base": "ГЭСН"}, + ], + "totals": {"grand_total": 350.0, "vat_pct": 22.0, "vat": 77.0, "total_with_vat": 427.0}, + } + r = ev.verify(clean) + check("verifier: чистая смета ok", r["ok"], str(r["errors"])) + + bad = {k: (v.copy() if isinstance(v, dict) else list(v)) for k, v in clean.items()} + bad["positions"] = [dict(p) for p in clean["positions"]] + bad["positions"][0]["total"] = 999.0 # 2×100=200, стоит 999 + rb = ev.verify(bad) + check("verifier: битая арифметика ловится", not rb["ok"] + and any("кол-во×цена" in e["rule"] for e in rb["errors"])) + + +def gate_gge_summary(): + import estimate_verify as ev + ok = ev.verify_gge_summary({"Salary": 100.0, "WorkersSalary": 60.0, "MachinistSalary": 40.0}) + check("gge summary: ФОТ=ЗПраб+ЗПмаш сходится", ok["errors"] == [] and ok["checked"] == 1) + bad = ev.verify_gge_summary({"Salary": 100.0, "WorkersSalary": 60.0, "MachinistSalary": 30.0}) + check("gge summary: расхождение ФОТ ловится", len(bad["errors"]) == 1) + + +def gate_keystone(): + """LLM-контракт → strict-движок(НР/СП реальные) → verify. Итог ДО КОПЕЙКИ. + Движок в отдельном репо smeta-railway; если он не рядом (иная раскладка на сервере) — + keystone пропускаем с предупреждением, а не роняем весь гейт из-за окружения. + Локально (перед push) smeta-railway на месте → проверка полноценная.""" + try: + import estimate_contract as ec + from smeta_railway.data.fgis import FGISLookup + from smeta_railway.models import NormResources, MaterialResource, LaborResource + except ImportError as e: + print(f" [WARN] keystone пропущен — движок недоступен в этой раскладке ({e})") + return + + resources = {"01-01-001-01": NormResources( + norm_code="01-01-001-01", unit="м3", + ozp=LaborResource(razryad=3.0, chel_hours=1.0), + materials=[MaterialResource(code="M1", name="Мат", unit="кг", qty=10.0, cost_base=100.0)])} + fgis = FGISLookup() + fgis.labor_price_map["1-100-30"] = 500.0 + + draft = ec.EstimateDraft(positions=[ec.DraftPosition(code="ГЭСН 01-01-001-01", unit="м3", qty=2)]) + r = ec.build_and_calc(draft, resources, fgis) + # ОТ=1×2×500=1000; мат=10×2×100=2000; ПЗ=3000; ФОТ=1000; НР=92%→920; СП=46%→460; итог=4380 + check("keystone: golden итог 4380.0 до копейки", r["ok"] and r["grand_total"] == 4380.0, + f"ok={r['ok']} grand_total={r['grand_total']} missing={r['missing']}") + # fail-loud: несуществующий код → ok=False + bad = ec.EstimateDraft(positions=[ec.DraftPosition(code="ГЭСН 99-01-001-01", unit="м3", qty=1)]) + rb = ec.build_and_calc(bad, {}, fgis) + check("keystone: несуществующий код → fail-loud", rb["ok"] is False) + + +def gate_session_scope(): + tmp = tempfile.mkdtemp() + os.environ["DB_PATH"] = str(Path(tmp) / "gate.db") + # db читает DB_PATH на импорте — импортируем ПОСЛЕ установки env + import importlib + import db as _db + importlib.reload(_db) + _db.init_db() + _db.save_message("alice", "tabX", "user", "моя смета") + _db.save_message("bob", "tabX", "user", "чужая смета") + _db.set_session_title("alice", "tabX", "Дом") + titles = {s["tab_id"]: s.get("title") for s in _db.list_sessions("alice")} + check("sessions: переименование видно у владельца", titles.get("tabX") == "Дом") + _db.delete_session("alice", "tabX") + check("sessions: удаление скоупано (чужой цел)", + [s["tab_id"] for s in _db.list_sessions("alice")] == [] + and [s["tab_id"] for s in _db.list_sessions("bob")] == ["tabX"]) + + +def main(): + print("Регресс-гейт (money-math + session-scope):") + for g in (gate_verifier, gate_gge_summary, gate_keystone, gate_session_scope): + try: + g() + except Exception as e: # noqa: BLE001 — любой сбой гейта = блок деплоя + _fails.append(f"{g.__name__}: {type(e).__name__}: {e}") + print(f" [FAIL] {g.__name__} упал: {type(e).__name__}: {e}") + if _fails: + print(f"\nГЕЙТ КРАСНЫЙ — {len(_fails)} провал(ов). Деплой блокируется:") + for f in _fails: + print(f" ✗ {f}") + sys.exit(1) + print("\nГЕЙТ ЗЕЛЁНЫЙ — money-math и скоуп сессий целы.") + + +if __name__ == "__main__": + main()