Screen the cost runs for foreign load and check a pass without S3
The cost matrix shares the Docker VM with the stands and builds of other labs. Each run now reads the VM-wide /proc/stat and the cpu.stat of the s3 and postgres cgroups before and after the pass, and the reconciler reports its own CPU time. Foreign CPU over the window is the busy time minus ours minus the cost of starting a container (1.5 core-s in the VM and 0.5 on the pinned cores, measured on the idle stand). A run with more than 2 foreign cores in the VM or 0.25 on the pinned cores goes to cost/disturbed and is repeated after 15 s of quiet, up to three times; docker stats of the whole host are saved before and after the series. The demo also runs a pass with s3 stopped: it must exit with code 1 in bounded time, log reconcile.failed and leave PostgreSQL and the bucket as they were. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
3b3cb5bd7f
commit
5c3c238d17
+153
-24
@@ -3,6 +3,7 @@ import argparse
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import struct
|
||||
import subprocess
|
||||
@@ -24,6 +25,8 @@ FLAGS = ("--grace", str(GRACE), "--skew", "0")
|
||||
INTENT_AGE = 300
|
||||
LOCK_KEY = 20260004
|
||||
FIXABLE = ("orphan_stale", "missing", "size_mismatch", "sha_mismatch", "pending_stale")
|
||||
USER_HZ = 100
|
||||
BUSY = (0, 1, 2, 5, 6, 7)
|
||||
|
||||
|
||||
def run(cmd, env=None, stdin=None):
|
||||
@@ -291,6 +294,26 @@ def single(check):
|
||||
)
|
||||
|
||||
|
||||
def outage(check):
|
||||
before = oracle("--grace", str(GRACE))
|
||||
compose("stop", "s3")
|
||||
try:
|
||||
cmd = ["docker", "compose", "run", "--rm", "--no-deps", "-T", "reconciler", "--apply"]
|
||||
code, out, err, wall = run([*cmd, *FLAGS])
|
||||
finally:
|
||||
compose("up", "-d", "--wait", "--no-deps", "s3")
|
||||
after = oracle("--grace", str(GRACE))
|
||||
log = [line for line in err.splitlines() if "reconcile." in line]
|
||||
same = all(after[k] == before[k] for k in ("objects", "rows", "counts"))
|
||||
save("s3-down.json", {"exit_code": code, "wall_seconds": wall, "stdout": out, "log": log})
|
||||
check(
|
||||
"S3 остановлен: код 1 за ограниченное время, состояние не изменилось",
|
||||
code == 1 and wall < 30 and not out.strip() and same,
|
||||
exit_code=code,
|
||||
wall_seconds=wall,
|
||||
)
|
||||
|
||||
|
||||
def uploader(base, token, chat, *, deadline, results, lock):
|
||||
host = urlsplit(base).netloc
|
||||
conn = http.client.HTTPConnection(host, timeout=30)
|
||||
@@ -416,6 +439,7 @@ def demo(args):
|
||||
result = {"started_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "commit": head()}
|
||||
result["faults"] = faults(c, check, pre)
|
||||
single(check)
|
||||
outage(check)
|
||||
under_load(c, check, args.base_url, args.load_seconds, args.load_threads)
|
||||
result.update(seconds=round(time.monotonic() - started, 1), checks=check.items, ok=check.ok)
|
||||
save("demo.json", result)
|
||||
@@ -436,6 +460,15 @@ def pins(args):
|
||||
)
|
||||
|
||||
|
||||
def cpu_set(env):
|
||||
cpus = set()
|
||||
for name in ("S3_CPUSET", "PG_CPUSET", "RECONCILE_CPUSET"):
|
||||
for part in filter(None, env.get(name, "").split(",")):
|
||||
low, _, high = part.partition("-")
|
||||
cpus.update(range(int(low), int(high or low) + 1))
|
||||
return cpus
|
||||
|
||||
|
||||
def limits():
|
||||
ids = compose("ps", "-q", "s3", "postgres").split()
|
||||
fmt = (
|
||||
@@ -445,6 +478,83 @@ def limits():
|
||||
return must(["docker", "inspect", "-f", fmt, *ids]).strip().splitlines()
|
||||
|
||||
|
||||
def host(title):
|
||||
stats = must(
|
||||
[
|
||||
"docker",
|
||||
"stats",
|
||||
"--no-stream",
|
||||
"--all",
|
||||
"--format",
|
||||
"table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.PIDs}}",
|
||||
]
|
||||
)
|
||||
running = must(["docker", "ps", "--format", "{{.Names}} {{.Image}} {{.Status}}"])
|
||||
stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
load = " ".join(f"{v:.2f}" for v in os.getloadavg())
|
||||
return (
|
||||
f"== {title} date: {stamp} commit: {head()} host loadavg: {load}\n"
|
||||
f"$ docker stats --no-stream --all\n{stats}\n$ docker ps\n{running}\n"
|
||||
)
|
||||
|
||||
|
||||
def usage(text):
|
||||
return int(re.search(r"^usage_usec (\d+)$", text, re.M).group(1)) / 1e6
|
||||
|
||||
|
||||
def sample():
|
||||
vm = compose(
|
||||
"exec", "-T", "postgres", "cat", "/proc/uptime", "/proc/stat", "/sys/fs/cgroup/cpu.stat"
|
||||
)
|
||||
s3 = compose("exec", "-T", "s3", "cat", "/sys/fs/cgroup/cpu.stat")
|
||||
busy = {}
|
||||
for line in vm.splitlines()[1:]:
|
||||
name, *values = line.split() or [""]
|
||||
if name.startswith("cpu") and name[3:].isdigit():
|
||||
busy[int(name[3:])] = sum(int(values[i]) for i in BUSY) / USER_HZ
|
||||
return float(vm.split()[0]), busy, usage(vm) + usage(s3)
|
||||
|
||||
|
||||
def screen(first, last, own, pinned, args, *, started=True):
|
||||
window = max(last[0] - first[0], 0.01)
|
||||
busy = {cpu: spent - first[1].get(cpu, 0.0) for cpu, spent in last[1].items()}
|
||||
ours = last[2] - first[2] + own
|
||||
other = sum(busy.values()) - ours - args.start_other * started
|
||||
on_pinned = sum(busy.get(cpu, 0.0) for cpu in pinned) - ours - args.start_pinned * started
|
||||
other, on_pinned = max(0.0, other / window), max(0.0, on_pinned / window) if pinned else 0.0
|
||||
return {
|
||||
"window_seconds": round(window, 2),
|
||||
"ours_cores": round(ours / window, 2),
|
||||
"other_cores": round(other, 2),
|
||||
"other_on_pinned_cores": round(on_pinned, 2),
|
||||
"host_loadavg_1m": round(os.getloadavg()[0], 2),
|
||||
"disturbed": other > args.max_other or on_pinned > args.max_pinned,
|
||||
}
|
||||
|
||||
|
||||
def wait_quiet(args, pinned):
|
||||
deadline, calm = time.monotonic() + args.quiet_timeout, 0
|
||||
while calm < 3 and time.monotonic() < deadline:
|
||||
first = sample()
|
||||
time.sleep(5)
|
||||
quiet = screen(first, sample(), 0.0, pinned, args, started=False)
|
||||
calm = 0 if quiet["disturbed"] else calm + 1
|
||||
sys.stderr.write(f"waiting for quiet: {json.dumps(quiet)}\n")
|
||||
|
||||
|
||||
def measure(flags, env, args, pinned):
|
||||
rejected = []
|
||||
for _ in range(args.retries + 1):
|
||||
first = sample()
|
||||
report = reconcile(*flags, "--samples", "3", env=env)
|
||||
report["screen"] = screen(first, sample(), report["cost"]["cpu_seconds"], pinned, args)
|
||||
if not report["screen"]["disturbed"]:
|
||||
break
|
||||
rejected.append(report)
|
||||
wait_quiet(args, pinned)
|
||||
return report, rejected
|
||||
|
||||
|
||||
def seed(count, env):
|
||||
if count <= 0:
|
||||
return {"added": 0}
|
||||
@@ -480,7 +590,7 @@ def median(runs, path):
|
||||
return statistics.median(values)
|
||||
|
||||
|
||||
def summarize(results):
|
||||
def summarize(results, rejected):
|
||||
rows = []
|
||||
for (n, mode), runs in sorted(results.items()):
|
||||
seconds = median(runs, ("cost", "seconds"))
|
||||
@@ -493,10 +603,17 @@ def summarize(results):
|
||||
"seconds_all": [r["cost"]["seconds"] for r in runs],
|
||||
"wall_seconds_median": median(runs, ("wall_seconds",)),
|
||||
"us_per_object": round(seconds / n * 1e6, 1),
|
||||
"cpu_seconds_median": median(runs, ("cost", "cpu_seconds")),
|
||||
"s3_list_wait_median": median(runs, ("cost", "waited_seconds", "s3_list")),
|
||||
"sql_wait_median": median(runs, ("cost", "waited_seconds", "sql")),
|
||||
"requests": runs[0]["cost"]["requests"],
|
||||
"max_rss_mib_median": median(runs, ("cost", "max_rss_mib")),
|
||||
"other_cores_max": max(r["screen"]["other_cores"] for r in runs),
|
||||
"other_on_pinned_cores_max": max(
|
||||
r["screen"]["other_on_pinned_cores"] for r in runs
|
||||
),
|
||||
"disturbed_kept": sum(r["screen"]["disturbed"] for r in runs),
|
||||
"rejected": rejected.get((n, mode), 0),
|
||||
"scanned": runs[0]["scanned"],
|
||||
"found_nonzero": {k: v for k, v in runs[0]["found"].items() if v},
|
||||
}
|
||||
@@ -506,8 +623,8 @@ def summarize(results):
|
||||
|
||||
def table(rows):
|
||||
head = (
|
||||
"objects mode runs t_med,s wall,s us/obj list,s sql,s lists sqls gets"
|
||||
" rss,MiB"
|
||||
"objects mode runs t_med,s wall,s us/obj cpu,s list,s sql,s lists sqls"
|
||||
" gets rss,MiB other pinned rejected"
|
||||
)
|
||||
lines = [head]
|
||||
for r in rows:
|
||||
@@ -515,8 +632,10 @@ def table(rows):
|
||||
lines.append(
|
||||
f"{r['objects']:>7} {r['mode']:<9} {r['runs']:>4} {r['seconds_median']:>7.3f} "
|
||||
f"{r['wall_seconds_median']:>6.2f} {r['us_per_object']:>6.1f} "
|
||||
f"{r['s3_list_wait_median']:>6.3f} {r['sql_wait_median']:>5.3f} {q['s3_list']:>5} "
|
||||
f"{q['sql']:>4} {q['s3_get']:>4} {r['max_rss_mib_median']:>7.1f}"
|
||||
f"{r['cpu_seconds_median']:>5.2f} {r['s3_list_wait_median']:>6.3f} "
|
||||
f"{r['sql_wait_median']:>5.3f} {q['s3_list']:>5} {q['sql']:>4} {q['s3_get']:>5} "
|
||||
f"{r['max_rss_mib_median']:>7.1f} {r['other_cores_max']:>5.2f} "
|
||||
f"{r['other_on_pinned_cores_max']:>6.2f} {r['rejected']:>8}"
|
||||
)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
@@ -524,31 +643,27 @@ def table(rows):
|
||||
def cost(args):
|
||||
out = OUT / "cost"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
stats = must(
|
||||
[
|
||||
"docker",
|
||||
"stats",
|
||||
"--no-stream",
|
||||
"--all",
|
||||
"--format",
|
||||
"table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.PIDs}}",
|
||||
]
|
||||
)
|
||||
snapshot = f"date: {stamp}\n$ docker stats --no-stream --all\n{stats}"
|
||||
(out / "host-docker-stats.txt").write_text(snapshot)
|
||||
rows = int(psql("SELECT count(*) FROM attachments"))
|
||||
if rows > args.sizes[0]:
|
||||
raise SystemExit(f"на стенде уже {rows} вложений: make reset-data && make up && make test")
|
||||
snapshot = out / "host-docker-stats.txt"
|
||||
snapshot.write_text(host("before the series"))
|
||||
env = pins(args)
|
||||
pinned = cpu_set(env)
|
||||
compose("up", "-d", "--wait", "--no-deps", "s3", "postgres", env=env)
|
||||
stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
plan = {"date": stamp, "commit": head(), "pins": env, "limits": limits(), "seeds": []}
|
||||
results = {}
|
||||
plan["screen"] = {
|
||||
"max_other_cores": args.max_other,
|
||||
"max_other_on_pinned_cores": args.max_pinned,
|
||||
}
|
||||
results, rejected = {}, {}
|
||||
try:
|
||||
for n in args.sizes:
|
||||
plan["seeds"].append(dict(seed(n - rows, env), target=n))
|
||||
rows = n
|
||||
time.sleep(args.settle)
|
||||
wait_quiet(args, pinned)
|
||||
modes = [("shallow", ["--dry-run"])]
|
||||
if n <= args.deep_max:
|
||||
modes.append(("deep", ["--dry-run", "--deep"]))
|
||||
@@ -556,15 +671,23 @@ def cost(args):
|
||||
modes.append(("page100", ["--dry-run", "--page-size", "100"]))
|
||||
for mode, flags in modes:
|
||||
for attempt in range(1, args.repeats + 1):
|
||||
report = reconcile(*flags, "--samples", "3", env=env)
|
||||
(out / f"n{n}-{mode}-{attempt}.json").write_text(json.dumps(report, indent=2))
|
||||
report, dropped = measure(flags, env, args, pinned)
|
||||
name = f"n{n}-{mode}-{attempt}"
|
||||
for number, bad in enumerate(dropped, 1):
|
||||
save(f"cost/disturbed/{name}-try{number}.json", bad)
|
||||
rejected[(n, mode)] = rejected.get((n, mode), 0) + len(dropped)
|
||||
(out / f"{name}.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
results.setdefault((n, mode), []).append(report)
|
||||
sys.stderr.write(f"{n} {mode} #{attempt}: {report['cost']['seconds']} s\n")
|
||||
sys.stderr.write(f"{name}: {report['cost']['seconds']} s {report['screen']}\n")
|
||||
finally:
|
||||
compose("up", "-d", "--wait", "--no-deps", "s3", "postgres")
|
||||
summary = summarize(results)
|
||||
with snapshot.open("a") as handle:
|
||||
handle.write("\n" + host("after the series"))
|
||||
summary = summarize(results, rejected)
|
||||
save("cost/summary.json", {**plan, "results": summary})
|
||||
(out / "summary.txt").write_text(f"date: {stamp} pins: {env}\n" + table(summary))
|
||||
(out / "summary.txt").write_text(
|
||||
f"date: {stamp} commit: {plan['commit']} pins: {env}\n" + table(summary)
|
||||
)
|
||||
sys.stdout.write(table(summary))
|
||||
|
||||
|
||||
@@ -583,6 +706,12 @@ def main():
|
||||
k.add_argument("--settle", type=float, default=10)
|
||||
k.add_argument("--s3-memory", default="3g")
|
||||
k.add_argument("--no-pin", action="store_true")
|
||||
k.add_argument("--max-other", type=float, default=2.0, help="foreign CPU in the VM, cores")
|
||||
k.add_argument("--max-pinned", type=float, default=0.25, help="foreign CPU on pinned cores")
|
||||
k.add_argument("--start-other", type=float, default=1.5, help="container start, core-s")
|
||||
k.add_argument("--start-pinned", type=float, default=0.5, help="the same on pinned cores")
|
||||
k.add_argument("--retries", type=int, default=3, help="reruns of a disturbed run")
|
||||
k.add_argument("--quiet-timeout", type=float, default=900.0)
|
||||
args = p.parse_args()
|
||||
if args.command == "demo":
|
||||
demo(args)
|
||||
|
||||
Reference in New Issue
Block a user