Files
Jyotisha/tests/test_release_capacity_2428.py
ClaudeandClaude Opus 5.5 0054781bc5
Independent Staging Quality Gate / validate-frontend (push) Successful in 6m34s
Independent Staging Quality Gate / validate-python (push) Successful in 8m34s
Independent Staging Quality Gate / publish (push) Successful in 3m57s
ops: container memory limits, api init, 65% disk alert, release cleanup (BUG-2428)
- postgres 1g + oom_score_adj -500; api 1536m + init; web 768m; caddy 128m
  (BUG-2416 hardening kept; web keeps its own SIGTERM handling)
- disk alert 80% -> 65%, below the 70% backup stop line
- ops-check: container_memory_high at 85% of the container's own limit
- after a verified production deploy: keep newest 5 pre-release recovery
  points (+ baseline) and current/previous app images; dry-run supported

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-26 23:18:02 +08:00

268 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""BUG-2428: container memory limits, api init, disk alert before the backup stop line,
container memory alert, and release cleanup (recovery points + old app images).
Fixtures are fictional; nothing here touches a real host or Docker."""
from __future__ import annotations
import json
import re
import subprocess
import sys
from pathlib import Path
import yaml
from tests.test_beta_safety_net import BASH, ROOT, alert_lines, bash_path, write_text
from tests.test_monitor_alerts_2348 import run_ops
DEPLOY = ROOT / "deploy"
PRUNE = DEPLOY / "prune-production-release.sh"
DEPLOY_SCRIPT = DEPLOY / "run-production-deploy.sh"
def load(name: str) -> dict:
return yaml.safe_load((DEPLOY / name).read_text(encoding="utf-8"))
def test_memory_limits_match_the_owner_approved_capacity_note() -> None:
# 原值: api 2g / web 1g / caddy 256m(BUG-2416),postgres 无上限、oom_score_adj 0。
# 新值: api 1536m / web 768m / caddy 128m / postgres 1g + oom_score_adj -500。
# 原因: BUG-2428,产品 11-26 批准 docs/operations/capacity-2026-11.md 的建议;合计 3.4 GB < 3.9 GB。
server = load("docker-compose.server.yml")["services"]
postgres = load("docker-compose.postgres.yml")["services"]["postgres"]
assert server["api"]["mem_limit"] == "1536m"
assert server["web"]["mem_limit"] == "768m"
assert server["caddy"]["mem_limit"] == "128m"
assert postgres["mem_limit"] == "1g"
assert postgres["oom_score_adj"] < 0 and postgres["oom_score_adj"] == -500
for name in ("api", "web", "caddy"):
assert "oom_score_adj" not in server[name] # only the database is protected
def test_api_gets_init_and_web_keeps_its_own_sigterm_handling() -> None:
# 原值: api 无 init(Python 做 1 号进程不理 SIGTERM,停容器等满 10 秒)。新值: init: true。
services = load("docker-compose.server.yml")["services"]
assert services["api"]["init"] is True
# web handles SIGTERM itself (BUG-2352) and must keep its 40 s grace period.
assert "init" not in services["web"]
assert services["web"]["stop_grace_period"] == "40s"
assert services["web"]["environment"]["NEXT_MANUAL_SIG_HANDLE"] == "true"
# BUG-2416 hardening is unchanged.
for name in ("api", "web"):
assert services[name]["read_only"] is True
assert services[name]["cap_drop"] == ["ALL"]
def test_disk_alert_threshold_is_below_the_backup_stop_line() -> None:
alert = (DEPLOY / "monitor" / "healthcheck-alert.sh").read_text(encoding="utf-8")
recovery = (DEPLOY / "run-production-recovery.sh").read_text(encoding="utf-8")
alert_at = int(re.search(r'if \[ "\$percent" -ge (\d+) \]', alert).group(1))
stop_at = int(re.search(r"\(\( usage_percent < (\d+) \)\)", recovery).group(1))
assert alert_at == 65 and stop_at == 70 and alert_at < stop_at
assert "65%%" in (DEPLOY / "monitor" / "notify-feishu.sh").read_text(encoding="utf-8")
def test_container_memory_alert_opens_once_and_recovers(tmp_path: Path) -> None:
state = tmp_path / "state"
api = "d" * 64
pg = "e" * 64
base = {
"fake_ids": f"{api[:12]}\n{pg[:12]}",
"fake_inspect": f"{api} /jyotisha-production-api-1 0 false\n{pg} /jyotisha-production-postgres-1 0 false",
}
limit = 1536 * 1024 * 1024
api_dir = tmp_path / "cgroup" / "system.slice" / f"docker-{api}.scope"
pg_dir = tmp_path / "cgroup" / "system.slice" / f"docker-{pg}.scope"
api_dir.mkdir(parents=True)
pg_dir.mkdir(parents=True)
# postgres: page cache fills the limit, but it is inactive_file, so no alert.
write_text(pg_dir / "memory.current", f"{1024 ** 3}\n")
write_text(pg_dir / "memory.max", f"{1024 ** 3}\n")
write_text(pg_dir / "memory.stat", f"anon 200000000\ninactive_file {700 * 1024 ** 2}\n")
def run(used: int):
write_text(api_dir / "memory.current", f"{used + 50 * 1024 ** 2}\n")
write_text(api_dir / "memory.max", f"{limit}\n")
write_text(api_dir / "memory.stat", f"anon {used}\ninactive_file {50 * 1024 ** 2}\n")
return run_ops(tmp_path, state, **base)
assert run(1000 * 1024 ** 2).returncode == 0 # 65 %: quiet
assert [line for line in alert_lines(state) if "memory" in line] == []
assert run(limit * 9 // 10 + 1024).returncode == 0
lines = [line for line in alert_lines(state) if "container_memory_high" in line]
assert len(lines) == 1 and "service=api" in lines[0] and "count=90" in lines[0]
assert run(int(limit * 0.95)).returncode == 0
assert len([line for line in alert_lines(state) if "container_memory_high" in line]) == 1
assert run(700 * 1024 ** 2).returncode == 0
assert "service=api" in alert_lines(state)[-1] and "errorCode=recovered" in alert_lines(state)[-1]
assert not any("service=postgres" in line for line in alert_lines(state))
def run_prune(script: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[BASH, "-c", f'source "{bash_path(PRUNE)}"\n{script}'],
capture_output=True, text=True, encoding="utf-8",
env={"PATH": "/usr/bin:/bin", **(env or {})},
)
def point(directory: Path, stamp: str, verify: bool = True) -> str:
name = f"production-pre-migration-{stamp}.dump.enc"
write_text(directory / name, "x")
if verify:
write_text(directory / f"production-pre-migration-{stamp}-restore-verify.json", "{}")
return name
def test_recovery_points_keep_newest_five_plus_baseline(tmp_path: Path) -> None:
backups = tmp_path / "backups"
backups.mkdir()
stamps = [f"202611{day:02d}T030000Z" for day in range(1, 9)] # 8 points, oldest first
names = [point(backups, stamp) for stamp in stamps]
daily = backups / "production-daily-20261101T040000Z.dump.enc"
write_text(daily, "d")
other = backups / "production-pre-migration-notes.txt"
write_text(other, "keep")
baseline = tmp_path / "recovery-baseline.env"
write_text(baseline, f"RECOVERY_REFERENCE=gitea-actions-run-1/{names[0]}\nRECOVERY_FORMAT=2\n")
dry = run_prune(f'prune_recovery_points "{bash_path(backups)}" 5 "{bash_path(baseline)}"',
{"RELEASE_CLEANUP_DRY_RUN": "1"})
assert dry.returncode == 0, dry.stderr
assert dry.stdout.count("would_remove recovery_point=") == 2
assert all((backups / name).exists() for name in names)
done = run_prune(f'prune_recovery_points "{bash_path(backups)}" 5 "{bash_path(baseline)}"')
assert done.returncode == 0, done.stderr
removed = re.findall(r"removed recovery_point=(\S+)", done.stdout)
assert removed == [names[2], names[1]] # oldest two outside the newest five; baseline kept
remaining = sorted(path.name for path in backups.glob("production-pre-migration-*.dump.enc"))
assert remaining == sorted([names[0], *names[3:]])
assert not (backups / f"production-pre-migration-{stamps[1]}-restore-verify.json").exists()
assert (backups / f"production-pre-migration-{stamps[0]}-restore-verify.json").exists()
assert daily.exists() and other.exists()
assert "recovery_points_kept=5 baseline=" in done.stdout
again = run_prune(f'prune_recovery_points "{bash_path(backups)}" 5 "{bash_path(baseline)}"')
assert "removed" not in again.stdout
def test_recovery_points_refuse_unsafe_input(tmp_path: Path) -> None:
target = tmp_path / "real"
target.mkdir()
link = tmp_path / "link"
link.symlink_to(target)
assert run_prune(f'prune_recovery_points "{bash_path(link)}" 5').returncode != 0
assert run_prune(f'prune_recovery_points "{bash_path(target)}" 0').returncode != 0
assert run_prune('prune_recovery_points "" 5').returncode != 0
FAKE_DOCKER = r'''#!PYTHON
import json, sys
cfg_path = sys.argv[0] + ".json"
cfg = json.load(open(cfg_path))
args = sys.argv[1:]
def out(lines):
for line in lines:
print(line)
if args[:2] == ["image", "inspect"]:
fmt, ref = args[3], args[4]
image = cfg["refs"].get(ref, ref)
if image not in cfg["images"]:
sys.exit(1)
if fmt == "{{.Id}}":
out([image])
else:
out(cfg["images"][image])
elif args[:2] == ["image", "ls"]:
out(list(cfg["images"]))
elif args[:2] == ["image", "rm"]:
image = args[2]
if image in cfg.get("busy", []):
sys.exit(1)
del cfg["images"][image]
cfg.setdefault("removed", []).append(image)
json.dump(cfg, open(cfg_path, "w"))
elif args[:1] == ["ps"]:
out(list(cfg["containers"]))
elif args[:1] == ["inspect"]:
out([cfg["containers"][args[3]]])
else:
sys.exit(2)
'''
def image_id(char: str) -> str:
return "sha256:" + char * 64
def test_release_images_keep_current_previous_and_in_use(tmp_path: Path) -> None:
repo = "registry.example:5000/root/jyotisha"
cur_api, cur_web, prev_api, prev_web = image_id("1"), image_id("2"), image_id("3"), image_id("4")
old_api, old_web, stopped, busy = image_id("5"), image_id("6"), image_id("7"), image_id("8")
postgres, caddy = image_id("a"), image_id("b")
cur_api_ref = f"{repo}@sha256:{'1' * 64}"
images = {
cur_api: [cur_api_ref],
cur_web: [f"{repo}@sha256:{'2' * 64}"],
prev_api: [f"{repo}@sha256:{'3' * 64}"],
prev_web: [f"{repo}@sha256:{'4' * 64}"],
old_api: [f"{repo}@sha256:{'5' * 64}"],
old_web: [f"{repo}:web-old"],
stopped: [f"{repo}@sha256:{'7' * 64}"],
busy: [f"{repo}@sha256:{'8' * 64}"],
postgres: ["postgres@sha256:" + "a" * 64, "postgres:17-alpine"],
caddy: ["caddy@sha256:" + "b" * 64],
}
cfg = {
"refs": {cur_api_ref: cur_api, f"{repo}@sha256:{'2' * 64}": cur_web},
"images": images,
"containers": {"c1": cur_api, "c2": cur_web, "c3": postgres, "c4": stopped},
"busy": [busy],
}
docker = tmp_path / "docker"
write_text(docker, FAKE_DOCKER.replace("#!PYTHON", f"#!{sys.executable}"))
docker.chmod(0o755)
(tmp_path / "docker.json").write_text(json.dumps(cfg), encoding="utf-8")
env = {"PATH": f"{bash_path(tmp_path)}:/usr/bin:/bin"}
call = (f'prune_release_images "{repo}" "{cur_api_ref}" "{repo}@sha256:{"2" * 64}" '
f'"{prev_api}" "{prev_web}"')
dry = run_prune(call, {**env, "RELEASE_CLEANUP_DRY_RUN": "1"})
assert dry.returncode == 0, dry.stderr
assert dry.stdout.count("would_remove image=") == 3
assert "removed" not in json.loads((tmp_path / "docker.json").read_text())
done = run_prune(call, env)
assert done.returncode == 0, done.stderr
state = json.loads((tmp_path / "docker.json").read_text())
assert sorted(state["removed"]) == sorted([old_api, old_web])
assert f"image_remove_failed image={'8' * 12}" in done.stdout
for kept in (cur_api, cur_web, prev_api, prev_web, stopped, busy, postgres, caddy):
assert kept in state["images"]
# A keep target missing on the host: nothing is removed at all.
missing = run_prune(f'prune_release_images "{repo}" "{image_id("f")}"', env)
assert missing.returncode == 0 and "removed" not in missing.stdout
assert run_prune('prune_release_images "bad repo" x', env).returncode != 0
def test_deploy_runs_cleanup_only_after_verification() -> None:
text = DEPLOY_SCRIPT.read_text(encoding="utf-8")
cleanup = text.index("source deploy/prune-production-release.sh")
assert text.index('mv -f "$revision_file" "$state_directory/deployed-revision"') < cleanup
assert text.index("trap - ERR") < cleanup
assert 'prune_recovery_points "$DEPLOY_PATH/backups" 5 "$state_directory/recovery-baseline.env" ||' in text
assert '"$previous_api_target" "$previous_web_target" ||' in text
assert "images_skipped=no_distinct_previous_release" in text
prune = PRUNE.read_text(encoding="utf-8")
assert "image rm -f" not in prune and "--force" not in prune and "system prune" not in prune
assert "production-daily" not in prune.split("set -euo pipefail", 1)[1]
assert "oss" not in prune.lower().split("set -euo pipefail", 1)[1]
def test_release_scripts_pass_bash_n() -> None:
for script in (PRUNE, DEPLOY_SCRIPT, DEPLOY / "monitor" / "ops-check.sh", DEPLOY / "monitor" / "healthcheck-alert.sh"):
completed = subprocess.run([BASH, "-n", str(script)], capture_output=True, text=True)
assert completed.returncode == 0, completed.stderr