feat(release): stage exact SHA on dev before automatic production
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env bash
|
||||
# Gitea push main -> production only if the identical SHA is live on release dev.
|
||||
set -euo pipefail
|
||||
|
||||
sha="${EXPECTED_SHA:?EXPECTED_SHA is required}"
|
||||
test "${EXPECTED_REF:-}" = refs/heads/main
|
||||
test "$(git rev-parse HEAD)" = "$sha"
|
||||
checkout=$(pwd -P)
|
||||
stage=/home/mcp-user/smeta-web-release
|
||||
prod=/home/mcp-user/smeta-web
|
||||
index=data/real_corpus/estimates_ext_index.json
|
||||
marker=/data_safe/backups/smeta-web/release-ready.json
|
||||
log="/data_safe/backups/smeta-web/release-prod-${sha:0:12}.log"
|
||||
|
||||
exec 9>/tmp/smeta-release-deploy.lock
|
||||
flock -w 1800 9
|
||||
test "$(git -C "$prod" branch --show-current)" = main
|
||||
remote=$(HTTPS_PROXY= HTTP_PROXY= NO_PROXY='*' git -C "$prod" ls-remote --exit-code origin refs/heads/main | cut -f1)
|
||||
test "$remote" = "$sha"
|
||||
HTTPS_PROXY= HTTP_PROXY= NO_PROXY='*' git -C "$prod" fetch -q origin main
|
||||
git -C "$prod" merge-base --is-ancestor HEAD "$sha"
|
||||
python3 "$checkout/scripts/release_gate.py" verify "$sha" "$stage" "$prod/$index" "$marker"
|
||||
systemctl is-active --quiet smeta-web-release
|
||||
curl -fsS --noproxy '*' http://127.0.0.1:8106/health | grep -q '"status":"ok"'
|
||||
index_before=$(sha256sum "$prod/$index" | cut -d' ' -f1)
|
||||
env_before=$(sha256sum "$prod/.env" | cut -d' ' -f1)
|
||||
|
||||
# Fresh full gate for this exact main push; the dev approval can be days old.
|
||||
cp "$prod/$index" "$checkout/$index"
|
||||
sqlite3 "$prod/smeta-web.db" ".backup $checkout/smeta-web.db"
|
||||
APP_DIR="$checkout" COPY_DIR=/home/mcp-user/smeta-prod-auto-predeploy \
|
||||
bash "$checkout/scripts/predeploy-tests.sh" > "$log" 2>&1 || {
|
||||
tail -30 "$log" >&2
|
||||
exit 1
|
||||
}
|
||||
test "$(head -n 1 "$checkout/.predeploy-stamp")" = "$sha"
|
||||
test "$(sha256sum "$prod/$index" | cut -d' ' -f1)" = "$index_before"
|
||||
test "$(sha256sum "$prod/.env" | cut -d' ' -f1)" = "$env_before"
|
||||
test "$(HTTPS_PROXY= HTTP_PROXY= NO_PROXY='*' git -C "$prod" ls-remote --exit-code origin refs/heads/main | cut -f1)" = "$sha"
|
||||
python3 "$checkout/scripts/release_gate.py" verify "$sha" "$stage" "$prod/$index" "$marker"
|
||||
cp "$checkout/.predeploy-stamp" "$prod/.predeploy-stamp"
|
||||
APP_DIR="$prod" bash "$prod/scripts/deploy.sh"
|
||||
|
||||
test "$(git -C "$prod" rev-parse HEAD)" = "$sha"
|
||||
test "$(sha256sum "$prod/$index" | cut -d' ' -f1)" = "$index_before"
|
||||
test "$(sha256sum "$prod/.env" | cut -d' ' -f1)" = "$env_before"
|
||||
systemctl is-active --quiet smeta-web
|
||||
curl -fsS --noproxy '*' http://127.0.0.1:8101/health | grep -q '"status":"ok"'
|
||||
(cd "$prod" && set -a && . ./.env && set +a &&
|
||||
python3 -c 'import health_checks; assert health_checks.check_unpriced_runs().ok')
|
||||
canary=$(cd "$prod" && CANARY_DRY_RUN=1 \
|
||||
JOURNEY_STATE=/tmp/smeta-release-journey.state bash scripts/journey_canary.sh)
|
||||
printf '%s\n' "$canary"
|
||||
[[ "$canary" == *' OK journey:'* ]]
|
||||
echo "RELEASE_PROD_OK sha=$sha log=$log"
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env bash
|
||||
# Gitea push release -> exact candidate on isolated release dev (8106).
|
||||
set -euo pipefail
|
||||
|
||||
sha="${EXPECTED_SHA:?EXPECTED_SHA is required}"
|
||||
test "${EXPECTED_REF:-}" = refs/heads/release
|
||||
test "$(git rev-parse HEAD)" = "$sha"
|
||||
stage=/home/mcp-user/smeta-web-release
|
||||
prod=/home/mcp-user/smeta-web
|
||||
index=data/real_corpus/estimates_ext_index.json
|
||||
marker=/data_safe/backups/smeta-web/release-ready.json
|
||||
log="/data_safe/backups/smeta-web/release-stage-${sha:0:12}.log"
|
||||
test -d "$stage/.git"
|
||||
test "$(git -C "$stage" branch --show-current)" = release
|
||||
|
||||
exec 9>/tmp/smeta-release-deploy.lock
|
||||
flock -w 1800 9
|
||||
remote=$(HTTPS_PROXY= HTTP_PROXY= NO_PROXY='*' git -C "$stage" ls-remote --exit-code origin refs/heads/release | cut -f1)
|
||||
test "$remote" = "$sha"
|
||||
test "$(git -C "$prod" branch --show-current)" = main
|
||||
printf '{"status":"pending"}\n' > "$marker"
|
||||
|
||||
HTTPS_PROXY= HTTP_PROXY= NO_PROXY='*' git -C "$stage" fetch -q origin
|
||||
test "$(git -C "$stage" rev-parse origin/release)" = "$sha"
|
||||
git -C "$stage" merge-base --is-ancestor origin/main "$sha"
|
||||
git -C "$stage" merge-base --is-ancestor HEAD "$sha"
|
||||
dirty=$(git -C "$stage" diff --name-only)
|
||||
test -z "$dirty" || test "$dirty" = "$index"
|
||||
git -C "$stage" diff --cached --quiet
|
||||
if [ -n "$dirty" ]; then
|
||||
test -z "$(git -C "$stage" diff --name-only HEAD "$sha" -- "$index")"
|
||||
fi
|
||||
|
||||
if systemctl is-active --quiet smeta-web-release; then
|
||||
sudo systemctl stop smeta-web-release
|
||||
fi
|
||||
git -C "$stage" merge --ff-only "$sha"
|
||||
cp "$prod/$index" "$stage/$index"
|
||||
sqlite3 "$prod/smeta-web.db" ".backup $stage/smeta-web.db"
|
||||
test "$(stat -c %i "$prod/smeta-web.db")" != "$(stat -c %i "$stage/smeta-web.db")"
|
||||
test "$(readlink -f "$prod/smeta-web.db")" != "$(readlink -f "$stage/smeta-web.db")"
|
||||
python3 "$stage/scripts/shadow/preflight.py" "$stage/.env"
|
||||
if grep -Eq '^(ALERT_TG|TG_BOT_TOKEN|TG_CHAT_ID|ROBOKASSA|SMTP|YOOKASSA)[A-Z_]*=.+' "$stage/.env"; then
|
||||
echo 'release dev has an external notification or payment channel' >&2
|
||||
exit 1
|
||||
fi
|
||||
test "$(sha256sum "$prod/$index" | cut -d' ' -f1)" = \
|
||||
"$(sha256sum "$stage/$index" | cut -d' ' -f1)"
|
||||
|
||||
APP_DIR="$stage" COPY_DIR=/home/mcp-user/smeta-web-release-predeploy \
|
||||
bash "$stage/scripts/predeploy-tests.sh" > "$log" 2>&1 || {
|
||||
tail -30 "$log" >&2
|
||||
exit 1
|
||||
}
|
||||
test "$(head -n 1 "$stage/.predeploy-stamp")" = "$sha"
|
||||
sudo systemctl restart smeta-web-release
|
||||
for i in $(seq 1 30); do
|
||||
if systemctl is-active --quiet smeta-web-release &&
|
||||
curl -fsS --noproxy '*' http://127.0.0.1:8106/health | grep -q '"status":"ok"'; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
systemctl is-active --quiet smeta-web-release
|
||||
curl -fsS --noproxy '*' http://127.0.0.1:8106/health | grep -q '"status":"ok"'
|
||||
test "$(git -C "$stage" rev-parse HEAD)" = "$sha"
|
||||
test "$(sha256sum "$prod/$index" | cut -d' ' -f1)" = \
|
||||
"$(sha256sum "$stage/$index" | cut -d' ' -f1)"
|
||||
|
||||
(cd "$stage" && set -a && . ./.env && set +a &&
|
||||
PYTHONPATH="$stage" timeout 420 python3 scripts/release_smoke.py)
|
||||
python3 "$stage/scripts/release_gate.py" mark "$sha" "$stage" "$prod/$index" "$marker"
|
||||
echo "RELEASE_DEV_OK sha=$sha port=8106 log=$log"
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check that production receives the exact revision already tested on release dev."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
SHA = re.compile(r"[0-9a-f]{40}\Z")
|
||||
|
||||
|
||||
def _git(stage: Path, *args: str) -> str:
|
||||
result = subprocess.run(["git", "-C", str(stage), *args],
|
||||
check=True, capture_output=True, text=True)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def _index_hash(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _stage_problems(expected: str, stage: Path) -> list[str]:
|
||||
problems = []
|
||||
try:
|
||||
if _git(stage, "symbolic-ref", "--quiet", "--short", "HEAD") != "release":
|
||||
problems.append("дев-каталог не на ветке release")
|
||||
if _git(stage, "rev-parse", "HEAD") != expected:
|
||||
problems.append("дев-каталог уже на другом коммите")
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
problems.append("не удалось прочесть git дев-каталога")
|
||||
try:
|
||||
lines = (stage / ".predeploy-stamp").read_text().splitlines()
|
||||
if len(lines) < 3 or lines[0] != expected or lines[2] != "full: not-ui+ui":
|
||||
problems.append("нет полного тестового следа этого коммита на деве")
|
||||
except OSError:
|
||||
problems.append("нет тестового следа на деве")
|
||||
return problems
|
||||
|
||||
|
||||
def verify(expected: str, stage: Path, prod_index: Path, marker: Path) -> list[str]:
|
||||
stage, prod_index, marker = Path(stage), Path(prod_index), Path(marker)
|
||||
if not SHA.fullmatch(expected):
|
||||
return ["неверный SHA кандидата"]
|
||||
problems = _stage_problems(expected, stage)
|
||||
try:
|
||||
data = json.loads(marker.read_text())
|
||||
if not isinstance(data, dict) or data.get("sha") != expected:
|
||||
problems.append("дев не подтвердил точный коммит")
|
||||
elif data.get("index_sha256") != _index_hash(prod_index):
|
||||
problems.append("боевой рабочий индекс изменился после проверки дев-версии")
|
||||
except (OSError, ValueError, TypeError):
|
||||
problems.append("нет корректного подтверждения дев-версии")
|
||||
return problems
|
||||
|
||||
|
||||
def mark_ready(expected: str, stage: Path, prod_index: Path, marker: Path) -> None:
|
||||
stage, prod_index, marker = Path(stage), Path(prod_index), Path(marker)
|
||||
if not SHA.fullmatch(expected):
|
||||
raise ValueError("неверный SHA кандидата")
|
||||
problems = _stage_problems(expected, stage)
|
||||
if problems:
|
||||
raise ValueError("; ".join(problems))
|
||||
data = {"sha": expected, "index_sha256": _index_hash(prod_index),
|
||||
"tested_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")}
|
||||
marker.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(prefix=".release-ready-", dir=marker.parent)
|
||||
try:
|
||||
os.fchmod(fd, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
||||
json.dump(data, stream, ensure_ascii=False)
|
||||
stream.write("\n")
|
||||
os.replace(tmp, marker)
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("mode", choices=("verify", "mark"))
|
||||
parser.add_argument("sha")
|
||||
parser.add_argument("stage", type=Path)
|
||||
parser.add_argument("prod_index", type=Path)
|
||||
parser.add_argument("marker", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.mode == "mark":
|
||||
try:
|
||||
mark_ready(args.sha, args.stage, args.prod_index, args.marker)
|
||||
except (OSError, ValueError) as error:
|
||||
print(f"release gate: {error}")
|
||||
return 2
|
||||
print(f"release ready: {args.sha}")
|
||||
return 0
|
||||
problems = verify(args.sha, args.stage, args.prod_index, args.marker)
|
||||
for problem in problems:
|
||||
print(f"release gate: {problem}")
|
||||
return 2 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One real agent turn on isolated release dev; never prints response content."""
|
||||
import json
|
||||
import secrets
|
||||
import sqlite3
|
||||
|
||||
import auth
|
||||
import db
|
||||
import regional_ref
|
||||
from scripts.shadow.send import send
|
||||
|
||||
|
||||
def main() -> None:
|
||||
email = "release-smoke@local"
|
||||
if db.get_user_by_email(email) is None:
|
||||
db.create_user(email, auth.hash_password(secrets.token_hex(16)))
|
||||
db.admin_verify_user(email)
|
||||
db.set_user_agent_access(email, True)
|
||||
try:
|
||||
with sqlite3.connect(str(regional_ref.DEFAULT_DB)) as regional:
|
||||
sample = regional.execute(
|
||||
"select s.name, w.code from works w join subjects s "
|
||||
"on s.code=w.subject_id where w.kind='ТЕР' and w.price is not null limit 1"
|
||||
).fetchone()
|
||||
if not sample:
|
||||
raise RuntimeError("no regional test sample")
|
||||
region, code = sample
|
||||
result = send(
|
||||
{"tab_id": "release-smoke", "message":
|
||||
f"Составь смету на работу по расценке ТЕР {code} в {region}, объём 1 м3."},
|
||||
base_url="http://127.0.0.1:8106", token=auth._make_token(email),
|
||||
timeout=360,
|
||||
)
|
||||
with sqlite3.connect("smeta-web.db") as local:
|
||||
usage = local.execute(
|
||||
"select output_tokens from llm_usage where username=? and path='agent' "
|
||||
"order by ts desc limit 1", (email,)
|
||||
).fetchone()
|
||||
if not result["дошёл"] or not usage or not (usage[0] or 0) > 0:
|
||||
raise RuntimeError("agent route did not finish with accounted output")
|
||||
print(json.dumps({"agent_done": True, "output_accounted": True,
|
||||
"tool_count": len(result["инструменты"]),
|
||||
"duration_s": result["длительность_с"]}))
|
||||
finally:
|
||||
db.soft_delete_user(email)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user