feat: limit accepted attachment work and add queue overload bench

Reject uploads with 429 at [uploads] max_unfinished_jobs, counted by the existing partial indexes in the membership block. Add the bench_queue profile, hypotheses H1-H9 and the fifth failure-stand API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-01 07:30:08 +03:00
co-authored by Claude Opus 5.5
parent 5b5f59aa3b
commit d667fa3c57
53 changed files with 5043 additions and 122 deletions
+113
View File
@@ -0,0 +1,113 @@
// Профиль очереди (design change track1-queue-overload, решение 6): открытая
// модель загрузок через LB. Окна — сценарии constant-arrival-rate, timeUnit 10 с
// для дробной интенсивности; VU заранее и без прибавления: тело — open на VU,
// создание на ходу с телом 10 MiB теряет итерации. Ответ не повторяется: 429 —
// отказ, недосланные итерации — dropped_iterations. Строка на загрузку
// «q,<окно>,<отправка мс>,<длительность мс>,<статус>,<Retry-After>,<X-Instance-Id>,
// <id>» — в файл консоли (--console-output); setup() пишет «q-t0,<мс>». WINDOWS —
// «имя:интенсивность:секунды:VU», окна идут подряд; WARM=N — N загрузок подряд.
import exec from "k6/execution";
import http from "k6/http";
import {
API,
SUMMARY_THRESHOLDS,
SUMMARY_TREND_STATS,
WORK_DIR,
summaryFiles,
} from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const BODY = open(`${WORK_DIR}/${__ENV.BODY}`, "b");
const MEDIA = __ENV.MEDIA;
const WARM = Number(__ENV.WARM || 0);
const WINDOWS = (__ENV.WINDOWS || "")
.split(",")
.filter((item) => item !== "")
.map((item) => {
const [name, rate, seconds, vus] = item.split(":");
return {
name,
rate: Number(rate),
seconds: Number(seconds),
vus: Number(vus),
};
});
// больше timeout server LB пути загрузки (30 с): клиент видит ответ LB
const TIMEOUT = "60s";
const URL = `${API}/chats/${fixture.readChatId}/attachments?filename=bench`;
const HEADERS = {
Authorization: `Bearer ${fixture.tokens[fixture.readerId]}`,
"Content-Type": MEDIA,
};
function scenarios() {
if (WARM) {
return {
warm: { executor: "shared-iterations", vus: 1, iterations: WARM },
};
}
const out = {};
let start = 0;
for (const item of WINDOWS) {
out[item.name] = {
executor: "constant-arrival-rate",
rate: Math.round(item.rate * 10),
timeUnit: "10s",
startTime: `${start}s`,
duration: `${item.seconds}s`,
preAllocatedVUs: item.vus,
maxVUs: item.vus,
gracefulStop: "45s",
};
start += item.seconds;
}
return out;
}
export const options = {
scenarios: scenarios(),
summaryTrendStats: SUMMARY_TREND_STATS,
// порог всегда выполняется: итерации попадают в итог, run.py сверяет с ними
// число строк
thresholds: {
...SUMMARY_THRESHOLDS,
iterations: ["count>=0"],
dropped_iterations: ["count>=0"],
},
};
export function setup() {
const t0 = Date.now();
console.log(`q-t0,${t0}`);
return t0;
}
export default function () {
const start = Date.now();
const res = http.post(URL, BODY, {
headers: HEADERS,
timeout: TIMEOUT,
responseCallback: http.expectedStatuses(202, 429),
});
const t = res.timings;
const measured = t.blocked + t.connecting + t.tls_handshaking + t.duration;
const duration = Math.max(
0,
Math.round(res.status === 0 ? Date.now() - start : measured),
);
let id = "-";
if (res.status === 202) {
id = res.json("id");
}
const retry = res.headers["Retry-After"] || "-";
const instance = res.headers["X-Instance-Id"] || "-";
console.log(
`q,${exec.scenario.name},${start},${duration},${res.status},${retry},` +
`${instance},${id}`,
);
}
export function handleSummary(data) {
return summaryFiles(data);
}
+81
View File
@@ -0,0 +1,81 @@
// Обход принятых вложений профиля очереди (design change track1-queue-overload,
// решение 9): истина о готовности — метаданные GET /attachments/{id}, опрос в
// замере не нужен: updated_at у ready не меняется после фиксации. Строка на
// вложение «qs,<id>,<http>,<status>,<error_code>,<variants>,<updated_at>»; у
// выборки (первые SAMPLE ids, порядок задал оркестратор от зерна) — оригинал и
// варианты с SHA-256 из метаданных: «qv,<id>,<имя>,<1|0>».
import { sha256 } from "k6/crypto";
import exec from "k6/execution";
import http from "k6/http";
import { SharedArray } from "k6/data";
import { API, WORK_DIR, authHeaders, summaryFiles } from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const ids = new SharedArray("ids", () =>
JSON.parse(open(`${WORK_DIR}/${__ENV.IDS}`)),
);
const SAMPLE = Number(__ENV.SAMPLE || 10);
const READER = authHeaders(fixture.tokens[fixture.readerId]);
const VARIANTS = ["thumbnail", "crop", "optimized"];
export const options = {
scenarios: {
sweep: {
executor: "shared-iterations",
vus: 4,
iterations: Math.max(1, ids.length),
maxDuration: "10m",
},
},
thresholds: { iterations: ["count>=0"] },
};
function checkBytes(id, name, expected) {
const query = name === "original" ? "" : `?variant=${name}`;
const res = http.get(`${API}/attachments/${id}/content${query}`, {
headers: READER,
responseType: "binary",
timeout: "60s",
});
let good = 0;
if (res.status === 200) {
good = sha256(res.body, "hex") === expected ? 1 : 0;
}
console.log(`qv,${id},${name},${good}`);
}
export default function () {
const index = exec.scenario.iterationInTest;
if (index >= ids.length) {
return;
}
const id = ids[index];
const res = http.get(`${API}/attachments/${id}`, {
headers: READER,
timeout: "30s",
responseCallback: http.expectedStatuses(200, 404),
});
if (res.status !== 200) {
console.log(`qs,${id},${res.status},-,-,0,-`);
return;
}
const meta = res.json();
const variants = meta.variants || [];
console.log(
`qs,${id},200,${meta.status},${meta.error_code || "-"},` +
`${variants.length},${meta.updated_at}`,
);
if (index < SAMPLE && meta.status === "ready") {
checkBytes(id, "original", meta.sha256);
for (const item of variants) {
if (VARIANTS.includes(item.name)) {
checkBytes(id, item.name, item.sha256);
}
}
}
}
export function handleSummary(data) {
return summaryFiles(data);
}
+161
View File
@@ -0,0 +1,161 @@
"""Файлы классов профиля очереди (design change `track1-queue-overload`,
решение 5): `s`, `m`, `lj`, `lp`, детерминированно от зерна.
Только в контейнере `mtusi-bench-images` на образе стенда: Pillow образа и та же
его версия, что у процесса обработки; `src` не импортируется. На stdout — JSON с
размерами, пикселями и SHA-256; файл больше лимита контракта — код 1.
python make_images.py <зерно> <каталог>
"""
import hashlib
import io
import json
import random
import sys
from pathlib import Path
from PIL import Image, ImageChops
from uploads import png_noise
MAX_BYTES = 10_485_760
MAX_PIXELS = 40_000_000
LARGE = (8000, 5000)
SMALL = (1600, 1200)
NOISE_HEIGHT = 3409
CELLS_LOW = 64
CELLS_HIGH = 512
FINE_DIVISOR = 6
TILE = 512
AMPLITUDE = 24
POSTERIZE_MASK = 0xF0
def noise_l(width: int, height: int, seed: int) -> Image.Image:
data = random.Random(seed).randbytes(width * height)
return Image.frombytes("L", (width, height), data)
def clouds(
width: int,
height: int,
seed: int,
cells: int = CELLS_LOW,
) -> Image.Image:
"""Гладкое поле из шума низкого разрешения: низкие частоты фото."""
return noise_l(cells, max(2, cells * height // width), seed).resize(
(width, height),
Image.Resampling.BICUBIC,
)
def detail_tile(
width: int,
height: int,
seed: int,
amplitude: int,
) -> Image.Image:
"""Плитка шума амплитуды `amplitude`, повторённая на всё поле."""
tile = noise_l(TILE, TILE, seed).point(lambda v: v * amplitude // 255)
field = Image.new("L", (width, height))
for y in range(0, height, TILE):
for x in range(0, width, TILE):
field.paste(tile, (x, y))
return field
def bands(
width: int,
height: int,
seed: int,
amplitude: int,
) -> list[Image.Image]:
out = []
for number in range(3):
band = ImageChops.add(
clouds(width, height, seed + number),
clouds(
width,
height,
seed + 10 + number,
cells=CELLS_HIGH,
).point(lambda v: v // FINE_DIVISOR),
)
if amplitude:
band = ImageChops.add(
band,
detail_tile(width, height, seed + 20 + number, amplitude),
)
out.append(band)
return out
def jpeg(image: Image.Image, quality: int) -> bytes:
out = io.BytesIO()
image.save(out, format="JPEG", quality=quality, subsampling="4:2:0")
return out.getvalue()
def build_s(seed: int) -> bytes:
return jpeg(Image.merge("RGB", bands(*SMALL, seed, AMPLITUDE)), 85)
def build_lj(seed: int) -> bytes:
return jpeg(Image.merge("RGB", bands(*LARGE, seed + 200, AMPLITUDE)), 88)
def build_lp(seed: int) -> bytes:
colour = [
band.point(lambda v: v & POSTERIZE_MASK)
for band in bands(*LARGE, seed + 200, 0)
]
alpha = clouds(*LARGE, seed + 300).point(
lambda v: (128 + v // 2) & POSTERIZE_MASK,
)
out = io.BytesIO()
Image.merge("RGBA", (*colour, alpha)).save(
out,
format="PNG",
compress_level=6,
)
return out.getvalue()
def build_m(seed: int) -> bytes:
return png_noise(NOISE_HEIGHT, seed + NOISE_HEIGHT)
BUILDERS = {
"s": (build_s, "s.jpg", "image/jpeg"),
"m": (build_m, "m.png", "image/png"),
"lj": (build_lj, "lj.jpg", "image/jpeg"),
"lp": (build_lp, "lp.png", "image/png"),
}
def main() -> int:
seed, directory = int(sys.argv[1]), Path(sys.argv[2])
report = {}
code = 0
for name, (build, filename, media) in BUILDERS.items():
data = build(seed)
with Image.open(io.BytesIO(data)) as image:
width, height = image.size
(directory / filename).write_bytes(data)
report[name] = {
"file": filename,
"media_type": media,
"bytes": len(data),
"width": width,
"height": height,
"sha256": hashlib.sha256(data).hexdigest(),
}
if len(data) > MAX_BYTES or width * height > MAX_PIXELS:
print(f"{name}: over the contract limit", file=sys.stderr)
code = 1
print(json.dumps(report))
return code
if __name__ == "__main__":
sys.exit(main())
+2173
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
# Override профиля очереди (третий -f, только этот профиль; design change
# track1-queue-overload, решение 10). Плагин метрик брокера и интервал
# статистики в секунду: порт 15692 — только сеть стенда, порты брокера сброшены
# в bench.compose.yml. Worker перезапускается, как на рабочем стенде: ядро может
# завершить его процесс 1, когда конкуренция не помещается в лимит памяти, и без
# перезапуска ячейка простояла бы до срока окна с ложными stuck. Пути — от
# каталога первого файла compose (корень репозитория)
services:
rabbitmq:
volumes:
- type: bind
source: ./bench/rabbitmq/enabled_plugins
target: /etc/rabbitmq/enabled_plugins
read_only: true
- type: bind
source: ./bench/rabbitmq/91-bench.conf
target: /etc/rabbitmq/conf.d/91-bench.conf
read_only: true
worker:
restart: unless-stopped
+2
View File
@@ -0,0 +1,2 @@
# Профиль очереди: значения метрик свежие за секунду (проба: 4,7 мс CPU на опрос)
collect_statistics_interval = 1000
+1
View File
@@ -0,0 +1 @@
[rabbitmq_prometheus].
+1085 -13
View File
File diff suppressed because it is too large Load Diff
+73 -3
View File
@@ -34,6 +34,14 @@
# `pk <нс> <роль> <id12> missing`. Появился /work/<имя>.stop — perl
# читает пик через тот же дескриптор (`peak <роль> <байт>|missing`),
# строка `end <нс>`, выход 0. Всё — в /work/<имя>.log.
# queue (профиль очереди, design change track1-queue-overload, решение 10):
# <интервал, с> queue <имя очереди>
# Сеть mtusi-bench. Обход cgroup, как scan (`cg`), `vm`, `lb`; ещё `mp <нс>
# <id12> <memory.peak> <anon> <oom_kill>` на контейнер и `mq <нс> <ready>
# <unacked>` — метрики брокера HTTP/1.0 по /dev/tcp (брокер недоступен —
# `mq <нс> missing`). В фоне psql с \watch пишет /work/jobs.log (одно
# соединение): jobs|<мс>|outbox|waiting|published|processing|oldest_s|
# staging_ready. Разбор — bench/overload.py.
set -u
interval=$1
@@ -42,6 +50,10 @@ mode=list
if [[ ${1:-} == scan ]]; then
mode=scan
shift
elif [[ ${1:-} == queue ]]; then
mode=queue
queue_name=$2
shift 2
elif [[ ${1:-} == peak ]]; then
mode=peak
name=$2
@@ -83,6 +95,25 @@ FROM pg_stat_io WHERE object = 'wal'
SQL
fi
if [[ $mode == queue ]]; then
export PGPASSWORD="$POSTGRES_PASSWORD"
psql "host=postgres user=$POSTGRES_USER dbname=$POSTGRES_DB \
application_name=bench-sampler" -XAtq -F '|' >/work/jobs.log 2>&1 <<SQL &
SELECT 'jobs', (extract(epoch FROM clock_timestamp()) * 1000)::bigint,
count(*) FILTER (WHERE state = 'queued' AND published_at IS NULL
AND coalesce(next_attempt_at, created_at) <= clock_timestamp()),
count(*) FILTER (WHERE state = 'queued' AND published_at IS NULL
AND coalesce(next_attempt_at, created_at) > clock_timestamp()),
count(*) FILTER (WHERE state = 'queued' AND published_at IS NOT NULL),
count(*) FILTER (WHERE state = 'processing'),
coalesce(round(extract(epoch FROM clock_timestamp() - min(created_at))::numeric, 1), 0),
(SELECT count(*) FROM attachments
WHERE status = 'ready' AND staging_key IS NOT NULL)
FROM attachment_jobs WHERE state IN ('queued', 'processing')
\watch $interval
SQL
fi
if [[ $mode == peak ]]; then
log=/work/$name.log
stop=/work/$name.stop
@@ -219,16 +250,54 @@ lb_lines() {
exec 3<&-
}
mp_line() {
local id=$1 dir=/sys/fs/cgroup/docker/$1
local key val peak= anon= oom=
{
read -r peak <"$dir/memory.peak"
while read -r key val; do
[[ $key == anon ]] && { anon=$val; break; }
done <"$dir/memory.stat"
while read -r key val; do
[[ $key == oom_kill ]] && oom=$val
done <"$dir/memory.events"
} 2>/dev/null
[[ -n $peak && -n $anon && -n $oom ]] &&
printf 'mp %s %s %s %s %s\n' "$ns" "${id:0:12}" "$peak" "$anon" "$oom" >&4
}
mq_line() {
local line ready= unacked=
if ! exec 3<>/dev/tcp/rabbitmq/15692 2>/dev/null; then
printf 'mq %s missing\n' "$ns" >&4
return
fi
printf 'GET /metrics/detailed?vhost=%%2F&family=queue_coarse_metrics HTTP/1.0\r\nHost: x\r\n\r\n' >&3
while IFS= read -r line; do
line=${line%$'\r'}
case $line in
rabbitmq_detailed_queue_messages_ready\{*"$queue_name"*) ready=${line##* } ;;
rabbitmq_detailed_queue_messages_unacked\{*"$queue_name"*) unacked=${line##* } ;;
esac
done <&3
exec 3<&-
# очередь ещё не объявлена — нули, а брокер отвечает
printf 'mq %s %s %s\n' "$ns" "${ready:-0}" "${unacked:-0}" >&4
}
hex64='^[0-9a-f]{64}$'
while :; do
# EPOCHREALTIME bash 5 — часы ВМ без запуска date
ns=${EPOCHREALTIME/./}000
if [[ $mode == scan ]]; then
if [[ $mode == scan || $mode == queue ]]; then
for dir in /sys/fs/cgroup/docker/*/; do
dir=${dir%/}
id=${dir##*/}
[[ $id =~ $hex64 ]] && cg_line - "$id"
if [[ $id =~ $hex64 ]]; then
cg_line - "$id"
[[ $mode == queue ]] && mp_line "$id"
fi
done
else
for i in "${!ids[@]}"; do
@@ -236,6 +305,7 @@ while :; do
done
fi
vm_line
[[ $mode == list ]] && lb_lines
[[ $mode == list || $mode == queue ]] && lb_lines
[[ $mode == queue ]] && mq_line
sleep "$interval"
done