Перенесите реализацию ЛР 4 на стенд ЛР 5

This commit is contained in:
2026-11-18 15:33:31 +03:00
parent 276dbdad8a
commit 911d97a77a
153 changed files with 17451 additions and 1 deletions
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
# Lists the API containers: <id> <name> <state> <X-Instance-Id> <image>. The
# alias is random per process, so each running replica is asked over
# /health/live, in parallel: the failover hook must return within 10 seconds.
set -eu
cd "$(dirname "$0")/.."
ids=$(docker compose ps -aq api)
[ -n "$ids" ] || exit 0
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
docker inspect --format '{{.Id}} {{.Name}} {{.State.Status}} {{.Image}}' $ids >"$tmp/containers"
while read -r id name state image; do
if [ "$state" = running ]; then
# wget prints the response headers on stderr; the body is dropped.
(docker exec "$id" wget -S -q -O - http://127.0.0.1:8080/health/live 2>&1 >/dev/null |
sed -n 's/^ *[Xx]-[Ii]nstance-[Ii]d: *//p' | tr -d '\r' | head -n 1 >"$tmp/$id") &
fi
done <"$tmp/containers"
wait
while read -r id name state image; do
alias=-
if [ -s "$tmp/$id" ]; then
alias=$(cat "$tmp/$id")
fi
image=${image#sha256:}
printf '%s %s %s %s %s\n' "$(printf '%s' "$id" | cut -c1-12)" "${name#/}" "$state" "$alias" "$(printf '%s' "$image" | cut -c1-12)"
done <"$tmp/containers"
+56
View File
@@ -0,0 +1,56 @@
#!/bin/sh
# Level 4: one replica stopped (SIGTERM) or killed (SIGKILL) at FAULT_AT and
# started again at RESTORE_AT, under a constant write load that retries
# uncertain sends with the same key; then every confirmed message must be in
# the history once.
#
# sh scripts/bench/failover.sh stop|kill <replica number, 1-based>
#
# Environment: RATE (50), DURATION (60s), FAULT_AT (15), RESTORE_AT (35), OUT
# (evidence/failover). Times come from the Docker VM clock; the Windows clock
# differs by a fraction of a second and is kept for reference only.
set -eu
cd "$(dirname "$0")/../.."
. scripts/bench/lib.sh
kind=${1:?usage: failover.sh stop|kill <replica number>}
n=${2:?usage: failover.sh stop|kill <replica number>}
case "$kind" in stop | kill) ;; *) echo "kind must be stop or kill" >&2; exit 2 ;; esac
rate=${RATE:-50}
duration=${DURATION:-60s}
fault_at=${FAULT_AT:-15}
restore_at=${RESTORE_AT:-35}
dir=${OUT:-evidence/failover}/$kind-$n
export MSYS_NO_PATHCONV=1
rm -rf "$dir"
mkdir -p "$dir"
docker compose up -d --wait >/dev/null 2>&1
target=$(docker compose ps -q api | sed -n "${n}p")
[ -n "$target" ] || { echo "no running replica number $n" >&2; exit 2; }
alias=$(sh scripts/api-instances.sh | awk -v id="$(printf '%s' "$target" | cut -c1-12)" '$1 == id { print $4 }')
meta "$dir/meta.json" "experiment=failover" "kind=$kind" "replica=$n" "rate=$rate" "duration=$duration" \
"fault_at_s=$fault_at" "restore_at_s=$restore_at"
sh scripts/instances.sh >"$dir/instances-before.txt"
# A margin for the host clock, which may run ahead of the VM's.
since=$(date -u -d '-10 seconds' +%Y-%m-%dT%H:%M:%SZ)
BENCH_OUT=$(abspath "$dir") docker compose --profile bench run --rm loadgen timeline \
-rate "$rate" -duration "$duration" >"$dir/loadgen.log" 2>&1 &
generator=$!
sleep "$fault_at"
fault_host=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
docker "$kind" "$target" >/dev/null
exited=$(docker inspect --format '{{.State.FinishedAt}}' "$target")
sleep $((restore_at - fault_at))
restore_host=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
docker compose start api >/dev/null 2>&1
started=$(docker inspect --format '{{.State.StartedAt}}' "$target")
wait "$generator" || echo "generator reported a failed history check, see $dir/loadgen.log"
printf '{\n "kind": "%s",\n "container": "%s",\n "x_instance_id": "%s",\n "process_exited_vm_utc": "%s",\n "restarted_vm_utc": "%s",\n "fault_command_host_utc": "%s",\n "restore_command_host_utc": "%s"\n}\n' \
"$kind" "$(printf '%s' "$target" | cut -c1-12)" "$alias" "$exited" "$started" "$fault_host" "$restore_host" >"$dir/faults.json"
docker compose logs --no-color --timestamps --since "$since" lb api >"$dir/compose.log" 2>&1
sh scripts/instances.sh >"$dir/instances-after.txt"
cat "$dir/loadgen.log" | tail -n 1
echo "results in $dir"
+77
View File
@@ -0,0 +1,77 @@
# Shared helpers of the experiment scripts; sourced, not run.
# The generator and the knobs the experiments vary live in compose.bench.yaml.
export COMPOSE_PATH_SEPARATOR=: COMPOSE_FILE=compose.yaml:compose.bench.yaml
# The balancer logs errors and state changes only, not every request.
export LB_QUIET=1
# abspath prints a directory in the form the Docker CLI mounts (a Windows path
# under Git Bash).
abspath() {
(cd "$1" && (pwd -W 2>/dev/null || pwd))
}
# meta writes what ran, when, on which commit and host: file, then key=value.
meta() {
file=$1
shift
{
printf '{\n'
printf ' "date_utc": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
printf ' "commit": "%s",\n' "$(git rev-parse --short HEAD)"
printf ' "branch": "%s",\n' "$(git branch --show-current)"
printf ' "docker": "%s",\n' "$(docker version --format '{{.Server.Version}}')"
printf ' "host_cpus": "%s",\n' "$(docker info --format '{{.NCPU}}')"
printf ' "host_memory_bytes": "%s",\n' "$(docker info --format '{{.MemTotal}}')"
for pair in "$@"; do
printf ' "%s": "%s",\n' "${pair%%=*}" "${pair#*=}"
done
printf ' "go": "%s"\n' "$(go env GOVERSION 2>/dev/null || echo unknown)"
printf '}\n'
} >"$file"
}
# host_probe prints the seconds a fixed CPU loop takes in a one-CPU container:
# the same work every time, so a slow spell of the host shows in the results.
host_probe() {
docker run --rm --cpus 1 --entrypoint sh mtusi-messenger:lab5 \
-c 'time -p awk "BEGIN{for(i=0;i<5000000;i++)s+=i}"' 2>&1 | awk '/^real/ { print $2 }'
}
# state_log keeps from `compose logs` (stdin) what explains a run: the
# balancer's server state changes and the replicas' start and stop. An
# overloaded run logs every failed request, gigabytes over a series; those
# lines are only counted.
state_log() {
awk '/is DOWN|is UP|UP\/READY|maintenance|"msg":"(starting|shutdown started|shutdown completed)"/ { print; next }
{ dropped++ } END { printf "# %d other lines dropped\n", dropped }'
}
# sample_docker_stats appends the CPU and memory of every container until killed.
sample_docker_stats() {
while :; do
docker stats --no-stream --format "{\"t\":$(date +%s),\"name\":\"{{.Name}}\",\"cpu\":\"{{.CPUPerc}}\",\"mem\":\"{{.MemUsage}}\"}" \
$(docker ps -q --filter label=com.docker.compose.project=lab5) 2>/dev/null || true
done >>"$1"
}
# sample_postgres appends, every second, the database counters and what the
# active sessions wait for ("cpu": nothing).
sample_postgres() {
while :; do
docker compose exec -T postgres psql -U messenger -d messenger -XAtq -c "
SELECT json_build_object(
't', extract(epoch FROM now()),
'xact_commit', xact_commit, 'xact_rollback', xact_rollback,
'tup_inserted', tup_inserted, 'blks_read', blks_read, 'blks_hit', blks_hit,
'sessions', sessions, 'sessions_abandoned', sessions_abandoned,
'active', (SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND backend_type = 'client backend' AND pid <> pg_backend_pid()),
'waits', (SELECT coalesce(json_object_agg(w, n), '{}') FROM (
SELECT coalesce(wait_event_type || ':' || wait_event, 'cpu') AS w, count(*) AS n
FROM pg_stat_activity
WHERE state = 'active' AND backend_type = 'client backend' AND pid <> pg_backend_pid()
GROUP BY 1) AS x))
FROM pg_stat_database WHERE datname = 'messenger'" 2>/dev/null || true
sleep 1
done >>"$1"
}
+336
View File
@@ -0,0 +1,336 @@
#!/usr/bin/env python3
"""Tables and charts of track 1 from the raw results of run-series.sh.
python scripts/bench/plot.py <raw root> <output dir>
The raw root holds <series>/<config>/rep<k>/ directories. Written to the
output directory:
summary.csv one row per step of every run;
capacity.csv the capacity of every run and the median per configuration;
control.csv the noise checks of every run, the host speed probe and the
loadgen CPU per request at the first step, each flagged when
more than 25 % off its median;
cost.csv CPU milliseconds per request of each component at the
COST_RATES steps (valid, error-free, unflagged runs only), and
the rate one database CPU would serve at that cost;
<series>-throughput.png, <series>-p99.png, capacity.png,
cpu-at-capacity.png, pool-waits.png, cost-per-request.png.
Capacity is the highest step that passed the criterion loadgen applies (valid,
under 1 % errors, p99 of successful requests within 500 ms). Charts show the
median of the repeats; a hollow marker means the generator fell behind.
"""
import csv
import gzip
import json
import pathlib
import statistics
import sys
from datetime import datetime
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
SLO_P99_MS = 500.0
CONTROL_TOLERANCE = 0.25
# Below saturation in every configuration, so the cost is not inflated by
# queueing.
COST_RATES = (800, 1000)
COMPONENTS = ("api", "lb", "postgres", "valkey", "loadgen")
def read_jsonl(path):
packed = path.with_name(path.name + ".gz")
if packed.exists():
text = gzip.decompress(packed.read_bytes()).decode("utf-8")
elif path.exists():
text = path.read_text(encoding="utf-8")
else:
return []
rows = []
for line in text.splitlines():
line = line.strip()
if line:
try:
rows.append(json.loads(line))
except json.JSONDecodeError:
pass
return rows
def component(name):
for c in COMPONENTS:
if f"-{c}-" in name:
return c
return None
def parse_time(value):
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
def load_runs(root):
runs = []
for steps_path in sorted(root.glob("*/*/rep*/steps.json")):
d = steps_path.parent
report = json.loads(steps_path.read_text(encoding="utf-8"))
runs.append({
"series": d.parent.parent.name,
"config": d.parent.name,
"rep": d.name,
"start": parse_time(report["started_at"]),
"steps": report["steps"],
"docker": read_jsonl(d / "docker-stats.jsonl"),
"metrics": read_jsonl(d / "metrics.jsonl"),
"meta": json.loads((d / "meta.json").read_text(encoding="utf-8")) if (d / "meta.json").exists() else {},
})
return runs
def mean_cpu(run, t0, t1):
"""Mean CPU per component in [t0, t1); replicas of the API are summed."""
per_time = {}
for row in run["docker"]:
c = component(row.get("name", ""))
if c is None or not t0 <= row["t"] < t1:
continue
try:
cpu = float(row["cpu"].rstrip("%"))
except (ValueError, KeyError):
continue
per_time.setdefault(row["t"], {}).setdefault(c, 0.0)
per_time[row["t"]][c] += cpu
out = {}
for c in COMPONENTS:
values = [v[c] for v in per_time.values() if c in v]
out[c] = round(statistics.mean(values), 1) if values else ""
return out
def pool_rate(run, t0, t1, counter):
"""Growth of a pgxpool counter during [t0, t1), all replicas, per second."""
first, last = {}, {}
for row in run["metrics"]:
t = run["start"] + row["t"]
if not t0 <= t < t1:
continue
for replica in row.get("replicas") or []:
pool = replica.get("pgxpool") or {}
key = replica.get("instance")
if key and counter in pool:
first.setdefault(key, pool[counter])
last[key] = pool[counter]
if not last:
return ""
return round(sum(last[k] - first[k] for k in last) / max(t1 - t0, 1e-9), 1)
def main(root, out):
runs = load_runs(root)
if not runs:
sys.exit(f"no runs under {root}")
out.mkdir(parents=True, exist_ok=True)
rows, capacities = [], []
for run in runs:
best = None
for step in run["steps"]:
t0 = run["start"] + step["started_at_s"]
t1 = t0 + step["seconds"]
cpu = mean_cpu(run, t0, t1)
classes = step["classes"]
row = {
"series": run["series"], "config": run["config"], "rep": run["rep"],
"offered_rps": step["offered_rps"], "ok_rps": round(step["ok_rps"], 1),
"error_share": round(step["error_share"], 4), "ok_p50_ms": step["ok_p50_ms"],
"ok_p95_ms": step["ok_p95_ms"], "ok_p99_ms": step["ok_p99_ms"],
"lag_p99_ms": step["lag_p99_ms"], "valid": step["valid"], "passed": step["passed"],
"client_timeouts": classes.get("client_timeout", 0),
"lb_errors": sum(n for c, n in classes.items() if c.endswith("_lb")),
"api_errors": sum(n for c, n in classes.items() if c.startswith("http_") and not c.endswith("_lb")),
**{f"cpu_{c}_pct": cpu[c] for c in COMPONENTS},
"pool_waits_per_s": pool_rate(run, t0, t1, "empty_acquire_count"),
"new_conns_per_s": pool_rate(run, t0, t1, "new_conns_count"),
}
rows.append(row)
if step["passed"] and (best is None or step["offered_rps"] > best["offered_rps"]):
best = row
capacities.append({
"series": run["series"], "config": run["config"], "rep": run["rep"],
"capacity_rps": best["offered_rps"] if best else 0, "at": best,
"invalid_below": sum(1 for s in run["steps"] if not s["valid"] and (best is None or s["offered_rps"] < best["offered_rps"])),
})
with open(out / "summary.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
configs = []
for c in capacities:
if (c["series"], c["config"]) not in configs:
configs.append((c["series"], c["config"]))
with open(out / "capacity.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["series", "config", "capacity_rps_per_repeat", "capacity_rps_median", "invalid_steps_below_capacity"])
medians = {}
for key in configs:
mine = [c for c in capacities if (c["series"], c["config"]) == key]
values = [c["capacity_rps"] for c in mine]
medians[key] = statistics.median(values)
w.writerow([key[0], key[1], " ".join(f"{v:g}" for v in values), f"{medians[key]:g}",
sum(c["invalid_below"] for c in mine)])
control = []
for run in runs:
first = [r for r in rows if (r["series"], r["config"], r["rep"]) == (run["series"], run["config"], run["rep"])][:1]
if first and first[0]["cpu_loadgen_pct"] != "":
probe = run["meta"].get("host_probe_s", "")
control.append([run["series"], run["config"], run["rep"], float(probe) if probe else None,
round(float(first[0]["cpu_loadgen_pct"]) * 10000 / first[0]["offered_rps"])])
if control:
probes = [c[3] for c in control if c[3] is not None]
probe_median = statistics.median(probes) if probes else None
cpu_median = statistics.median(c[4] for c in control)
with open(out / "control.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["series", "config", "rep", "host_probe_s", "probe_deviation",
"loadgen_cpu_ms_per_1000_requests", "cpu_deviation", "flagged"])
flagged = set()
for series, config, rep, probe, cpu in control:
probe_dev = probe / probe_median - 1 if probe is not None else 0.0
cpu_dev = cpu / cpu_median - 1
noisy = max(abs(probe_dev), abs(cpu_dev)) > CONTROL_TOLERANCE
if noisy:
flagged.add((series, config, rep))
w.writerow([series, config, rep, probe if probe is not None else "", f"{probe_dev:+.2f}", cpu,
f"{cpu_dev:+.2f}", noisy])
cost = {}
for r in rows:
if (r["series"], r["config"], r["rep"]) in flagged or r["offered_rps"] not in COST_RATES:
continue
if not r["valid"] or r["error_share"] > 0:
continue
per = cost.setdefault((r["series"], r["config"]), {"runs": set()})
per["runs"].add(r["rep"])
for c in ("api", "postgres", "lb"):
if r[f"cpu_{c}_pct"] != "":
per.setdefault(c, []).append(float(r[f"cpu_{c}_pct"]) * 10 / r["offered_rps"])
with open(out / "cost.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["series", "config", "runs", "api_cpu_ms_per_request", "postgres_cpu_ms_per_request",
"lb_cpu_ms_per_request", "rps_per_database_cpu"])
for (series, config), per in cost.items():
med = {c: statistics.median(per[c]) for c in ("api", "postgres", "lb") if per.get(c)}
w.writerow([series, config, " ".join(sorted(per["runs"])),
*(round(med[c], 2) if c in med else "" for c in ("api", "postgres", "lb")),
round(1000 / med["postgres"]) if med.get("postgres") else ""])
if cost:
keys = list(cost)
fig, ax = plt.subplots(figsize=(max(6, len(keys) * 0.9), 4.5))
width = 0.27
for i, c in enumerate(("api", "postgres", "lb")):
ax.bar([j + i * width for j in range(len(keys))],
[statistics.median(cost[k][c]) if cost[k].get(c) else 0 for k in keys], width, label=c)
ax.set_xticks([j + width for j in range(len(keys))], [f"{s_}/{c_}" for s_, c_ in keys], rotation=30)
ax.set_ylabel("CPU ms per request")
ax.set_title(f"Cost per request at {'/'.join(map(str, COST_RATES))} rps (clean runs)")
ax.grid(axis="y", alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(out / "cost-per-request.png", dpi=120)
plt.close(fig)
def median_by_offered(series, config, field):
points, valid = {}, {}
for r in rows:
if r["series"] == series and r["config"] == config and r[field] != "":
points.setdefault(r["offered_rps"], []).append(float(r[field]))
valid[r["offered_rps"]] = valid.get(r["offered_rps"], True) and r["valid"]
xs = sorted(points)
return xs, [statistics.median(points[x]) for x in xs], [valid[x] for x in xs]
for series in sorted({s for s, _ in configs}):
names = [c for s, c in configs if s == series]
for field, title, filename, log in (
("ok_rps", "Successful requests per second", "throughput", False),
("ok_p99_ms", "p99 of successful requests, ms", "p99", True),
):
fig, ax = plt.subplots(figsize=(7, 4.5))
top = 0
for name in names:
xs, ys, valid = median_by_offered(series, name, field)
line, = ax.plot(xs, ys, label=name)
ax.scatter([x for x, v in zip(xs, valid) if v], [y for y, v in zip(ys, valid) if v], color=line.get_color())
ax.scatter([x for x, v in zip(xs, valid) if not v], [y for y, v in zip(ys, valid) if not v],
facecolors="none", edgecolors=line.get_color())
top = max([top, *xs])
if field == "ok_rps" and top:
ax.plot([0, top], [0, top], linestyle=":", color="grey", label="offered")
if field == "ok_p99_ms":
ax.axhline(SLO_P99_MS, linestyle="--", color="grey", label="500 ms")
if log:
ax.set_yscale("log")
ax.set_xlabel("Offered requests per second")
ax.set_ylabel(title)
ax.set_title(f"Series {series}: median of repeats (hollow: generator fell behind)")
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(out / f"{series}-{filename}.png", dpi=120)
plt.close(fig)
labels = [f"{s}/{c}" for s, c in configs]
fig, ax = plt.subplots(figsize=(max(6, len(labels) * 0.9), 4.5))
meds = [medians[k] for k in configs]
lows = [medians[k] - min(c["capacity_rps"] for c in capacities if (c["series"], c["config"]) == k) for k in configs]
highs = [max(c["capacity_rps"] for c in capacities if (c["series"], c["config"]) == k) - medians[k] for k in configs]
ax.bar(labels, meds, yerr=[lows, highs], capsize=4, color="#4c78a8")
ax.set_ylabel("Capacity, requests per second")
ax.set_title("Capacity per configuration (median, range of repeats)")
ax.tick_params(axis="x", rotation=30)
ax.grid(axis="y", alpha=0.3)
fig.tight_layout()
fig.savefig(out / "capacity.png", dpi=120)
plt.close(fig)
fig, ax = plt.subplots(figsize=(max(6, len(labels) * 1.1), 4.5))
width = 0.8 / len(COMPONENTS)
for i, comp in enumerate(COMPONENTS):
values = []
for key in configs:
at = [c["at"] for c in capacities if (c["series"], c["config"]) == key and c["at"]]
cpu = [float(a[f"cpu_{comp}_pct"]) for a in at if a[f"cpu_{comp}_pct"] != ""]
values.append(statistics.median(cpu) if cpu else 0)
ax.bar([j + i * width for j in range(len(configs))], values, width, label=comp)
ax.set_xticks([j + 0.4 - width / 2 for j in range(len(configs))], labels, rotation=30)
ax.set_ylabel("Mean CPU at capacity, % of one core")
ax.set_title("Which component is busy at capacity")
ax.grid(axis="y", alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(out / "cpu-at-capacity.png", dpi=120)
plt.close(fig)
fig, ax = plt.subplots(figsize=(7, 4.5))
for series, name in configs:
xs, ys, _ = median_by_offered(series, name, "pool_waits_per_s")
if xs:
ax.plot(xs, ys, marker="o", label=f"{series}/{name}")
ax.set_xlabel("Offered requests per second")
ax.set_ylabel("Waits for a pooled connection per second")
ax.set_title("Connection pool waits, all replicas")
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(out / "pool-waits.png", dpi=120)
plt.close(fig)
print(f"{len(runs)} runs, {len(rows)} steps -> {out}")
if __name__ == "__main__":
if len(sys.argv) != 3:
sys.exit(__doc__)
main(pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]))
+50
View File
@@ -0,0 +1,50 @@
#!/bin/sh
# Level 4: scripts/rollout.sh replaces every replica at UPDATE_AT under a
# constant write load that retries uncertain sends with the same key; then
# every confirmed message must be in the history once.
#
# sh scripts/bench/rollout-under-load.sh
#
# Environment: RATE (50), DURATION (60s), UPDATE_AT (15), OUT (evidence/rollout).
# Times come from the Docker VM clock, as in failover.sh.
set -eu
cd "$(dirname "$0")/../.."
. scripts/bench/lib.sh
rate=${RATE:-50}
duration=${DURATION:-60s}
update_at=${UPDATE_AT:-15}
dir=${OUT:-evidence/rollout}
export MSYS_NO_PATHCONV=1
rm -rf "$dir"
mkdir -p "$dir"
docker compose up -d --wait >/dev/null 2>&1
# Built beforehand, as by a delivery pipeline: the update replaces replicas.
docker compose build api >/dev/null 2>&1
meta "$dir/meta.json" "experiment=rolling-update" "rate=$rate" "duration=$duration" "update_at_s=$update_at"
sh scripts/instances.sh >"$dir/instances-before.txt"
# A margin for the host clock, which may run ahead of the VM's.
since=$(date -u -d '-10 seconds' +%Y-%m-%dT%H:%M:%SZ)
old=$(docker compose ps -q api | cut -c1-12 | tr '\n' ' ')
BENCH_OUT=$(abspath "$dir") docker compose --profile bench run --rm loadgen timeline \
-rate "$rate" -duration "$duration" >"$dir/loadgen.log" 2>&1 &
generator=$!
sleep "$update_at"
started_host=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
status=0
sh scripts/rollout.sh >"$dir/rollout.log" 2>&1 || status=$?
finished_host=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
wait "$generator" || echo "generator reported a failed history check, see $dir/loadgen.log"
new=""
for id in $(docker compose ps -q api); do
new="$new{\"container\": \"$(printf '%s' "$id" | cut -c1-12)\", \"started_vm_utc\": \"$(docker inspect --format '{{.State.StartedAt}}' "$id")\"}, "
done
printf '{\n "rollout_exit_code": %s,\n "old_containers": "%s",\n "new_containers": [%s],\n "command_started_host_utc": "%s",\n "command_finished_host_utc": "%s"\n}\n' \
"$status" "$old" "${new%, }" "$started_host" "$finished_host" >"$dir/update.json"
docker compose logs --no-color --timestamps --since "$since" lb api migrate >"$dir/compose.log" 2>&1
sh scripts/instances.sh >"$dir/instances-after.txt"
cat "$dir/loadgen.log" | tail -n 1
echo "results in $dir"
+88
View File
@@ -0,0 +1,88 @@
#!/bin/sh
# Track 1: every configuration of the given series files, each on a fresh
# stand, under one grid of offered rates. Repeats are interleaved (repeat 1
# of every configuration, then repeat 2), so a slow spell of the host does not
# fall on one configuration.
#
# RATES=400,800,1200 sh scripts/bench/run-series.sh scripts/bench/series/A.conf [...]
#
# Environment: RATES (required), REPEATS (3), STEP (30s), WARMUP (30s),
# STOP_ON_FAIL (1: end a ladder at its first failing step), OUT
# (evidence/track1/raw). Results: <OUT>/<series>/<config>/rep<k>/.
set -eu
cd "$(dirname "$0")/../.."
. scripts/bench/lib.sh
[ $# -gt 0 ] || { echo "usage: RATES=... run-series.sh <series.conf>..." >&2; exit 2; }
: "${RATES:?set RATES, the offered requests per second of the steps, e.g. 400,800,1200}"
repeats=${REPEATS:-3}
step=${STEP:-30s}
warmup=${WARMUP:-30s}
out=${OUT:-evidence/track1/raw}
stop=
[ "${STOP_ON_FAIL:-1}" = 1 ] && stop=-stop-on-fail
# Fixed for every configuration; the API, its pool, maxconn and the database
# CPU come from the series line.
export LB_CPUS=1.0 PG_MEMORY=1G LOADGEN_CPUS=2.0
export MSYS_NO_PATHCONV=1
# One series line: name replicas cpus memory gomemlimit pool maxconn pg_cpus.
run_config() {
series=$1 rep=$2 name=$3 replicas=$4 cpus=$5 memory=$6 gomemlimit=$7 pool=$8 maxconn=$9 pg_cpus=${10}
dir=$out/$series/$name/rep$rep
rm -rf "$dir"
mkdir -p "$dir"
echo "== $series/$name rep $rep: $replicas x $cpus CPU / $memory, pool $pool, maxconn $maxconn, PostgreSQL $pg_cpus CPU"
export API_REPLICAS=$replicas API_CPUS=$cpus API_MEMORY=$memory API_GOMEMLIMIT=$gomemlimit \
DB_MAX_CONNS=$pool API_MAXCONN=$maxconn PG_CPUS=$pg_cpus
docker compose down -v --remove-orphans >/dev/null 2>&1
if ! docker compose up -d --build --wait >"$dir/up.log" 2>&1; then
echo " the stand did not start, see $dir/up.log" >&2
exit 1
fi
meta "$dir/meta.json" "series=$series" "config=$name" "repeat=$rep" \
"api_replicas=$replicas" "api_cpus=$cpus" "api_memory=$memory" "gomemlimit=$gomemlimit" \
"db_max_conns=$pool" "api_maxconn=$maxconn" "pg_cpus=$pg_cpus" "pg_memory=$PG_MEMORY" \
"lb_cpus=$LB_CPUS" "loadgen_cpus=$LOADGEN_CPUS" "rates=$RATES" "step=$step" "warmup=$warmup" \
"stop_on_fail=${STOP_ON_FAIL:-1}" "host_probe_s=$(host_probe)"
sample_docker_stats "$dir/docker-stats.jsonl" &
stats=$!
sample_postgres "$dir/postgres.jsonl" &
pg=$!
# stdin closed: `compose run` would otherwise read it.
BENCH_OUT=$(abspath "$dir") docker compose --profile bench run --rm loadgen bench \
-rates "$RATES" -step "$step" -warmup "$warmup" -scrape $stop >"$dir/loadgen.log" 2>&1 </dev/null ||
echo " loadgen failed, see $dir/loadgen.log"
kill "$stats" "$pg" 2>/dev/null || true
wait "$stats" "$pg" 2>/dev/null || true
docker compose logs --no-color --timestamps lb api 2>&1 | state_log >"$dir/compose.log"
gzip -9 "$dir"/*.jsonl
grep '^step' "$dir/loadgen.log" || true
}
for conf in "$@"; do
[ -r "$conf" ] || { echo "cannot read $conf" >&2; exit 2; }
bad=$(grep -v '^#' "$conf" | awk 'NF && NF != 8')
[ -z "$bad" ] || { echo "$conf: a line needs 8 fields: $bad" >&2; exit 2; }
done
docker compose --profile bench build loadgen >/dev/null
default_ifs=$IFS
newline='
'
for rep in $(seq 1 "$repeats"); do
for conf in "$@"; do
lines=$(grep -v '^#' "$conf" | sed '/^[[:space:]]*$/d')
IFS=$newline
for line in $lines; do
IFS=$default_ifs
# shellcheck disable=SC2086 # the line splits into the fields
run_config "$(basename "$conf" .conf)" "$rep" $line
done
IFS=$default_ifs
done
done
docker compose down -v --remove-orphans >/dev/null 2>&1
echo "results in $out"
+6
View File
@@ -0,0 +1,6 @@
# Series A: the same API budget, 2 CPU and 1 GiB, cut into 1, 2 or 4 replicas;
# the pool stays 10 per replica, so the total grows with the replicas.
# name replicas cpus memory gomemlimit pool maxconn pg_cpus
A1 1 2.0 1024M 920MiB 10 0 1.0
A2 2 1.0 512M 460MiB 10 0 1.0
A4 4 0.5 256M 230MiB 10 0 1.0
+5
View File
@@ -0,0 +1,5 @@
# Series A': the budget of series A with the total pool fixed at 20 connections;
# A'2 equals A2.
# name replicas cpus memory gomemlimit pool maxconn pg_cpus
Ap1 1 2.0 1024M 920MiB 20 0 1.0
Ap4 4 0.5 256M 230MiB 5 0 1.0
+5
View File
@@ -0,0 +1,5 @@
# Series B: replicas of 1 CPU, 512 MiB and pool 10 added one by one; B2 equals A2.
# name replicas cpus memory gomemlimit pool maxconn pg_cpus
B1 1 1.0 512M 460MiB 10 0 1.0
B3 3 1.0 512M 460MiB 10 0 1.0
B4 4 1.0 512M 460MiB 10 0 1.0
+10
View File
@@ -0,0 +1,10 @@
# Improvement C: maxconn per replica on the balancer, before (0, no limit) and
# after (20) on 1 and 4 replicas, under an overload ladder (STOP_ON_FAIL=0);
# 10 and 40 show how much the value matters.
# name replicas cpus memory gomemlimit pool maxconn pg_cpus
R1m0 1 1.0 512M 460MiB 10 0 1.0
R1m20 1 1.0 512M 460MiB 10 20 1.0
R4m0 4 1.0 512M 460MiB 10 0 1.0
R4m20 4 1.0 512M 460MiB 10 20 1.0
R1m10 1 1.0 512M 460MiB 10 10 1.0
R1m40 1 1.0 512M 460MiB 10 40 1.0
+6
View File
@@ -0,0 +1,6 @@
# Control: A2 next to A2 with twice the database CPU, interleaved, run with
# STOP_ON_FAIL=0 so that one noisy step does not end a ladder. If the database
# is the bottleneck, the capacity rises.
# name replicas cpus memory gomemlimit pool maxconn pg_cpus
A2 2 1.0 512M 460MiB 10 0 1.0
A2pg2 2 1.0 512M 460MiB 10 0 2.0
+75
View File
@@ -0,0 +1,75 @@
-- EXPLAIN evidence for the message history query (make explain).
--
-- Everything runs in one transaction that is rolled back: it seeds 12 000
-- messages in one chat and 90 000 in 300 other chats, so the plan is measured
-- on a realistic volume without leaving data on the stand. The PREPARE text
-- is the statement of Messages.ListByChat in internal/chat/store/postgres.go;
-- keep them identical.
\set ON_ERROR_STOP on
\pset pager off
BEGIN;
SELECT uuidv7() AS author \gset
SELECT uuidv7() AS big_chat \gset
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (:'author', 'explain_' || substr(md5(random()::text), 1, 12), 'EXPLAIN', 'not-a-password-hash',
uuid_extract_timestamp(:'author'));
CREATE TEMP TABLE noise_chats ON COMMIT DROP AS
SELECT uuidv7() AS id FROM generate_series(1, 300);
INSERT INTO chats (id, title, created_at)
SELECT :'big_chat'::uuid, 'explain: big chat', uuid_extract_timestamp(:'big_chat')
UNION ALL
SELECT id, 'explain: other chat', uuid_extract_timestamp(id) FROM noise_chats;
INSERT INTO chat_members (chat_id, user_id)
SELECT id, :'author' FROM chats WHERE title LIKE 'explain:%';
-- Rows are inserted ordered by n, so the messages of all chats interleave in
-- the heap as they would under real traffic; ids stay increasing per chat.
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT id, chat_id, :'author', 'message ' || n, uuid_extract_timestamp(id)
FROM (
SELECT uuidv7() AS id, chat_id, n
FROM (
SELECT :'big_chat'::uuid AS chat_id, n FROM generate_series(1, 12000) AS n
UNION ALL
SELECT c.id, n FROM noise_chats AS c, generate_series(1, 300) AS n
) AS planned
ORDER BY n
) AS generated;
ANALYZE users, chats, chat_members, messages;
SELECT (SELECT count(*) FROM messages WHERE chat_id = :'big_chat') AS big_chat_messages,
(SELECT count(*) FROM messages) AS all_messages;
PREPARE history(uuid, uuid, int) AS
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
AND id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)
ORDER BY id
LIMIT $3;
\echo
\echo == First page: no cursor, limit 50 (+1 row that tells whether a next page exists)
EXPLAIN (ANALYZE, BUFFERS) EXECUTE history(:'big_chat', NULL, 51);
SELECT id AS deep_cursor FROM messages WHERE chat_id = :'big_chat' ORDER BY id OFFSET 10000 LIMIT 1 \gset
\echo
\echo == Deep page: cursor after the 10 001st message of the chat
EXPLAIN (ANALYZE, BUFFERS) EXECUTE history(:'big_chat', :'deep_cursor', 51);
\echo
\echo == For contrast, OFFSET pagination of the same page reads every skipped row
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = :'big_chat'
ORDER BY id
OFFSET 10001 LIMIT 51;
ROLLBACK;
+96
View File
@@ -0,0 +1,96 @@
#!/bin/sh
# Creates the local credentials of the compose stand in ./secrets, which git
# ignores. Existing secrets are kept: PostgreSQL applies its password only
# when the volume is first initialised, so a new password would lock the API
# out of an existing database. To start over: make destroy, then delete
# ./secrets and run this again.
set -eu
cd "$(dirname "$0")/.."
files="postgres_password database_url valkey_auth.conf session_store_url"
present=0
for f in $files; do
if [ -e "secrets/$f" ]; then
present=$((present + 1))
fi
done
if [ "$present" -ne 0 ] && [ "$present" -ne 4 ]; then
echo "./secrets is incomplete: delete it (and run make destroy if the stand holds data), then run again" >&2
exit 1
fi
# 24 random bytes as hex: URL-safe without escaping.
random() {
od -An -tx1 -N24 /dev/urandom | tr -d ' \n'
}
# The directory is private; the files stay readable for the unprivileged
# users inside the containers, which see them through bind mounts.
umask 022
mkdir -p secrets
chmod 700 secrets
if [ "$present" -eq 0 ]; then
pg=$(random)
kv=$(random)
printf '%s\n' "$pg" > secrets/postgres_password
printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable\n' "$pg" > secrets/database_url
printf 'requirepass %s\n' "$kv" > secrets/valkey_auth.conf
printf 'redis://:%s@valkey:6379/0\n' "$kv" > secrets/session_store_url
fi
# Read just the bucket setting, never execute the local .env file as a script.
bucket=${S3_BUCKET:-}
if [ -z "$bucket" ] && [ -f .env ]; then
bucket=$(sed -n 's/^S3_BUCKET=//p' .env | tail -n 1 | tr -d '\r')
fi
bucket=${bucket:-messenger-attachments}
case "$bucket" in
*[!a-z0-9.-]*|.*|*.|-*|*-|*..*|*.-*|*-.*)
echo "S3_BUCKET must be a lowercase S3 bucket name" >&2; exit 1 ;;
esac
if [ "${#bucket}" -lt 3 ] || [ "${#bucket}" -gt 63 ]; then
echo "S3_BUCKET must contain 3 to 63 characters" >&2; exit 1
fi
s3files="s3_admin_access_key_id s3_admin_secret_access_key s3_access_key_id s3_secret_access_key s3_reconcile_access_key_id s3_reconcile_secret_access_key s3_identities.json"
s3present=0
for f in $s3files; do
if [ -s "secrets/$f" ]; then s3present=$((s3present + 1)); fi
done
if [ "$s3present" -eq 7 ]; then
if ! grep -Fq "\"Read:$bucket\"" secrets/s3_identities.json; then
echo "existing S3 identities use another bucket; keep S3_BUCKET consistent with the retained volume" >&2
exit 1
fi
echo "existing PostgreSQL, Valkey and S3 secrets kept"
exit 0
fi
if [ "$s3present" -ne 0 ]; then
echo "S3 secrets are incomplete; restore the s3_* secret files together; PostgreSQL and Valkey secrets were kept" >&2
exit 1
fi
admin_key=$(random)
admin_secret=$(random)
api_key=$(random)
api_secret=$(random)
recon_key=$(random)
recon_secret=$(random)
printf '%s\n' "$admin_key" > secrets/s3_admin_access_key_id
printf '%s\n' "$admin_secret" > secrets/s3_admin_secret_access_key
printf '%s\n' "$api_key" > secrets/s3_access_key_id
printf '%s\n' "$api_secret" > secrets/s3_secret_access_key
printf '%s\n' "$recon_key" > secrets/s3_reconcile_access_key_id
printf '%s\n' "$recon_secret" > secrets/s3_reconcile_secret_access_key
# The server loads all identities before listening. There is no anonymous
# identity, and no post-start allow-all provisioning phase.
cat > secrets/s3_identities.json <<EOF
{
"identities": [
{"name":"bootstrap","credentials":[{"accessKey":"$admin_key","secretKey":"$admin_secret"}],"actions":["Admin","Read","Write","List"]},
{"name":"api","credentials":[{"accessKey":"$api_key","secretKey":"$api_secret"}],"actions":["Read:$bucket","Write:$bucket"]},
{"name":"reconciler","credentials":[{"accessKey":"$recon_key","secretKey":"$recon_secret"}],"actions":["List:$bucket","Read:$bucket","Write:$bucket"]}
]
}
EOF
echo "PostgreSQL and Valkey secrets kept or created; S3 identities created"
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# Which container answers under which X-Instance-Id.
set -eu
cd "$(dirname "$0")/.."
printf '%-12s %-14s %-8s %-16s %s\n' CONTAINER NAME STATE X-INSTANCE-ID IMAGE
sh scripts/api-instances.sh | while read -r id name state alias image; do
printf '%-12s %-14s %-8s %-16s %s\n' "$id" "$name" "$state" "$alias" "$image"
done
+209
View File
@@ -0,0 +1,209 @@
#!/usr/bin/env python3
"""File-driven decoder stress evidence. Requires rebuilt APIs with >=2 GiB limits.
Run with python -X utf8 -B. Default is one upload; no container lifecycle actions.
"""
import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import datetime as dt
import hashlib
import importlib.util
import json
from pathlib import Path
import re
import struct
import subprocess
import sys
import threading
import time
from urllib.parse import urlsplit
import zlib
sys.dont_write_bytecode = True
_spec = importlib.util.spec_from_file_location('upload_memory', Path(__file__).with_name('upload-memory.py'))
memory = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(memory)
def write_rgba64_png(path, width=40_000_000, height=1, chunk_bytes=65536):
"""Stream zero scanlines, including filter bytes; never allocate a full row."""
if min(width, height, chunk_bytes) <= 0 or width * height > 40_000_000:
raise ValueError('invalid stress dimensions or chunk size')
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
encoder = zlib.compressobj(1)
remaining = height * (width * 8 + 1)
zeros = bytes(min(chunk_bytes, remaining))
with path.open('wb') as out:
out.write(b'\x89PNG\r\n\x1a\n')
out.write(memory.png_chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 16, 6, 0, 0, 0)))
while remaining:
count = min(len(zeros), remaining)
compressed = encoder.compress(zeros[:count])
if compressed:
out.write(memory.png_chunk(b'IDAT', compressed))
remaining -= count
out.write(memory.png_chunk(b'IDAT', encoder.flush()))
out.write(memory.png_chunk(b'IEND', b''))
def fixture_info(content, mime):
if mime == 'image/png' and content.startswith(b'\x89PNG\r\n\x1a\n') and len(content) >= 33:
width, height, depth, color = struct.unpack_from('>IIBB', content, 16)
return {'width': width, 'height': height, 'bit_depth': depth, 'color_type': color}
if mime == 'image/jpeg' and content.startswith(b'\xff\xd8'):
pos = 2
while pos + 4 <= len(content):
if content[pos] != 255:
break
while pos < len(content) and content[pos] == 255:
pos += 1
marker = content[pos]
pos += 1
length = struct.unpack_from('>H', content, pos)[0]
frame = content[pos + 2:pos + length]
pos += length
if marker in (0xc0, 0xc1, 0xc2):
height, width = struct.unpack_from('>HH', frame, 1)
count = frame[5]
return {'width': width, 'height': height, 'bit_depth': frame[0], 'components': count,
'progressive': marker == 0xc2, 'sampling': [frame[7 + 3 * i] for i in range(count)]}
if length < 2 or marker == 0xda:
break
raise ValueError('fixture MIME/header mismatch or missing image header')
def read_fixture(path, mime):
if not 0 < path.stat().st_size <= 10 * 1024 * 1024:
raise ValueError('fixture must be between 1 byte and 10 MiB')
content = path.read_bytes()
info = fixture_info(content, mime)
if not 0 < info['width'] * info['height'] <= 40_000_000:
raise ValueError('fixture exceeds 40M pixels')
return content, info
def api_limits(ids):
template = '{"id":{{json .Id}},"limit_bytes":{{json .HostConfig.Memory}}}'
result = subprocess.run(['docker', 'inspect', '--format', template, *ids], stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, check=True, timeout=20)
return {row['id']: row['limit_bytes'] for row in (json.loads(line) for line in result.stdout.splitlines())}
def experiment(args, content, report):
sys.path.insert(0, str(memory.ROOT / 'tests'))
import client as module
ids = memory.api_containers(args)
report['api_limits'] = api_limits(ids)
if any(report['api_limits'].get(cid, 0) < 2 * 1024**3 for cid in ids):
raise RuntimeError('stress uploads require every API container limit to be >=2 GiB')
report['state_before'] = memory.container_states(ids)
bootstrap = module.Client(args.base_url, timeout=args.timeout)
actor, reader, _, chat = bootstrap.bootstrap()
clients = [module.Client(args.base_url, timeout=args.timeout) for _ in range(args.concurrency)]
with memory.DockerStats(ids) as stats:
stats.mark(args.label, 'baseline')
stats.wait_for_baseline(args.label)
time.sleep(args.baseline_seconds)
barrier = threading.Barrier(args.concurrency + 1)
with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
futures = [executor.submit(memory.upload, module, client, actor, chat, content, report['sha256'],
barrier, index, args.label, mime=args.mime) for index, client in enumerate(clients)]
stats.mark(args.label, 'load')
started = time.monotonic()
barrier.wait(timeout=30)
results = [future.result() for future in futures]
report['duration_s'] = time.monotonic() - started
time.sleep(args.tail_seconds)
stats.mark(args.label, 'idle')
report['memory_samples'] = stats.snapshot(args.label)
report['sampling_error'] = stats.error
report['state_after'] = memory.container_states(ids)
stable = all(report['state_after'][cid]['running'] and not report['state_after'][cid]['oom_killed']
and report['state_after'][cid]['restart_count'] == report['state_before'][cid]['restart_count'] for cid in ids)
report['restart_or_oom_detected'] = not stable
try:
report['memory'] = memory.summarize_memory(report['memory_samples'], ids)
except RuntimeError as exc:
report['memory_error'] = str(exc)
report['observed_max_inflight'] = memory.max_inflight([(r['_started'], r['_finished']) for r in results])
accepted = [r for r in results if r['ok']]
report['accepted'] = len(accepted)
report['status_counts'] = dict(Counter(str(r['status']) if r['status'] else 'transport_error' for r in results))
report['latency'] = memory.latency_summary([r['latency_ms'] for r in results])
report['attempted_bytes'], report['successful_bytes'] = len(content) * len(results), len(content) * len(accepted)
for result in results:
result['start_offset_ms'] = round((result.pop('_started') - started) * 1000, 3)
result.pop('_finished')
report['results'] = results
report['download'] = {'ok': False}
if accepted:
try:
response = bootstrap.call('GET', '/api/v1/attachments/' + accepted[0]['attachment_id'] + '/content', actor=reader)
body = response['bytes']
report['download'] = {'ok': body == content and response['headers'].get_content_type() == args.mime,
'status': response['status'], 'bytes': len(body), 'sha256': hashlib.sha256(body).hexdigest()}
except Exception as exc:
report['download']['error'] = str(exc) if isinstance(exc, module.Failure) else type(exc).__name__
report['ok'] = (len(accepted) == args.concurrency and report['download']['ok'] and stable
and not report.get('memory_error') and not report['sampling_error']
and report['observed_max_inflight'] == args.concurrency)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--file', type=Path)
parser.add_argument('--mime', choices=('image/png', 'image/jpeg'))
parser.add_argument('--label', default='decoder')
parser.add_argument('--concurrency', type=int, default=1, help='1-10, default single-upload acceptance')
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--compose-file', type=Path, default=memory.ROOT / 'compose.yaml')
parser.add_argument('--project-name')
parser.add_argument('--timeout', type=float, default=45)
parser.add_argument('--baseline-seconds', type=float, default=3)
parser.add_argument('--tail-seconds', type=float, default=3)
parser.add_argument('--output', type=Path)
parser.add_argument('--check-file', action='store_true', help='inspect bytes/header without HTTP or Docker')
parser.add_argument('--generate-wide', type=Path, help='generate 40Mx1 RGBA64 PNG offline using bounded zlib input')
args = parser.parse_args()
if args.generate_wide:
write_rgba64_png(args.generate_wide)
content, info = read_fixture(args.generate_wide, 'image/png')
print(json.dumps({**info, 'bytes': len(content), 'sha256': hashlib.sha256(content).hexdigest()}))
return 0
if not args.file or not args.mime:
parser.error('--file and --mime are required')
if not 1 <= args.concurrency <= 10 or args.timeout <= 0 or args.baseline_seconds < 1 or args.tail_seconds < 2:
parser.error('require concurrency1-10, timeout>0, baseline>=1s, tail>=2s')
if not re.fullmatch(r'[A-Za-z0-9_-]{1,40}', args.label):
parser.error('label must be 1-40 safe ASCII characters')
url = urlsplit(args.base_url)
if url.scheme not in ('http', 'https') or not url.hostname or url.username or url.password or url.query or url.fragment:
parser.error('base URL must be HTTP(S) without credentials/query/fragment')
content, info = read_fixture(args.file, args.mime)
report = {'schema_version': 1, 'name': args.label, 'mime': args.mime, 'fixture': info,
'payload_bytes': len(content), 'sha256': hashlib.sha256(content).hexdigest(),
'requests': args.concurrency, 'ok': False, 'started_at': dt.datetime.now(dt.timezone.utc).isoformat(),
'measurement': {'source': 'docker stats JSON stream, formatted working-set values',
'limitation': 'sampled/rounded peaks can miss instantaneous maxima',
'baseline_seconds': args.baseline_seconds, 'tail_seconds': args.tail_seconds}}
if args.check_file:
print(json.dumps(report, indent=2))
return 0
if not args.output:
parser.error('--output is required for a live run')
try:
experiment(args, content, report)
except Exception as exc:
report['error'] = type(exc).__name__
if isinstance(exc, RuntimeError) or type(exc).__name__ == 'Failure':
report['failure'] = str(exc)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print(json.dumps({key: value for key, value in report.items() if key not in ('memory_samples', 'results')}))
return 0 if report['ok'] else 1
if __name__ == '__main__':
raise SystemExit(main())
+95
View File
@@ -0,0 +1,95 @@
"""Stop each actual uploader replica and verify its bytes through the survivor."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
def instances():
text = subprocess.check_output(['sh', 'scripts/api-instances.sh'], cwd=ROOT,
encoding='utf-8')
result = []
for line in text.splitlines():
container, replica, state, alias, image = line.split()
result.append({'container': container, 'replica': replica,
'state': state, 'alias': alias, 'image': image})
return result
def restore(c):
subprocess.run(['docker', 'compose', 'start', 'api'], cwd=ROOT,
check=True, stdout=subprocess.DEVNULL)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
observed = {c.call('GET', '/health/live')['headers']['X-Instance-Id']
for _ in range(6)}
if len(observed) >= 2:
return
time.sleep(0.3)
raise AssertionError('two replicas did not return after restore')
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--base-url', default='http://localhost:8080')
p.add_argument('--output', type=Path, default=ROOT / 'evidence/failover-uploaders.json')
args = p.parse_args()
c = Client(args.base_url, timeout=10)
actor, reader, _, chat = c.bootstrap()
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
wanted = instances()
check(len(wanted) == 2 and all(x['state'] == 'running' for x in wanted),
'this experiment requires two running API replicas')
report = {'scenario': 'stop actual upload-serving replica; download via survivor',
'cases': [], 'ok': False}
try:
for target in wanted:
upload = None
for _ in range(10):
attempt = c.call('POST', '/api/v1/chats/' + chat['id'] +
'/attachments?filename=sample.png', 201,
actor=actor, raw=data,
headers={'Content-Type': 'image/png'}, schema='Attachment')
if attempt['headers']['X-Instance-Id'] == target['alias']:
upload = attempt
break
check(upload is not None, 'target replica did not serve an upload')
before = instances()
env = dict(os.environ, TARGET_INSTANCE_ID=target['alias'])
started = time.monotonic()
subprocess.run(['sh', 'scripts/stop-one.sh'], cwd=ROOT, env=env,
check=True, stdout=subprocess.DEVNULL, timeout=15)
stop_seconds = time.monotonic() - started
downloaded = c.call('GET', '/api/v1/attachments/' +
upload['json']['id'] + '/content', actor=reader)
survivor = downloaded['headers']['X-Instance-Id']
check(survivor != target['alias'], 'stopped uploader still served download')
check(downloaded['bytes'] == data, 'bytes changed after uploader stop')
after = instances()
check(any(x['container'] == target['container'] and x['state'] != 'running'
for x in after), 'uploader was not left stopped')
report['cases'].append({'uploader': target, 'download_instance': survivor,
'stop_seconds': round(stop_seconds, 3),
'sha256': hashlib.sha256(downloaded['bytes']).hexdigest(),
'same_bytes': True, 'before': before, 'after': after})
restore(c)
report['ok'] = True
finally:
# This script only restores the API containers that it deliberately stopped.
restore(c)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print(json.dumps({'ok': report['ok'], 'cases': len(report['cases']),
'output': str(args.output)}))
if __name__ == '__main__':
main()
+45
View File
@@ -0,0 +1,45 @@
"""Generate optional 40 MP regression images; requires Pillow==11.1.0."""
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import sys
sys.dont_write_bytecode = True
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output-dir', type=Path, default=Path('bin/decoder-fixtures'))
args = parser.parse_args()
try:
from PIL import Image
except ImportError:
parser.error('install optional fixture dependency: pip install Pillow==11.1.0')
spec = importlib.util.spec_from_file_location('decoder_memory',
Path(__file__).with_name('decoder-memory.py'))
decoder = importlib.util.module_from_spec(spec)
spec.loader.exec_module(decoder)
args.output_dir.mkdir(parents=True, exist_ok=True)
manifest = {'pillow_version': Image.__version__, 'fixtures': []}
for mode, color in [('RGB', (25, 90, 160)), ('CMYK', (20, 40, 60, 10))]:
path = args.output_dir / ('progressive-' + mode.lower() + '-444-40mp.jpg')
with Image.new(mode, (8000, 5000), color) as image:
image.save(path, format='JPEG', progressive=True, subsampling=0, quality=85)
content, info = decoder.read_fixture(path, 'image/jpeg')
if not info['progressive'] or any(value != 0x11 for value in info['sampling']):
raise ValueError('encoder did not produce progressive 4:4:4')
manifest['fixtures'].append({'name': path.name, 'mime': 'image/jpeg', **info,
'bytes': len(content), 'sha256': hashlib.sha256(content).hexdigest()})
wide = args.output_dir / 'wide-rgba64-40mp.png'
decoder.write_rgba64_png(wide)
content, info = decoder.read_fixture(wide, 'image/png')
manifest['fixtures'].append({'name': wide.name, 'mime': 'image/png', **info,
'bytes': len(content), 'sha256': hashlib.sha256(content).hexdigest()})
(args.output_dir / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
print(json.dumps(manifest, indent=2))
if __name__ == '__main__':
main()
+55
View File
@@ -0,0 +1,55 @@
"""Offline checks for bounded stress fixtures and format identification."""
import importlib.util
from pathlib import Path
import struct
import tempfile
import unittest
import zlib
class DecoderMemoryTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
path = Path(__file__).with_name('decoder-memory.py')
cls.module = None
if path.exists():
spec = importlib.util.spec_from_file_location('decoder_memory', path)
cls.module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(cls.module)
def setUp(self):
self.assertIsNotNone(self.module, 'decoder-memory.py is not implemented')
def test_streamed_rgba64_png_has_valid_crc_and_zero_pixels(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'wide.png'
self.module.write_rgba64_png(path, width=19, height=3, chunk_bytes=7)
payload = path.read_bytes()
self.assertEqual(payload[:8], b'\x89PNG\r\n\x1a\n')
pos, compressed = 8, bytearray()
while pos < len(payload):
size = struct.unpack_from('>I', payload, pos)[0]
kind, body = payload[pos + 4:pos + 8], payload[pos + 8:pos + 8 + size]
self.assertEqual(struct.unpack_from('>I', payload, pos + 8 + size)[0], zlib.crc32(kind + body) & 0xffffffff)
if kind == b'IDAT':
compressed.extend(body)
pos += size + 12
self.assertEqual(zlib.decompress(compressed), bytes(3 * (19 * 8 + 1)))
self.assertEqual(self.module.fixture_info(payload, 'image/png'),
{'width': 19, 'height': 3, 'bit_depth': 16, 'color_type': 6})
def test_progressive_jpeg_444_components_are_identified(self):
sof = b'\x08' + struct.pack('>HHB', 5000, 8000, 3) + bytes([1, 0x11, 0, 2, 0x11, 0, 3, 0x11, 0])
payload = b'\xff\xd8\xff\xc2' + struct.pack('>H', len(sof) + 2) + sof
info = self.module.fixture_info(payload, 'image/jpeg')
self.assertEqual((info['width'], info['height'], info['components']), (8000, 5000, 3))
self.assertTrue(info['progressive'])
self.assertEqual(info['sampling'], [0x11, 0x11, 0x11])
def test_fixture_byte_cap_is_checked_before_reading(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'oversized.png'
with path.open('wb') as out:
out.truncate(10 * 1024 * 1024 + 1)
with self.assertRaises(ValueError):
self.module.read_fixture(path, 'image/png')
+139
View File
@@ -0,0 +1,139 @@
"""Offline checks for reproducible PNGs and Docker memory evidence."""
import importlib.util
import json
from pathlib import Path
import struct
import unittest
from types import SimpleNamespace
import io
import zlib
class UploadMemoryTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
spec = importlib.util.spec_from_file_location('upload_memory', Path(__file__).with_name('upload-memory.py'))
cls.module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(cls.module)
def inspect_png(self, payload, width, height):
self.assertEqual(payload[:8], b'\x89PNG\r\n\x1a\n')
pos, chunks, compressed = 8, [], bytearray()
while pos < len(payload):
size = struct.unpack_from('>I', payload, pos)[0]
kind = payload[pos + 4:pos + 8]
data = payload[pos + 8:pos + 8 + size]
crc = struct.unpack_from('>I', payload, pos + 8 + size)[0]
self.assertEqual(crc, zlib.crc32(kind + data) & 0xffffffff)
if kind == b'IHDR':
self.assertEqual(struct.unpack('>IIBBBBB', data), (width, height, 8, 2, 0, 0, 0))
if kind == b'IDAT':
compressed.extend(data)
chunks.append(kind)
pos += size + 12
self.assertEqual(pos, len(payload))
self.assertEqual(chunks[0], b'IHDR')
self.assertEqual(chunks[-1], b'IEND')
self.assertIn(b'npAD', chunks)
rows = zlib.decompress(compressed)
self.assertEqual(len(rows), height * (width * 3 + 1))
self.assertTrue(all(rows[row * (width * 3 + 1)] == 0 for row in range(height)))
def test_seeded_png_has_correct_crc_pixels_and_exact_size(self):
first = self.module.make_png(32, 24, 4096, 123)
self.assertEqual(len(first), 4096)
self.assertEqual(first, self.module.make_png(32, 24, 4096, 123))
self.assertNotEqual(first, self.module.make_png(32, 24, 4096, 124))
self.inspect_png(first, 32, 24)
def test_both_experiment_payloads_decode_and_reach_exact_limits(self):
for name, width, height, size, seed in self.module.CASES:
with self.subTest(name=name):
payload = self.module.make_png(width, height, size, seed)
self.assertEqual(len(payload), size)
self.assertLessEqual(len(payload), 10 * 1024 * 1024)
self.assertLessEqual(width * height, 40_000_000)
self.inspect_png(payload, width, height)
def test_impossible_png_size_is_rejected(self):
with self.assertRaises(ValueError):
self.module.make_png(32, 32, 64, 1)
def test_docker_memory_uses_binary_and_decimal_units(self):
for raw, expected in [('1.5MiB / 512MiB', 1572864), ('2MB / 512MB', 2000000), ('4096B / 1GiB', 4096)]:
self.assertEqual(self.module.memory_bytes(raw), expected)
with self.assertRaises(ValueError):
self.module.memory_bytes('not available')
def test_memory_summary_separates_baseline_and_load_for_each_replica(self):
samples = [
{'container_id': 'a', 'phase': 'baseline', 'used_bytes': 10},
{'container_id': 'b', 'phase': 'baseline', 'used_bytes': 20},
{'container_id': 'a', 'phase': 'baseline', 'used_bytes': 12},
{'container_id': 'a', 'phase': 'load', 'used_bytes': 35},
{'container_id': 'a', 'phase': 'load', 'used_bytes': 30},
{'container_id': 'b', 'phase': 'load', 'used_bytes': 50},
]
result = self.module.summarize_memory(samples, ['a', 'b'])
self.assertEqual(result['a']['baseline_bytes'], 12)
self.assertEqual(result['a']['sampled_peak_bytes'], 35)
self.assertEqual(result['a']['delta_bytes'], 23)
self.assertEqual(result['b']['sampled_peak_bytes'], 50)
with self.assertRaises(RuntimeError):
self.module.summarize_memory(samples, ['a', 'b', 'missing'])
def test_latency_percentiles_and_overlap_are_explicit(self):
self.assertEqual(self.module.latency_summary(list(range(1, 11))),
{'p50_ms': 5.5, 'p95_ms': 10, 'max_ms': 10})
self.assertEqual(self.module.max_inflight([(0, 4), (1, 3), (2, 5)]), 3)
self.assertEqual(self.module.max_inflight([(0, 1), (1, 2)]), 1)
def test_docker_stream_ignores_ansi_only_lines_between_samples(self):
cid = 'a' * 64
row = json.dumps({'ID': cid, 'Name': 'lab4-api-1', 'MemUsage': '12MiB / 512MiB'})
stats = self.module.DockerStats([cid])
stats.process = SimpleNamespace(stdout=iter(['\x1b[H' + row + '\n', ' \x1b[K\n', row + '\n']))
stats.mark('small', 'baseline')
stats._read()
self.assertIsNone(stats.error)
self.assertEqual(len(stats.samples), 2)
def test_rgba64_profile_has_valid_header_crc_and_zero_scanlines(self):
payload = self.module.make_rgba64_png(8, 5)
pos, compressed = 8, bytearray()
while pos < len(payload):
size = struct.unpack_from('>I', payload, pos)[0]
kind, data = payload[pos + 4:pos + 8], payload[pos + 8:pos + 8 + size]
self.assertEqual(struct.unpack_from('>I', payload, pos + 8 + size)[0], zlib.crc32(kind + data) & 0xffffffff)
if kind == b'IHDR':
self.assertEqual(struct.unpack('>IIBBBBB', data), (8, 5, 16, 6, 0, 0, 0))
if kind == b'IDAT':
compressed.extend(data)
pos += size + 12
self.assertEqual(zlib.decompress(compressed), bytes(5 * (1 + 8 * 8)))
self.assertEqual(pos, len(payload))
def test_max_pixels_profile_fits_byte_limit_without_full_raw_buffer(self):
payload = self.module.make_rgba64_png(8000, 5000)
self.assertLess(len(payload), 10 * 1024 * 1024)
self.assertEqual(struct.unpack_from('>IIBB', payload, 16), (8000, 5000, 16, 6))
def test_upload_uses_requested_jpeg_mime(self):
captured = []
class Opener:
def open(self, request, timeout):
captured.append(request)
response = io.BytesIO(b'')
response.code, response.headers = 415, {}
return response
client = SimpleNamespace(base='http://localhost', opener=Opener(), timeout=1)
import threading
result = self.module.upload(None, client, {'token': 'synthetic'}, {'id': 'chat'}, b'jpeg', 'hash',
threading.Barrier(1), 0, 'decoder', mime='image/jpeg')
self.assertEqual(captured[0].get_header('Content-type'), 'image/jpeg')
self.assertTrue(captured[0].full_url.endswith('decoder-0.jpg'))
self.assertEqual(result['status'], 415)
if __name__ == '__main__':
unittest.main()
+376
View File
@@ -0,0 +1,376 @@
#!/usr/bin/env python3
"""Concurrent upload experiment; stdlib only, no stand lifecycle operations."""
import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import datetime as dt
import hashlib
import json
import math
import os
from pathlib import Path
import platform
import random
import re
import statistics
import struct
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
from urllib.parse import urlsplit
import zlib
ROOT = Path(__file__).resolve().parents[2]
sys.dont_write_bytecode = True
CASES = (
('small', 512, 512, 1024 * 1024, 41),
('limit', 1600, 1600, 10 * 1024 * 1024, 42),
)
MAXPIXEL_CASE = ('maxpixels', 8000, 5000, None, None)
def png_chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff)
def make_png(width, height, size, seed):
rng = random.Random(seed)
rows = b''.join(b'\0' + rng.randbytes(width * 3) for _ in range(height))
header = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
prefix = b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', header) + png_chunk(b'IDAT', zlib.compress(rows, 1))
ending = png_chunk(b'IEND', b'')
gap = size - len(prefix) - len(ending)
if gap < 0 or 0 < gap < 12:
raise ValueError('target cannot contain this PNG')
# Ancillary, private, reserved bit valid: unknown npAD is safely ignored.
padding = png_chunk(b'npAD', bytes(gap - 12)) if gap else b''
return prefix + padding + ending
def make_rgba64_png(width, height):
encoder = zlib.compressobj(1)
row = bytes(1 + width * 8)
pieces = [encoder.compress(row) for _ in range(height)]
pieces.append(encoder.flush())
header = struct.pack('>IIBBBBB', width, height, 16, 6, 0, 0, 0)
return (b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', header)
+ png_chunk(b'IDAT', b''.join(pieces)) + png_chunk(b'IEND', b''))
def payload_for(case):
name, width, height, size, seed = case
return make_rgba64_png(width, height) if name == 'maxpixels' else make_png(width, height, size, seed)
def memory_bytes(value):
match = re.fullmatch(r'([0-9]+(?:\.[0-9]+)?)\s*(B|kB|KB|KiB|MB|MiB|GB|GiB|TB|TiB)', value.split('/')[0].strip())
if not match:
raise ValueError('unrecognized docker memory value')
units = {'B': 1, 'kB': 1000, 'KB': 1000, 'KiB': 1024, 'MB': 1000**2, 'MiB': 1024**2,
'GB': 1000**3, 'GiB': 1024**3, 'TB': 1000**4, 'TiB': 1024**4}
return round(float(match[1]) * units[match[2]])
def summarize_memory(samples, container_ids):
result = {}
for container_id in container_ids:
baseline = [s for s in samples if s['container_id'] == container_id and s['phase'] == 'baseline']
load = [s for s in samples if s['container_id'] == container_id and s['phase'] == 'load']
if not baseline or not load:
raise RuntimeError('missing baseline or load sample for an API replica')
before, peak = baseline[-1]['used_bytes'], max(s['used_bytes'] for s in load)
result[container_id] = {'baseline_bytes': before, 'sampled_peak_bytes': peak, 'delta_bytes': peak - before,
'baseline_samples': len(baseline), 'load_samples': len(load)}
return result
def latency_summary(values):
ordered = sorted(values)
return {'p50_ms': statistics.median(ordered), 'p95_ms': ordered[math.ceil(len(ordered) * .95) - 1],
'max_ms': ordered[-1]}
def max_inflight(intervals):
active, peak = 0, 0
events = [(start, 1) for start, _ in intervals] + [(end, -1) for _, end in intervals]
for _, delta in sorted(events):
active += delta
peak = max(peak, active)
return peak
class DockerStats:
def __init__(self, container_ids):
self.ids = container_ids
self.samples = []
self.lock = threading.Condition()
self.case, self.phase = '', 'idle'
self.error = None
self.started = time.monotonic()
def __enter__(self):
self.process = subprocess.Popen(['docker', 'stats', '--no-trunc', '--format', '{{json .}}', *self.ids],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
text=True, encoding='utf-8', errors='replace', bufsize=1)
self.thread = threading.Thread(target=self._read, daemon=True)
self.thread.start()
return self
def _read(self):
for line in self.process.stdout:
try:
cleaned = re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', line).strip()
if not cleaned:
continue
raw = json.loads(cleaned)
reported_id = raw.get('ID') or raw.get('Container', '')
container_id = next(cid for cid in self.ids if cid.startswith(reported_id) or reported_id.startswith(cid))
used = memory_bytes(raw['MemUsage'])
limit = memory_bytes(raw['MemUsage'].split('/')[1])
if used == 0:
continue
with self.lock:
self.samples.append({'container_id': container_id, 'name': raw['Name'], 'used_bytes': used,
'limit_bytes': limit, 'elapsed_s': round(time.monotonic() - self.started, 6),
'case': self.case, 'phase': self.phase})
self.lock.notify_all()
except (ValueError, KeyError, IndexError, StopIteration) as exc:
with self.lock:
self.error = 'invalid_docker_stats_sample:' + type(exc).__name__ + ':' + repr(line[:120])
self.lock.notify_all()
with self.lock:
self.lock.notify_all()
def mark(self, case, phase):
with self.lock:
self.case, self.phase = case, phase
def snapshot(self, case):
with self.lock:
return [dict(s) for s in self.samples if s['case'] == case]
def wait_for_baseline(self, case, timeout=20):
deadline = time.monotonic() + timeout
with self.lock:
while True:
seen = {s['container_id'] for s in self.samples if s['case'] == case and s['phase'] == 'baseline'}
if seen == set(self.ids):
return
if self.error or self.process.poll() is not None or time.monotonic() >= deadline:
raise RuntimeError('docker stats baseline unavailable')
self.lock.wait(min(.1, max(0, deadline - time.monotonic())))
def __exit__(self, *_):
if self.process.poll() is None:
self.process.terminate()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait(timeout=5)
self.thread.join(timeout=5)
self.process.stdout.close()
def api_containers(args):
command = ['docker', 'compose', '--project-directory', str(ROOT), '-f', str(args.compose_file)]
if args.project_name:
command.extend(['--project-name', args.project_name])
result = subprocess.run(command + ['ps', '--status', 'running', '-q', 'api'], cwd=ROOT,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, check=True, timeout=20)
ids = result.stdout.split()
if not ids or any(not re.fullmatch(r'[a-f0-9]{12,64}', cid) for cid in ids):
raise RuntimeError('compose has no running API containers')
return ids
def container_states(container_ids):
template = ('{"id":{{json .Id}},"oom_killed":{{json .State.OOMKilled}},'
'"running":{{json .State.Running}},"restart_count":{{json .RestartCount}},'
'"exit_code":{{json .State.ExitCode}}}')
result = subprocess.run(['docker', 'inspect', '--format', template, *container_ids],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, check=True, timeout=20)
return {state['id']: state for state in (json.loads(line) for line in result.stdout.splitlines())}
def upload(client_module, client, actor, chat, content, checksum, barrier, index, case, mime='image/png'):
result = {'index': index, 'status': None, 'ok': False, 'request_bytes': len(content)}
barrier.wait(timeout=30)
started = time.monotonic()
try:
suffix = '.jpg' if mime == 'image/jpeg' else '.png'
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + case + '-' + str(index) + suffix
req = urllib.request.Request(client.base + path, data=content, method='POST', headers={
'Authorization': 'Bearer ' + actor['token'], 'Content-Type': mime,
'Content-Length': str(len(content)), 'Accept': 'application/json'})
try:
response = client.opener.open(req, timeout=client.timeout)
except urllib.error.HTTPError as exc:
response = exc
with response:
result['status'] = response.code
result['instance_id'] = response.headers.get('X-Instance-Id')
body = response.read(65537)
if result['status'] != 201:
result['error'] = 'http_error'
elif len(body) > 65536:
result['error'] = 'oversized_metadata'
else:
attachment = json.loads(body)
client_module.shape(attachment, 'Attachment')
valid = (attachment['sha256'] == checksum and attachment['size_bytes'] == len(content)
and attachment['status'] == 'ready' and attachment['owner_id'] == actor['id']
and attachment['chat_id'] == chat['id'])
result['ok'] = valid
result['attachment_id'] = attachment['id']
if not valid:
result['error'] = 'attachment_metadata_mismatch'
except Exception as exc:
# Exception text and response bodies are deliberately excluded from evidence.
result['error'] = type(exc).__name__
finished = time.monotonic()
result.update(_started=started, _finished=finished, latency_ms=round((finished - started) * 1000, 3))
return result
def run_case(module, bootstrap_client, actor, reader, chat, stats, args, case):
name, width, height, size, seed = case
content = payload_for(case)
size = len(content)
checksum = hashlib.sha256(content).hexdigest()
clients = [module.Client(args.base_url, timeout=args.timeout) for _ in range(args.concurrency)]
state_before = container_states(stats.ids)
stats.mark(name, 'baseline')
stats.wait_for_baseline(name)
time.sleep(args.baseline_seconds)
barrier = threading.Barrier(args.concurrency + 1)
with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
futures = [executor.submit(upload, module, client, actor, chat, content, checksum, barrier, index, name)
for index, client in enumerate(clients)]
stats.mark(name, 'load')
started = time.monotonic()
barrier.wait(timeout=30)
results = [future.result() for future in futures]
duration = time.monotonic() - started
# Retain a tail because docker stats reports its own sampled windows.
time.sleep(args.tail_seconds)
stats.mark(name, 'idle')
samples = stats.snapshot(name)
memory_error = None
try:
memory = summarize_memory(samples, stats.ids)
except RuntimeError as exc:
memory, memory_error = {}, str(exc)
intervals = [(r['_started'], r['_finished']) for r in results]
peak_requests = max_inflight(intervals)
successes = [r for r in results if r['ok']]
download = {'ok': False}
if successes:
try:
response = bootstrap_client.call('GET', '/api/v1/attachments/' + successes[0]['attachment_id'] + '/content', actor=reader)
downloaded = response['bytes']
download = {'ok': downloaded == content and response['headers'].get_content_type() == 'image/png',
'bytes': len(downloaded), 'sha256': hashlib.sha256(downloaded).hexdigest(),
'status': response['status']}
except Exception as exc:
download['error'] = type(exc).__name__
distinct = len({r['attachment_id'] for r in successes})
state_after = container_states(stats.ids)
stable = all(state_after[cid]['running'] and not state_after[cid]['oom_killed']
and state_after[cid]['restart_count'] == state_before[cid]['restart_count'] for cid in stats.ids)
for result in results:
result['start_offset_ms'] = round((result.pop('_started') - started) * 1000, 3)
result.pop('_finished')
return {'name': name, 'width': width, 'height': height, 'seed': seed, 'payload_bytes': size, 'sha256': checksum,
'bit_depth': 16 if name == 'maxpixels' else 8, 'color_type': 6 if name == 'maxpixels' else 2,
'nominal_decoded_bytes': width * height * (8 if name == 'maxpixels' else 4),
'requests': args.concurrency, 'attempted_bytes': size * args.concurrency,
'successful_bytes': size * len(successes), 'accepted': len(successes),
'status_counts': dict(Counter(str(r['status']) if r['status'] else 'transport_error' for r in results)),
'errors': len(results) - len(successes), 'duration_s': round(duration, 6),
'observed_max_inflight': peak_requests, 'distinct_attachment_ids': distinct,
'latency': latency_summary([r['latency_ms'] for r in results]), 'memory': memory,
'memory_samples': samples, 'memory_error': memory_error, 'results': results, 'download': download,
'state_before': state_before, 'state_after': state_after, 'restart_or_oom_detected': not stable,
'ok': (len(successes) == args.concurrency and distinct == args.concurrency and peak_requests >= 10
and download['ok'] and not memory_error and stable)}
def main():
parser = argparse.ArgumentParser(description=__doc__, epilog='On Windows, run python -X utf8 -B to match tests/client.py contract-file encoding.')
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--compose-file', type=Path, default=ROOT / 'compose.yaml')
parser.add_argument('--project-name', default=None)
parser.add_argument('--output', type=Path, help='write sanitized JSON evidence here')
parser.add_argument('--profile', choices=('standard', 'maxpixels'), default='standard',
help='standard: 1/10 MiB; maxpixels: 8000x5000 RGBA64 (320 MB decoded)')
parser.add_argument('--concurrency', type=int, default=10, help='simultaneous uploads per case, 10-100 (default 10)')
parser.add_argument('--timeout', type=float, default=45)
parser.add_argument('--baseline-seconds', type=float, default=3)
parser.add_argument('--tail-seconds', type=float, default=3)
parser.add_argument('--check-generator', action='store_true', help='check payload construction only; no HTTP or Docker')
args = parser.parse_args()
selected_cases = CASES if args.profile == 'standard' else (MAXPIXEL_CASE,)
if args.check_generator:
print(json.dumps([{'case': name, 'width': width, 'height': height, 'bytes': len(payload),
'sha256': hashlib.sha256(payload).hexdigest()}
for name, width, height, size, seed in selected_cases
for payload in [payload_for((name, width, height, size, seed))]], indent=2))
return 0
if not args.output:
parser.error('--output is required for live execution')
if not 10 <= args.concurrency <= 100 or args.timeout <= 0 or args.baseline_seconds < 1 or args.tail_seconds < 2:
parser.error('require concurrency 10-100, timeout > 0, baseline >= 1 s and tail >= 2 s')
target = urlsplit(args.base_url)
if target.scheme not in ('http', 'https') or not target.hostname or target.username or target.password or target.query or target.fragment:
parser.error('--base-url must be HTTP(S) without credentials, query or fragment')
report = {'schema_version': 1, 'started_at': dt.datetime.now(dt.timezone.utc).isoformat(), 'ok': False,
'driver': {'os': platform.system(), 'architecture': platform.machine(),
'logical_cpus': os.cpu_count(), 'python': platform.python_version()},
'measurement': {'source': 'docker stats JSON stream', 'cadence': 'Docker-managed, typically about 1 second',
'limitation': 'sampled peaks may miss sub-second maxima; includes post-upload sampling tail',
'memory_semantics': 'Docker CLI memory usage (working set, cache excluded where supported)',
'baseline_seconds': args.baseline_seconds, 'tail_seconds': args.tail_seconds,
'same_bytes_per_case': True, 'p95_method': 'nearest rank',
'profile': args.profile,
'png_compression': ('zlib level 1; random RGB; npAD padding to exact byte limit' if args.profile == 'standard'
else 'streamed zero RGBA64 scanlines; no full decoded buffer in driver')}, 'cases': []}
try:
sys.path.insert(0, str(ROOT / 'tests'))
import client as client_module
ids = api_containers(args)
report['api_container_ids'] = ids
bootstrap_client = client_module.Client(args.base_url, timeout=args.timeout)
report['stage'] = 'bootstrap'
actor, reader, _, chat = bootstrap_client.bootstrap()
with DockerStats(ids) as stats:
for case in selected_cases:
report['stage'] = case[0]
report['cases'].append(run_case(client_module, bootstrap_client, actor, reader, chat, stats, args, case))
if stats.error:
report['sampling_error'] = stats.error
report['ok'] = all(case['ok'] for case in report['cases']) and len(report['cases']) == len(selected_cases) and not stats.error
report['stage'] = 'complete'
except Exception as exc:
report['error'] = type(exc).__name__
if isinstance(exc, RuntimeError) or ('client_module' in locals() and isinstance(exc, client_module.Failure)):
# Public helper diagnostics contain only paths/schema names, never values or credentials.
report['failure'] = str(exc)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print(json.dumps({'ok': report['ok'], 'output': str(args.output),
'cases': [{'case': c['name'], 'accepted': c['accepted'], 'requests': c['requests'],
'observed_max_inflight': c['observed_max_inflight'], 'latency': c['latency'],
'memory': c['memory'], 'download_ok': c['download']['ok']} for c in report['cases']],
'error': report.get('error')}))
return 0 if report['ok'] else 1
if __name__ == '__main__':
raise SystemExit(main())
+5
View File
@@ -0,0 +1,5 @@
@echo off
rem Windows entry point of scripts/restart.sh: tests/resilience.py starts the
rem hook without a shell, and Windows cannot execute a .sh file directly.
sh "%~dp0restart.sh"
exit /b %errorlevel%
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# Restart hook of `make test-persistence`: stops the whole stand gracefully and
# starts the same containers again; volumes are kept.
set -eu
cd "$(dirname "$0")/.."
docker compose stop
# Re-run one-shot jobs against the retained data before restoring replicas.
docker compose up -d --wait postgres valkey s3
docker compose run --rm migrate
docker compose run --rm s3-init
docker compose up -d --wait
sh scripts/wait-ready.sh
+44
View File
@@ -0,0 +1,44 @@
#!/bin/sh
# Rolling update of the API with docker rollout (github.com/wowu/docker-rollout,
# MIT): new replicas start next to the old ones, and the old ones go once all
# new ones are healthy; if one is not, the new ones are removed instead.
#
# With a stopped replica docker rollout would replace only that one and leave
# two versions running, so the script refuses. The migrate container is
# recreated from the new image without starting: the `up` of docker rollout
# then applies the new migrations once, before any new replica starts.
set -eu
cd "$(dirname "$0")/.."
idle=$(docker compose ps -aq --status exited --status created --status paused --status dead api)
if [ -n "$idle" ]; then
echo "some API replicas are not running; start them first: docker compose start api" >&2
exit 2
fi
version=v0.14
checksum=cdeaba6ae9eee3b0b606286e585bbda6787283d801a6ad6d9b9d2bc347fda05b
tool=bin/docker-rollout
if ! printf '%s %s\n' "$checksum" "$tool" | sha256sum -c - >/dev/null 2>&1; then
mkdir -p bin
curl -fsSL -o "$tool.download" "https://github.com/wowu/docker-rollout/releases/download/$version/docker-rollout"
if ! printf '%s %s\n' "$checksum" "$tool.download" | sha256sum -c - >/dev/null 2>&1; then
rm -f "$tool.download"
echo "docker-rollout $version: checksum mismatch, not used" >&2
exit 1
fi
mv "$tool.download" "$tool"
fi
docker compose build api
docker compose up --no-start --no-deps --force-recreate migrate
# Run through sh: Windows cannot use the script as a docker CLI plugin.
if ! sh "$tool" rollout --wait-after-healthy 4 api; then
# A failed migration leaves the new containers created but not started.
created=$(docker compose ps -aq --status created api)
if [ -n "$created" ]; then
docker rm $created >/dev/null
fi
exit 1
fi
+5
View File
@@ -0,0 +1,5 @@
@echo off
rem Windows entry point of scripts/stop-one.sh: tests/resilience.py starts the
rem hook without a shell, and Windows cannot execute a .sh file directly.
sh "%~dp0stop-one.sh"
exit /b %errorlevel%
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
# Failover hook of `make test-failover`: gracefully stops the one running API
# replica whose X-Instance-Id is $TARGET_INSTANCE_ID, and nothing else.
# Restore it with: docker compose start api
set -eu
cd "$(dirname "$0")/.."
target=${TARGET_INSTANCE_ID:-}
case "$target" in
'' | *[!0-9a-f]*)
echo "TARGET_INSTANCE_ID must be the 16 lowercase hex characters of an X-Instance-Id" >&2
exit 2
;;
esac
if [ ${#target} -ne 16 ]; then
echo "TARGET_INSTANCE_ID must be the 16 lowercase hex characters of an X-Instance-Id" >&2
exit 2
fi
matches=$(sh scripts/api-instances.sh | awk -v t="$target" '$3 == "running" && $4 == t { print $1 }')
count=$(printf '%s\n' "$matches" | grep -c . || true)
if [ "$count" -ne 1 ]; then
echo "expected one running API replica with X-Instance-Id $target, found $count" >&2
exit 2
fi
docker stop "$matches" >/dev/null
echo "stopped API container $matches (X-Instance-Id $target)"
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# Compose may retain the balancer's earlier healthy status while API backends
# are recreated. Wait for fresh successful responses through the real LB.
set -eu
cd "$(dirname "$0")/.."
attempt=0
stable=0
while [ "$attempt" -lt 60 ]; do
if docker compose exec -T lb wget -qO- http://127.0.0.1:8080/health/ready >/dev/null 2>&1; then
stable=$((stable + 1))
if [ "$stable" -ge 3 ]; then
echo "balancer readiness confirmed"
exit 0
fi
else
stable=0
fi
attempt=$((attempt + 1))
sleep 1
done
echo "balancer did not become ready within 60 probes" >&2
exit 1