feat(lab5): track 1 queue experiment and evidence

- 3 profiles (serial 1/1, balanced 4/4, eager 8/32) x 2 image sizes
- measure throughput, DB-derived queue lag and p95 time-to-ready, worker RSS
- separate MAX_PENDING_JOBS=3 backpressure and worker recovery run
- self-contained HTML/SVG dashboard plus JSON/Markdown evidence
- document methodology, results and limitations in REPORT/README/CHANGELOG
This commit is contained in:
Mikhail Verkovykh
2026-11-15 00:44:45 +03:00
parent 9e43faa536
commit fec2882c9a
8 changed files with 2809 additions and 10 deletions
+5 -1
View File
@@ -25,6 +25,10 @@
- Проверки: async-aware custom tests, негативный случай 42 MP (413), evidence
для smoke, отказов, persistence и failover.
- `scripts/restart.sh` перезапускает RabbitMQ и worker с сохранением volumes.
- `scripts/track1_experiment.py` и `make track1` — трек 1: матрица
`serial/balanced/eager` × `small_many`/`huge_few`, throughput, queue lag,
p95 time-to-ready, RSS и отдельный backpressure/recovery прогон;
self-contained HTML-дашборд с inline SVG.
- Документация: README с запуском и архитектурой, отчёт с таблицей критериев,
CHANGELOG.
@@ -55,4 +59,4 @@
- `evidence/lab5-smoke.txt`, `evidence/lab5-negative-cases.txt`,
`evidence/lab5-grade4.{json,md}`, `evidence/lab5-persistence.{txt}`,
`evidence/lab5-persistence-containers.txt`, `evidence/lab5-failover.txt`,
`evidence/reconcile.txt`.
`evidence/reconcile.txt`, `evidence/track1.{json,html,md}`.
+4 -1
View File
@@ -4,7 +4,7 @@ CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence test-failover
.PHONY: help check validate test load test-persistence test-failover track1
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@@ -28,3 +28,6 @@ test-persistence:
test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
track1:
$(PYTHON) scripts/track1_experiment.py --base-url "$(BASE_URL)"
+29 -3
View File
@@ -136,8 +136,9 @@ byte-for-byte и сохраняет исходный SHA-256. Метаданны
make check
make test BASE_URL=http://localhost:8080 # публичный smoke
python3 tests/custom/attachments.py --base-url ... # 413/415/404/400, без 5xx
python3 tests/custom/attachment_flow.py --base-url ... # сквозной upload/download
python3 tests/custom/concurrent_uploads.py --base-url ... # конкурентные upload
# attachment_flow.py — двухшаговый helper для verify-attachment-failover.sh,
# а не самостоятельный тест: ему нужны --action upload|download и --state.
python3 scripts/lab5_resilience.py --base-url ... # 6 сценариев уровня 4
python3 scripts/track1_experiment.py # трек 1 уровня 5
@@ -151,8 +152,33 @@ python3 scripts/track1_experiment.py # трек 1 уров
Трек 1 запускает матрицу профилей `serial/balanced/eager` на маленьких и
больших изображениях, измеряет throughput, queue lag, p95 time-to-ready и RSS,
затем отдельно показывает backpressure и восстановление. Результаты и графики
описаны в [REPORT.md](REPORT.md).
затем отдельно показывает backpressure и восстановление. Результаты и графики —
`evidence/track1.{json,html,md}`, разбор — в [REPORT.md](REPORT.md).
```sh
# Полный прогон: 30 small + 12 huge на каждый профиль, затем backpressure.
make track1 BASE_URL=http://localhost:8080
# То же без make.
python3 scripts/track1_experiment.py --base-url http://localhost:8080
# Быстрая проверка механики и/или свои лимиты worker-а.
python3 scripts/track1_experiment.py --small-jobs 5 --huge-jobs 3 --skip-backpressure
TRACK1_WORKER_CPU_LIMIT=2.0 TRACK1_WORKER_MEM_LIMIT=3G \
python3 scripts/track1_experiment.py --base-url http://localhost:8080
```
Эксперимент пересоздаёт worker с `WORKER_CONCURRENCY`/`WORKER_PREFETCH`,
поднимает memory limit до 2 GiB (чтобы `eager` не падал по OOM на больших
изображениях), а в `finally` возвращает конфигурацию из `.env`. Он управляет
только локальным Compose-стендом и не предназначен для production.
Кратко: на 192×128 eager дал 13.86 jobs/s против 6.88 у serial (2×) при RSS
28→33 MiB. На 2400×1800 все профили дали ~0.45 jobs/s (worker ограничен 1 CPU),
но RSS вырос 205→1122 MiB, а queue lag p95 упал 23.3→17.5 s: concurrency меняет
latency/ресурсы, а не throughput CPU-bound задач. При `MAX_PENDING_JOBS=3`
четвёртый upload получил `503` + `Retry-After: 5`; после старта worker три
принятых задания стали ready за 7.6 s.
## Ограничения
+103 -5
View File
@@ -115,7 +115,7 @@ backoff ±50% jitter до `JOB_MAX_ATTEMPTS`. После исчерпания
| Очистка staging после фиксации | сценарии `worker_stopped`, `crash_after_effect` | `staging_cleared: true`; reconciler удаляет только брошенное | `evidence/lab5-grade4.json`, `evidence/reconcile.txt` |
| Негативные случаи и лимиты | `python3 tests/custom/attachments.py` | 413 по bytes и по 42 MP, 415 corrupt/spoof, 404/400, нет 5xx | `evidence/lab5-negative-cases.txt` |
| Failover API | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 118 успешных записей, 1 переходная ошибка, восстановление 2.659 s; остановлена именно `api-2` | `evidence/lab5-failover.txt` |
| Трек 1, уровень 5 | `python3 scripts/track1_experiment.py` | см. раздел «Эксперимент трека 1» ниже | `evidence/track1.json`, `evidence/track1.html` |
| Трек 1, уровень 5 | `python3 scripts/track1_experiment.py` | 3 профиля × 2 размера; eager/small 13.86 jobs/s против serial 6.88; huge_few ~0.45 jobs/s у всех, RSS 205→1122 MiB; cap=3 дал 503 + Retry-After 5 и восстановление за 7.596 s | `evidence/track1.json`, `evidence/track1.html` |
## Эксперименты и отказы
@@ -141,10 +141,108 @@ HAProxy; отказ БД или брокера в этом сценарии не
## Эксперимент трека 1 (уровень 5)
<!-- TRACK1:START -->
Будет заполнено после запуска `scripts/track1_experiment.py`: гипотеза, профили,
размеры изображений, throughput, queue lag, p95 time-to-ready, RSS,
backpressure и восстановление. Сырые данные — `evidence/track1.json`, графики —
`evidence/track1.html`.
### Гипотеза
Маленькие изображения, которые не требуют масштабирования, дешевле на задание:
выше throughput и ниже RSS. Большие изображения (2400×1800) требуют декодирования
и downscale до 1280×960, поэтому очередь растёт, p95 time-to-ready увеличивается,
а память сильнее зависит от concurrency. Дополнительно проверялся компромисс
«latency против ресурсов»: больше concurrency/prefetch должно снижать queue lag,
но повышать RSS.
### Методика
- Профили: `serial` 1/1, `balanced` 4/4, `eager` 8/32
(concurrency/prefetch).
- Сценарии: `small_many` — 30 PNG 192×128 (941 B, варианты не масштабируются);
`huge_few` — 12 PNG 2400×1800 (53 135 B, 4.32 MP, optimized уменьшается до
1280×960).
- Для каждой из 6 ячеек worker пересоздавался с профилем, поэтому RSS не
переносился из предыдущего прогона. Изображения загружались параллельно
(до 8 HTTP-клиентов). Все задания дожидались терминального состояния.
- Метрики берутся из PostgreSQL по `attachment_jobs`: queue lag =
`processing_started_at - created_at`, time-to-ready =
`finished_at - created_at`, processing = `finished_at - processing_started_at`.
Throughput = число ready / (последний `finished_at` − первый `created_at`).
- RSS — `VmRSS` процесса worker из `/proc/1/status`, сэмпл примерно каждые
100 мс; baseline снимался до загрузки.
- Worker ограничен **1 CPU**. На время эксперимента memory limit поднят до
**2 GiB** (в `.env` по умолчанию 1 GiB), иначе `eager/huge_few` упирался бы в
OOM, а не в измеряемый компромисс. Это зафиксировано в JSON.
- Backpressure: API пересоздан с `MAX_PENDING_JOBS=3`, worker остановлен,
upload-ы идут последовательно до первого `503`; затем worker запускается и
проверяется восстановление принятых заданий и новый probe upload.
Команда:
```sh
make track1 BASE_URL=http://localhost:8080
# или
python3 scripts/track1_experiment.py --base-url http://localhost:8080
```
Сырые данные: `evidence/track1.json`; графики: `evidence/track1.html`;
краткая таблица: `evidence/track1.md`.
### Результаты
| Профиль | Сценарий | Jobs/s | Queue lag p95, ms | Ready p95, ms | Processing p95, ms | RSS peak, MiB | Max parallel |
| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |
| serial | small_many | 6.875 | 3 194 | 3 284 | 113 | 28.2 | 1 |
| serial | huge_few | 0.443 | 23 333 | 25 521 | 2 308 | 204.7 | 1 |
| balanced | small_many | 11.590 | 1 624 | 1 736 | 209 | 30.6 | 4 |
| balanced | huge_few | 0.454 | 17 716 | 25 785 | 25 374 | 728.7 | 4 |
| eager | small_many | 13.858 | 898 | 1 158 | 284 | 32.7 | 8 |
| eager | huge_few | 0.459 | 17 538 | 25 699 | 24 979 | 1 122.1 | 8 |
Backpressure: cap `3`; первые 3 upload-а получили `202`, четвёртый — `503` с
`Retry-After: 5` и `error_code=unavailable`. После старта worker три принятых
задания стали `ready` за **7.596 s** (включая запуск контейнера и healthcheck),
после чего probe upload получил `202` и дошёл до `ready`.
### Выводы
1. **Размер изображения важнее числа заданий.** При `balanced` маленькие файлы
дают 11.59 jobs/s, большие — 0.454 jobs/s (в 25.5× меньше); p95 time-to-ready
растёт с 1 736 до 25 785 ms (в 14.9×). Processing p50 для huge — 8 460 ms
против 211 ms для small: доминирует декодирование/масштабирование, а не
ожидание в очереди.
2. **Eager хорошо работает на маленьких заданиях.** 13.86 jobs/s против 6.88 у
serial (2.0×), queue lag p95 падает с 3 194 до 898 ms, RSS растёт всего с
28.2 до 32.7 MiB. Это ожидаемый выигрыш от перекрытия лёгких задач.
3. **На huge_few concurrency не даёт throughput.** Все три профиля дают
~0.44–0.46 jobs/s: worker упирается в 1 CPU, а декодирование и WebP-кодирование
уже насыщают его. Queue lag p95 снижается (23.3 → 17.5 s), но p95
time-to-ready остаётся ~25.5 s: последние задания всё равно ждут своей доли
CPU. При этом RSS растёт с 205 MiB (serial) до 729 MiB (balanced) и
1 122 MiB (eager). **Больше concurrency здесь — не бесплатное ускорение, а
рост памяти при том же throughput.**
4. **Backpressure ограничивает принятую работу.** При cap=3 API перестал
принимать новые файлы до чтения тела и вернул retryable `503`; уже
подтверждённые задания не потерялись и завершились после возврата worker.
Это и есть требуемое «bounded acceptance + recovery».
5. **Практический выбор.** Для лёгких изображений разумен `balanced`/`eager`;
для тяжёлых при одном CPU лучше `balanced` (или `serial`, если важна память):
throughput тот же, а RSS в 1.5–5.5× ниже, чем у eager. `prefetch` больше
`concurrency` лишь держит сообщения у worker-а и не увеличивает параллельную
обработку.
### Ограничения эксперимента
- Один worker, один RabbitMQ, один PostgreSQL; это сравнение настроек, не HA и
не горизонтальное масштабирование.
- Worker ограничен 1 CPU и 2 GiB; на другом железе абсолютные числа и точка
насыщения будут другими. Относительный вывод «CPU-bound huge не ускоряется
concurrency» получен именно для этого лимита.
- PNG-фикстуры синтетические и хорошо сжимаются; доминирует стоимость
декодирования/масштабирования, а не сеть. Размеры в байтах и SHA-256 есть в
JSON.
- Один прогон на ячейку, без длительного прогрева и повторений; p95 по 12
заданиям чувствителен к выбросу. Это учебная оценка, не SLA.
- `MAX_PENDING_JOBS` проверяется приблизительно и не одной транзакцией с
вставкой; при нескольких API-репликах возможен небольшой перебор.
- Время восстановления backpressure включает `docker compose start` и
healthcheck, поэтому это верхняя оценка, а не время чистой обработки.
<!-- TRACK1:END -->
## Ограничения и следующие шаги
+276
View File
@@ -0,0 +1,276 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lab5 track 1 — очередь под перегрузкой</title>
<style>
:root { color-scheme: light; }
* { box-sizing: border-box; }
body { margin: 0; padding: 28px; font: 15px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: #0f172a; background: #f8fafc; }
main { max-width: 980px; margin: 0 auto; }
h1 { font-size: 28px; margin: 0 0 6px; }
h2 { font-size: 20px; margin: 28px 0 10px; }
p.lead { color: #475569; margin: 0 0 18px; }
.card { background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 16px 18px;
box-shadow: 0 1px 2px rgba(15,23,42,.04); margin: 0 0 16px; }
.hypothesis { border-left: 4px solid #0284c7; }
.hypothesis strong { color: #075985; }
.metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; }
.metric { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; padding: 12px; }
.metric .value { font-size: 22px; font-weight: 700; }
.metric .label { color: #64748b; font-size: 13px; }
table { border-collapse: collapse; width: 100%; font-size: 14px; }
th, td { text-align: right; padding: 8px 9px; border-bottom: 1px solid #e2e8f0; }
th:first-child, td:first-child, th:nth-child(2), td:nth-child(2) { text-align: left; }
th { color: #475569; font-weight: 600; background: #f8fafc; }
tr:last-child td { border-bottom: 0; }
.ok { color: #047857; font-weight: 700; }
.blocked { color: #b91c1c; font-weight: 700; }
.chart { padding: 10px 12px 4px; }
svg { width: 100%; height: auto; display: block; }
.chart-title { font-size: 17px; font-weight: 700; fill: #0f172a; }
.chart-sub { font-size: 12px; fill: #64748b; }
.axis { font-size: 11px; fill: #475569; }
.bar-label { font-size: 10px; fill: #0f172a; font-weight: 600; }
.grid { stroke: #e2e8f0; stroke-width: 1; }
ul { margin: 8px 0 0; padding-left: 22px; }
li { margin: 5px 0; }
.note { color: #475569; font-size: 13px; }
code { background: #f1f5f9; padding: 1px 5px; border-radius: 4px; }
@media (max-width: 640px) {
body { padding: 16px; }
.card { padding: 12px; }
table { font-size: 12px; }
}
</style>
</head>
<body>
<main>
<h1>Lab5, трек 1: очередь под перегрузкой</h1>
<p class="lead">Сгенерировано 2026-11-14T21:42:03.122104+00:00. Стенд: http://172.18.0.1:8080,
4 CPU, Docker 5.6.1.</p>
<section class="card hypothesis">
<strong>Гипотеза.</strong> Маленькие изображения, которые почти не требуют
масштабирования, должны давать высокий throughput и низкий RSS на задание.
Большие изображения требуют декодирования и downscale, поэтому каждое задание
дороже: при том же числе worker-ов очередь растёт, p95 time-to-ready
увеличивается, а пиковый RSS зависит от concurrency сильнее, чем у маленьких
файлов. Одновременно проверяем компромисс: <em>eager</em> уменьшает ожидание,
но повышает потребление памяти; <em>serial</em> экономит память, но ограничивает
throughput.
</section>
<section class="card">
<h2>Профили и сценарии</h2>
<table>
<thead><tr><th>Профиль</th><th>Concurrency</th><th>Prefetch</th><th>Смысл</th></tr></thead>
<tbody>
<tr><td>serial</td><td>1</td><td>1</td><td style='text-align:left'>one job at a time; minimum memory, maximum queueing</td></tr><tr><td>balanced</td><td>4</td><td>4</td><td style='text-align:left'>moderate in-process parallelism and broker window</td></tr><tr><td>eager</td><td>8</td><td>32</td><td style='text-align:left'>wide broker window; highest memory, lowest latency</td></tr>
</tbody>
</table>
<p class="note">Сценарии:
small_many — 192×128, 30 jobs, many small images; variants fit or crop without large scaling; huge_few — 2400×1800, 12 jobs, few 4.32 MP images; optimized variant must scale down to 1280.</p>
</section>
<section class="card">
<h2>Ключевые числа</h2>
<div class="metrics">
<div class="metric"><div class="value">6</div><div class="label">прогонов матрицы</div></div>
<div class="metric"><div class="value">1122 MiB</div><div class="label">максимальный RSS worker</div></div>
<div class="metric"><div class="value">3</div><div class="label">принято до первого 503</div></div>
<div class="metric"><div class="value">7.6 s</div><div class="label">восстановление после backpressure</div></div>
</div>
</section>
<section class="card chart"><svg viewBox="0 0 760 320" role="img" aria-label="Throughput: готовые задания в секунду">
<text x="64" y="24" class="chart-title">Throughput: готовые задания в секунду</text>
<text x="64" y="42" class="chart-sub">Чем выше, тем быстрее pipeline обрабатывает очередь.</text>
<line x1="64" y1="258.0" x2="740" y2="258.0" class="grid"/>
<text x="54" y="262.0" class="axis" text-anchor="end">0 jobs/s</text>
<line x1="64" y1="206.5" x2="740" y2="206.5" class="grid"/>
<text x="54" y="210.5" class="axis" text-anchor="end">4 jobs/s</text>
<line x1="64" y1="155.0" x2="740" y2="155.0" class="grid"/>
<text x="54" y="159.0" class="axis" text-anchor="end">8 jobs/s</text>
<line x1="64" y1="103.5" x2="740" y2="103.5" class="grid"/>
<text x="54" y="107.5" class="axis" text-anchor="end">12 jobs/s</text>
<line x1="64" y1="52.0" x2="740" y2="52.0" class="grid"/>
<text x="54" y="56.0" class="axis" text-anchor="end">16 jobs/s</text>
<rect x="92.9" y="171.4" width="67.6" height="86.6" fill="#64748b" rx="3"/>
<text x="126.7" y="166.4" class="bar-label" text-anchor="middle">6.88 jobs/s</text>
<rect x="175.3" y="112.0" width="67.6" height="146.0" fill="#0284c7" rx="3"/>
<text x="209.1" y="107.0" class="bar-label" text-anchor="middle">11.59 jobs/s</text>
<rect x="257.7" y="83.4" width="67.6" height="174.6" fill="#f59e0b" rx="3"/>
<text x="291.5" y="78.4" class="bar-label" text-anchor="middle">13.86 jobs/s</text>
<text x="233.0" y="282" class="axis" text-anchor="middle">small_many</text>
<rect x="430.9" y="252.4" width="67.6" height="5.6" fill="#64748b" rx="3"/>
<text x="464.7" y="247.4" class="bar-label" text-anchor="middle">0.44 jobs/s</text>
<rect x="513.3" y="252.3" width="67.6" height="5.7" fill="#0284c7" rx="3"/>
<text x="547.1" y="247.3" class="bar-label" text-anchor="middle">0.45 jobs/s</text>
<rect x="595.7" y="252.2" width="67.6" height="5.8" fill="#f59e0b" rx="3"/>
<text x="629.5" y="247.2" class="bar-label" text-anchor="middle">0.46 jobs/s</text>
<text x="571.0" y="282" class="axis" text-anchor="middle">huge_few</text>
<rect x="64" y="298" width="11" height="11" fill="#64748b" rx="2"/>
<text x="80" y="308" class="axis">serial</text>
<rect x="154" y="298" width="11" height="11" fill="#0284c7" rx="2"/>
<text x="170" y="308" class="axis">balanced</text>
<rect x="244" y="298" width="11" height="11" fill="#f59e0b" rx="2"/>
<text x="260" y="308" class="axis">eager</text>
<text x="740" y="308" class="axis" text-anchor="end">higher is better</text>
</svg></section>
<section class="card chart"><svg viewBox="0 0 760 320" role="img" aria-label="p95 time-to-ready: от 202 до ready">
<text x="64" y="24" class="chart-title">p95 time-to-ready: от 202 до ready</text>
<text x="64" y="42" class="chart-sub">95% заданий стали ready быстрее этого времени (меньше — лучше).</text>
<line x1="64" y1="258.0" x2="740" y2="258.0" class="grid"/>
<text x="54" y="262.0" class="axis" text-anchor="end">0 ms</text>
<line x1="64" y1="206.5" x2="740" y2="206.5" class="grid"/>
<text x="54" y="210.5" class="axis" text-anchor="end">7606 ms</text>
<line x1="64" y1="155.0" x2="740" y2="155.0" class="grid"/>
<text x="54" y="159.0" class="axis" text-anchor="end">15213 ms</text>
<line x1="64" y1="103.5" x2="740" y2="103.5" class="grid"/>
<text x="54" y="107.5" class="axis" text-anchor="end">22819 ms</text>
<line x1="64" y1="52.0" x2="740" y2="52.0" class="grid"/>
<text x="54" y="56.0" class="axis" text-anchor="end">30426 ms</text>
<rect x="92.9" y="235.8" width="67.6" height="22.2" fill="#64748b" rx="3"/>
<text x="126.7" y="230.8" class="bar-label" text-anchor="middle">3284 ms</text>
<rect x="175.3" y="246.2" width="67.6" height="11.8" fill="#0284c7" rx="3"/>
<text x="209.1" y="241.2" class="bar-label" text-anchor="middle">1736 ms</text>
<rect x="257.7" y="250.2" width="67.6" height="7.8" fill="#f59e0b" rx="3"/>
<text x="291.5" y="245.2" class="bar-label" text-anchor="middle">1158 ms</text>
<text x="233.0" y="282" class="axis" text-anchor="middle">small_many</text>
<rect x="430.9" y="85.2" width="67.6" height="172.8" fill="#64748b" rx="3"/>
<text x="464.7" y="80.2" class="bar-label" text-anchor="middle">25521 ms</text>
<rect x="513.3" y="83.4" width="67.6" height="174.6" fill="#0284c7" rx="3"/>
<text x="547.1" y="78.4" class="bar-label" text-anchor="middle">25785 ms</text>
<rect x="595.7" y="84.0" width="67.6" height="174.0" fill="#f59e0b" rx="3"/>
<text x="629.5" y="79.0" class="bar-label" text-anchor="middle">25699 ms</text>
<text x="571.0" y="282" class="axis" text-anchor="middle">huge_few</text>
<rect x="64" y="298" width="11" height="11" fill="#64748b" rx="2"/>
<text x="80" y="308" class="axis">serial</text>
<rect x="154" y="298" width="11" height="11" fill="#0284c7" rx="2"/>
<text x="170" y="308" class="axis">balanced</text>
<rect x="244" y="298" width="11" height="11" fill="#f59e0b" rx="2"/>
<text x="260" y="308" class="axis">eager</text>
<text x="740" y="308" class="axis" text-anchor="end">lower is better</text>
</svg></section>
<section class="card chart"><svg viewBox="0 0 760 320" role="img" aria-label="p95 queue lag: ожидание до старта обработки">
<text x="64" y="24" class="chart-title">p95 queue lag: ожидание до старта обработки</text>
<text x="64" y="42" class="chart-sub">Время между durable 202 и первым claim worker-а (меньше — лучше).</text>
<line x1="64" y1="258.0" x2="740" y2="258.0" class="grid"/>
<text x="54" y="262.0" class="axis" text-anchor="end">0 ms</text>
<line x1="64" y1="206.5" x2="740" y2="206.5" class="grid"/>
<text x="54" y="210.5" class="axis" text-anchor="end">6883 ms</text>
<line x1="64" y1="155.0" x2="740" y2="155.0" class="grid"/>
<text x="54" y="159.0" class="axis" text-anchor="end">13766 ms</text>
<line x1="64" y1="103.5" x2="740" y2="103.5" class="grid"/>
<text x="54" y="107.5" class="axis" text-anchor="end">20650 ms</text>
<line x1="64" y1="52.0" x2="740" y2="52.0" class="grid"/>
<text x="54" y="56.0" class="axis" text-anchor="end">27533 ms</text>
<rect x="92.9" y="234.1" width="67.6" height="23.9" fill="#64748b" rx="3"/>
<text x="126.7" y="229.1" class="bar-label" text-anchor="middle">3194 ms</text>
<rect x="175.3" y="245.9" width="67.6" height="12.1" fill="#0284c7" rx="3"/>
<text x="209.1" y="240.9" class="bar-label" text-anchor="middle">1624 ms</text>
<rect x="257.7" y="251.3" width="67.6" height="6.7" fill="#f59e0b" rx="3"/>
<text x="291.5" y="246.3" class="bar-label" text-anchor="middle">898 ms</text>
<text x="233.0" y="282" class="axis" text-anchor="middle">small_many</text>
<rect x="430.9" y="83.4" width="67.6" height="174.6" fill="#64748b" rx="3"/>
<text x="464.7" y="78.4" class="bar-label" text-anchor="middle">23333 ms</text>
<rect x="513.3" y="125.4" width="67.6" height="132.6" fill="#0284c7" rx="3"/>
<text x="547.1" y="120.4" class="bar-label" text-anchor="middle">17716 ms</text>
<rect x="595.7" y="126.8" width="67.6" height="131.2" fill="#f59e0b" rx="3"/>
<text x="629.5" y="121.8" class="bar-label" text-anchor="middle">17538 ms</text>
<text x="571.0" y="282" class="axis" text-anchor="middle">huge_few</text>
<rect x="64" y="298" width="11" height="11" fill="#64748b" rx="2"/>
<text x="80" y="308" class="axis">serial</text>
<rect x="154" y="298" width="11" height="11" fill="#0284c7" rx="2"/>
<text x="170" y="308" class="axis">balanced</text>
<rect x="244" y="298" width="11" height="11" fill="#f59e0b" rx="2"/>
<text x="260" y="308" class="axis">eager</text>
<text x="740" y="308" class="axis" text-anchor="end">lower is better</text>
</svg></section>
<section class="card chart"><svg viewBox="0 0 760 320" role="img" aria-label="Пиковый RSS worker">
<text x="64" y="24" class="chart-title">Пиковый RSS worker</text>
<text x="64" y="42" class="chart-sub">VmRSS процесса worker во время задания (меньше — экономнее).</text>
<line x1="64" y1="258.0" x2="740" y2="258.0" class="grid"/>
<text x="54" y="262.0" class="axis" text-anchor="end">0 MiB</text>
<line x1="64" y1="206.5" x2="740" y2="206.5" class="grid"/>
<text x="54" y="210.5" class="axis" text-anchor="end">331 MiB</text>
<line x1="64" y1="155.0" x2="740" y2="155.0" class="grid"/>
<text x="54" y="159.0" class="axis" text-anchor="end">662 MiB</text>
<line x1="64" y1="103.5" x2="740" y2="103.5" class="grid"/>
<text x="54" y="107.5" class="axis" text-anchor="end">993 MiB</text>
<line x1="64" y1="52.0" x2="740" y2="52.0" class="grid"/>
<text x="54" y="56.0" class="axis" text-anchor="end">1324 MiB</text>
<rect x="92.9" y="253.6" width="67.6" height="4.4" fill="#64748b" rx="3"/>
<text x="126.7" y="248.6" class="bar-label" text-anchor="middle">28 MiB</text>
<rect x="175.3" y="253.2" width="67.6" height="4.8" fill="#0284c7" rx="3"/>
<text x="209.1" y="248.2" class="bar-label" text-anchor="middle">31 MiB</text>
<rect x="257.7" y="252.9" width="67.6" height="5.1" fill="#f59e0b" rx="3"/>
<text x="291.5" y="247.9" class="bar-label" text-anchor="middle">33 MiB</text>
<text x="233.0" y="282" class="axis" text-anchor="middle">small_many</text>
<rect x="430.9" y="226.2" width="67.6" height="31.8" fill="#64748b" rx="3"/>
<text x="464.7" y="221.2" class="bar-label" text-anchor="middle">205 MiB</text>
<rect x="513.3" y="144.6" width="67.6" height="113.4" fill="#0284c7" rx="3"/>
<text x="547.1" y="139.6" class="bar-label" text-anchor="middle">729 MiB</text>
<rect x="595.7" y="83.4" width="67.6" height="174.6" fill="#f59e0b" rx="3"/>
<text x="629.5" y="78.4" class="bar-label" text-anchor="middle">1122 MiB</text>
<text x="571.0" y="282" class="axis" text-anchor="middle">huge_few</text>
<rect x="64" y="298" width="11" height="11" fill="#64748b" rx="2"/>
<text x="80" y="308" class="axis">serial</text>
<rect x="154" y="298" width="11" height="11" fill="#0284c7" rx="2"/>
<text x="170" y="308" class="axis">balanced</text>
<rect x="244" y="298" width="11" height="11" fill="#f59e0b" rx="2"/>
<text x="260" y="308" class="axis">eager</text>
<text x="740" y="308" class="axis" text-anchor="end">lower is better</text>
</svg></section>
<section class="card">
<h2>Полная матрица</h2>
<table>
<thead><tr><th>Профиль</th><th>Сценарий</th><th>Jobs</th><th>Jobs/s</th><th>Queue lag p95, ms</th><th>Ready p95, ms</th><th>Processing p95, ms</th><th>RSS peak, MiB</th><th>Max parallel</th><th>Max backlog</th></tr></thead>
<tbody><tr><td>serial</td><td>small_many</td><td>30</td><td>6.88</td><td>3194</td><td>3284</td><td>152</td><td>28</td><td>1</td><td>27</td></tr><tr><td>serial</td><td>huge_few</td><td>12</td><td>0.44</td><td>23333</td><td>25521</td><td>2311</td><td>205</td><td>1</td><td>12</td></tr><tr><td>balanced</td><td>small_many</td><td>30</td><td>11.59</td><td>1624</td><td>1736</td><td>336</td><td>31</td><td>4</td><td>26</td></tr><tr><td>balanced</td><td>huge_few</td><td>12</td><td>0.45</td><td>17716</td><td>25785</td><td>8710</td><td>729</td><td>4</td><td>12</td></tr><tr><td>eager</td><td>small_many</td><td>30</td><td>13.86</td><td>898</td><td>1158</td><td>566</td><td>33</td><td>8</td><td>26</td></tr><tr><td>eager</td><td>huge_few</td><td>12</td><td>0.46</td><td>17538</td><td>25699</td><td>17320</td><td>1122</td><td>8</td><td>12</td></tr></tbody>
</table>
<p class="note">Queue lag = <code>processing_started_at - created_at</code>.
Time-to-ready = <code>finished_at - created_at</code>. Processing = <code>finished_at - processing_started_at</code>.
RSS — VmRSS процесса worker, сэмплирование примерно каждые 100 мс.
Max parallel — максимум одновременно обрабатываемых заданий; max backlog —
максимум принятых, но ещё не готовых заданий.</p>
</section>
<section class="card">
<h2>Backpressure и восстановление</h2>
<p>Перед этим прогоном API пересоздан с <code>MAX_PENDING_JOBS=3</code>, worker
остановлен. Последовательные upload-ы показывают, где заканчивается принятая
работа. Затем worker запускается, принятые задания должны дойти до ready.</p>
<table>
<thead><tr><th>#</th><th>HTTP</th><th>Latency, ms</th><th>Retry-After</th><th>Error code</th></tr></thead>
<tbody><tr><td>1</td><td class="ok">202</td><td>18.2</td><td>—</td><td>—</td></tr><tr><td>2</td><td class="ok">202</td><td>17.4</td><td>—</td><td>—</td></tr><tr><td>3</td><td class="ok">202</td><td>10.8</td><td>—</td><td>—</td></tr><tr><td>4</td><td class="blocked">503</td><td>3.9</td><td>5</td><td>unavailable</td></tr></tbody>
</table>
<p class="note">Recovery: 3 принятых заданий
стали ready за 7.60 с после старта worker.
Финальный probe upload: HTTP 202 → ready.</p>
</section>
<section class="card">
<h2>Что это значит</h2>
<ul><li>small_many: eager быстрее serial в 2.0× по throughput.</li><li>small_many: пиковый RSS eager относится к serial как 1.2×.</li><li>huge_few: throughput eager и serial практически одинаков.</li><li>huge_few: пиковый RSS eager относится к serial как 5.5×.</li><li>При balanced p95 time-to-ready для huge_few в 14.9× больше, чем для small_many: размер изображения меняет стоимость задания, а не только число заданий.</li><li>На huge_few eager почти не поднял throughput (1.04×): worker ограничен 1.0 CPU, а декодирование и масштабирование упираются в CPU. Concurrency снижает queue lag, но при этом растёт RSS; это и есть компромисс latency/ресурсы, а не бесплатное ускорение.</li><li>serial ограничивает одновременно обрабатываемые задания одним, поэтому queue lag растёт, но RSS остаётся минимальным. eager держит больше заданий в работе и в prefetch-окне брокера.</li><li>Backpressure: при MAX_PENDING_JOBS=3 API принял 3 задания, затем вернул 503 с Retry-After=5; после старта worker очередь восстановилась за 7.6 с.</li></ul>
</section>
<section class="card">
<h2>Ограничения</h2>
<ul>
<li>Один worker, один RabbitMQ и один PostgreSQL: это сравнение настроек, а не
HA-кластер. Числа зависят от CPU/диска конкретной машины.</li>
<li>PNG-фикстуры синтетические и хорошо сжимаются; доминирует стоимость декодирования
и масштабирования, а не передача по сети. Размер в байтах указан в JSON.</li>
<li>RSS сэмплируется из <code>/proc/1/status</code>; короткий прогон не заменяет
длительный memory profile и p99.</li>
<li>Backpressure cap приблизительный: каждая API-реплика считает pending-задания
по общей БД, но проверка и вставка не являются одной транзакцией.</li>
</ul>
</section>
</main>
</body>
</html>
+1306
View File
File diff suppressed because it is too large Load Diff
+16
View File
@@ -0,0 +1,16 @@
# Lab5 track 1 — queue under load
Generated: `2026-11-14T21:42:03.122104+00:00`
Synthetic images; no tokens or credentials are stored.
| Profile | Scenario | Jobs | Jobs/s | Queue lag p95, ms | Ready p95, ms | RSS peak, MiB |
| --- | --- | ---: | ---: | ---: | ---: | ---: |
| serial | small_many | 30 | 6.88 | 3194 | 3284 | 28 |
| serial | huge_few | 12 | 0.44 | 23333 | 25521 | 205 |
| balanced | small_many | 30 | 11.59 | 1624 | 1736 | 31 |
| balanced | huge_few | 12 | 0.45 | 17716 | 25785 | 729 |
| eager | small_many | 30 | 13.86 | 898 | 1158 | 33 |
| eager | huge_few | 12 | 0.46 | 17538 | 25699 | 1122 |
Backpressure: cap=3, accepted=3, first 503 Retry-After=5, recovery=7.60s, probe HTTP 202.
+1070
View File
File diff suppressed because it is too large Load Diff