feat: process attachments asynchronously with RabbitMQ and a worker
Upload answers 202 after staging, a queued job in PostgreSQL and a broker confirm; a separate worker publishes the original and a thumbnail with bounded retries. Adds the job and variant tables, the broker service, the worker S3 user, cleanup and reconcile support for staging and variants, the failure stand with broker and worker, bench and driver updates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+69
-13
@@ -34,7 +34,11 @@ VARIANT_NAMES = {
|
||||
"unlimited": "без лимита",
|
||||
"limited": "с лимитом",
|
||||
}
|
||||
# коды ответов в runs.csv; 0 — ошибка соединения (ответа нет)
|
||||
# коды ответов в runs.csv; 0 — ошибка соединения (ответа нет). Столбец s201 не
|
||||
# переименовывается (.claude/rules/bench.md, «Результаты»): в нём код успеха
|
||||
# варианта, а какой — называет success_code (design change async-attachments,
|
||||
# решение 16). Второй код успеха у того же варианта — s_other
|
||||
SUCCESS_FIELD = "s201"
|
||||
CODES = (201, 429, 400, 413, 415, 502, 503, 504, 0)
|
||||
CODE_FIELDS = [f"s{code}" if code else "s_conn_error" for code in CODES]
|
||||
|
||||
@@ -69,6 +73,7 @@ RUN_FIELDS = [
|
||||
"lb_sock_max_mib",
|
||||
"host_swapouts",
|
||||
"flags",
|
||||
"success_code",
|
||||
]
|
||||
|
||||
|
||||
@@ -230,14 +235,20 @@ def k6_stats(
|
||||
t0: int,
|
||||
ramp_s: float,
|
||||
window_s: float,
|
||||
*,
|
||||
success_code: int,
|
||||
) -> dict[str, Any]:
|
||||
"""Ответы по кодам — за весь прогон (разгон и окно, в том числе после
|
||||
гибели реплики); загрузок 201 в секунду и перцентили успешных — по
|
||||
загрузкам, отправленным в окне `[t0 + ramp, t0 + ramp + window)`."""
|
||||
гибели реплики); успешных загрузок в секунду и их перцентили — по
|
||||
загрузкам, отправленным в окне `[t0 + ramp, t0 + ramp + window)`.
|
||||
Успешная — ответ с `success_code` варианта, он считается в `s201`;
|
||||
прочий 201 или 202 — в `s_other`."""
|
||||
counts = dict.fromkeys(CODE_FIELDS, 0)
|
||||
other = 0
|
||||
for item in uploads:
|
||||
if item.status in CODES:
|
||||
if item.status == success_code:
|
||||
counts[SUCCESS_FIELD] += 1
|
||||
elif item.status in CODES and item.status != 201:
|
||||
key = f"s{item.status}" if item.status else "s_conn_error"
|
||||
counts[key] += 1
|
||||
else:
|
||||
@@ -247,7 +258,7 @@ def k6_stats(
|
||||
ok = [
|
||||
item.duration_ms
|
||||
for item in uploads
|
||||
if item.status == 201 and w0 <= item.start_ms < w1
|
||||
if item.status == success_code and w0 <= item.start_ms < w1
|
||||
]
|
||||
|
||||
def ms(value: float | None) -> float | None:
|
||||
@@ -255,6 +266,7 @@ def k6_stats(
|
||||
|
||||
return {
|
||||
**counts,
|
||||
"success_code": success_code,
|
||||
"s_other": other,
|
||||
"requests": len(uploads),
|
||||
"window_s": window_s,
|
||||
@@ -367,7 +379,8 @@ def run_row(
|
||||
из-за памяти (`OOMKilled` контейнера или `oom_kill` cgroup),
|
||||
`host_swap` — хост выгружал страницы в swap во время прогона,
|
||||
`peak_sampled` — пик окна по выборкам, а не по сброшенному
|
||||
`memory.peak`."""
|
||||
`memory.peak`, `s3_down` и `broker_down` — S3 или брокер не дожил до
|
||||
конца прогона."""
|
||||
app = peaks.roles.get("api", Peak())
|
||||
s3 = peaks.roles.get("s3", Peak())
|
||||
lb = peaks.roles.get("haproxy", Peak())
|
||||
@@ -381,6 +394,8 @@ def run_row(
|
||||
flags.append("peak_sampled")
|
||||
if state.get("s3_down"):
|
||||
flags.append("s3_down")
|
||||
if state.get("broker_down"):
|
||||
flags.append("broker_down")
|
||||
return {
|
||||
**{key: run[key] for key in ("run", "variant", "size", "clients")},
|
||||
"repeat": run["repeat"],
|
||||
@@ -599,8 +614,8 @@ def hypotheses(
|
||||
out.append(
|
||||
{
|
||||
"id": "H3",
|
||||
"text": "загрузок 201 в секунду при C ≥ 10: «с лимитом» ≥ 90 % "
|
||||
"«без лимита» на тех же C, пока тот жив",
|
||||
"text": "успешных загрузок в секунду при C ≥ 10: «с лимитом» ≥ "
|
||||
"90 % «без лимита» на тех же C, пока тот жив",
|
||||
"numbers": "; ".join(
|
||||
f"{s} C={c}: {a:.2f} / {b:.2f} = {ratio:.0%}"
|
||||
for s, c, a, b, ratio in ratios
|
||||
@@ -676,8 +691,20 @@ def render_summary(meta: dict[str, Any], rows: list[dict[str, Any]]) -> str:
|
||||
),
|
||||
f"- Реплика {profile['cpus']} CPU / {profile['memory']} без swap, "
|
||||
f"буфер приёма `{meta.get('stand', {}).get('api_tcp_rmem', '—')}`; "
|
||||
f"S3 {profile['s3_cpus']} CPU / {profile['s3_memory']}; LB "
|
||||
f"{profile['lb_cpus']} CPU / {profile['lb_memory']}",
|
||||
f"S3 {profile['s3_cpus']} CPU / {profile['s3_memory']}; брокер "
|
||||
f"{profile['broker_cpus']} CPU / {profile['broker_memory']}; LB "
|
||||
f"{profile['lb_cpus']} CPU / {profile['lb_memory']}. Worker не "
|
||||
"запущен: задания ждут в очереди, на прогон — новый volume брокера",
|
||||
"- Код успеха: "
|
||||
+ (
|
||||
", ".join(
|
||||
f"«{VARIANT_NAMES[v]}» — {code}"
|
||||
for v, code in info.get("success_codes", {}).items()
|
||||
)
|
||||
or "—"
|
||||
)
|
||||
+ " (столбец `s201` `runs.csv` считает код варианта, его называет "
|
||||
"`success_code`)",
|
||||
"- Пик — `memory.peak` cgroup, сброшенный через свой дескриптор "
|
||||
"перед нагрузкой (`peak_source` = reset); без сброса — наибольшая "
|
||||
"выборка раз в "
|
||||
@@ -695,7 +722,7 @@ def render_summary(meta: dict[str, Any], rows: list[dict[str, Any]]) -> str:
|
||||
"включает.",
|
||||
"",
|
||||
"| Вариант | Тело | C | Пик старта, MiB | До окна, MiB | Пик, MiB | "
|
||||
"anon, MiB | sock, MiB | OOM | 201 | 429 | 5xx | ошибка соединения | "
|
||||
"anon, MiB | sock, MiB | OOM | Успех | 429 | 5xx | ошибка соединения | "
|
||||
"Загрузок/с | p50, мс | p95, мс | S3 пик, MiB | S3 anon, MiB | "
|
||||
"LB пик, MiB | Пометки |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"
|
||||
@@ -933,8 +960,9 @@ def selftest() -> int:
|
||||
t0, ups = parse_k6(console)
|
||||
expect("t0", t0, 1000)
|
||||
expect("uploads", len(ups), 6)
|
||||
stats = k6_stats(ups, t0 or 0, 3, 20)
|
||||
stats = k6_stats(ups, t0 or 0, 3, 20, success_code=201)
|
||||
expect("201", stats["s201"], 3)
|
||||
expect("success code", stats["success_code"], 201)
|
||||
expect("429", stats["s429"], 1)
|
||||
expect("conn", stats["s_conn_error"], 1)
|
||||
expect("503", stats["s503"], 1)
|
||||
@@ -942,6 +970,24 @@ def selftest() -> int:
|
||||
expect("uploads/s", stats["uploads_per_s"], 0.05)
|
||||
expect("p95", stats["p95_ms"], 80.0)
|
||||
expect("percentile", percentile([1, 2, 3, 4], 0.5), 2.5)
|
||||
# лаба 5: код успеха варианта — 202, столбец тот же; чужой код успеха —
|
||||
# s_other, и в окно не идёт
|
||||
_, async_ups = parse_k6(console.replace(",201,", ",202,"))
|
||||
accepted = k6_stats(async_ups, t0 or 0, 3, 20, success_code=202)
|
||||
expect("202 in s201", accepted["s201"], 3)
|
||||
expect("success code 202", accepted["success_code"], 202)
|
||||
expect("202 p95", accepted["p95_ms"], 80.0)
|
||||
expect("202 other", accepted["s_other"], 0)
|
||||
wrong = k6_stats(ups, t0 or 0, 3, 20, success_code=202)
|
||||
expect("201 is not success of 202", wrong["s201"], 0)
|
||||
expect("201 in s_other", wrong["s_other"], 3)
|
||||
expect("no window uploads", wrong["uploads_per_s"], 0.0)
|
||||
expect("no percentiles", wrong["p95_ms"], None)
|
||||
swapped = k6_stats(async_ups, t0 or 0, 3, 20, success_code=201)
|
||||
expect("202 is not success of 201", swapped["s201"], 0)
|
||||
expect("202 in s_other", swapped["s_other"], 3)
|
||||
expect("success_code column last", RUN_FIELDS[-1], "success_code")
|
||||
expect("s201 column kept", "s201" in RUN_FIELDS, True)
|
||||
|
||||
sampler = "\n".join(
|
||||
[
|
||||
@@ -976,6 +1022,9 @@ def selftest() -> int:
|
||||
expect("row flags", row["flags"], "oom host_swap")
|
||||
expect("row fields", set(RUN_FIELDS) >= set(row), True)
|
||||
expect("row peak", row["peak_mib"], 145.0)
|
||||
expect("row success code", row["success_code"], 201)
|
||||
downed = run_row(run, 1, parsed, stats, {"broker_down": True}, 0)
|
||||
expect("row broker_down", downed["flags"], "broker_down")
|
||||
|
||||
def synth(variant: str, clients: int, peak: float, **extra: Any) -> dict:
|
||||
base = {
|
||||
@@ -1042,13 +1091,20 @@ def selftest() -> int:
|
||||
"memory": "512m",
|
||||
"s3_cpus": "1",
|
||||
"s3_memory": "512m",
|
||||
"broker_cpus": "1",
|
||||
"broker_memory": "512m",
|
||||
"lb_cpus": "1",
|
||||
"lb_memory": "256m",
|
||||
},
|
||||
"uploads": {"bodies": {"10MiB": body_passport("10MiB", 3409, b"x")}},
|
||||
"uploads": {
|
||||
"bodies": {"10MiB": body_passport("10MiB", 3409, b"x")},
|
||||
"success_codes": {"unlimited": 202, "limited": 202},
|
||||
},
|
||||
}
|
||||
text = render_summary(meta, rows)
|
||||
expect("summary has H1", "| H1 |" in text, True)
|
||||
expect("summary names code", "«с лимитом» — 202" in text, True)
|
||||
expect("summary names broker", "брокер 1 CPU / 512m" in text, True)
|
||||
expect("summary has cells", "| с лимитом | 10MiB | 40 |" in text, True)
|
||||
expect(
|
||||
"replica growth over C=10",
|
||||
|
||||
Reference in New Issue
Block a user