feat(lab5): add exactly_right scenario and refresh evidence

This commit is contained in:
Mikhail Verkovykh
2026-11-20 19:05:29 +03:00
parent d0f533b371
commit b6953ae6ee
7 changed files with 2529 additions and 675 deletions
+15 -2
View File
@@ -26,14 +26,27 @@
для 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 прогон;
`serial/balanced/eager` × `small_many`/`exactly_right`/`huge_few`,
throughput, queue lag, p95 time-to-ready, RSS, декомпозиция
decode/scale/JPEG/WebP и отдельный backpressure/recovery прогон;
self-contained HTML-дашборд с inline SVG.
- `exactly_right` (1280×1280): optimized WebP кодируется без scaling, поэтому
encode share показывает нижнюю границу стоимости сжатия.
- Документация: README с запуском и архитектурой, отчёт с таблицей критериев,
CHANGELOG.
### Removed
- 34 устаревших файла `*.lab3`/`*.lab4` (Makefile, contracts, tests, scripts,
CI templates и fixtures) удалены из рабочего дерева.
### Changed
- Параметры вариантов (`ThumbnailMax`, `CropSize`, `OptimizedMax`, качества
JPEG/WebP и WebP method) перенесены в `app/internal/config/config.go`.
- Комментарии в Go/SQL/shell/Python больше не ссылаются на номера лабораторных;
поведение описывается по существу.
- `POST /chats/{id}/attachments` отвечает `202` после durable staging и COMMIT
задания; готовность определяется опросом метаданных, content до `ready` — 409.
- Загрузка потоковая (буфер 32 KiB), лимиты bytes/pixels проверяются до
+15 -14
View File
@@ -150,35 +150,36 @@ python3 scripts/track1_experiment.py # трек 1 уров
`make test-persistence` / `make test-failover` с `scripts/restart.sh` и
`scripts/stop-one.sh`; см. `evidence/lab5-persistence*` и `evidence/lab5-failover.txt`.
Трек 1 запускает матрицу профилей `serial/balanced/eager` на маленьких и
больших изображениях, измеряет throughput, queue lag, p95 time-to-ready и RSS,
затем отдельно показывает backpressure и восстановление. Результаты и графики —
Трек 1 запускает матрицу `serial/balanced/eager` на трёх размерах:
`small_many` (192×128), `exactly_right` (1280×1280, optimized WebP без scaling)
и `huge_few` (2400×1800). Метрики: throughput, queue lag, p95 time-to-ready,
RSS и разложение времени на decode / scale / JPEG / WebP. Результаты и графики —
`evidence/track1.{json,html,md}`, разбор — в [REPORT.md](REPORT.md).
```sh
# Полный прогон: 30 small + 12 huge на каждый профиль, затем backpressure.
# Полный прогон: 30 small + 18 exactly_right + 12 huge на профиль.
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
python3 scripts/track1_experiment.py --small-jobs 5 --exactly-jobs 3 --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.
поднимает memory limit до 2 GiB (чтобы `eager` не падал по OOM), а в `finally`
возвращает конфигурацию из `.env`. Он управляет только локальным Compose-стендом.
Кратко: на 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.
Кратко: на 192×128 eager дал 15.58 jobs/s против 6.84 у serial (2.3×) при RSS
28→32 MiB. На 1280×1280 и 2400×1800 все профили дали ~0.44–0.50 jobs/s:
worker ограничен 1 CPU, а encode share составил 82–83% и 61–64% — сжатие, а не
только scaling, задаёт нижнюю границу. RSS вырос до 818–950 MiB, queue lag p95
упал, но ready p95 остался ~26–36 s. При `MAX_PENDING_JOBS=3` API вернул
`503` + `Retry-After: 5`; после старта worker принятые задания стали ready за
7.65 s.
## Ограничения
+53 -80
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` | 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` |
| Трек 1, уровень 5 | `python3 scripts/track1_experiment.py` | 3 профиля × 3 размера; eager/small 15.58 jobs/s против serial 6.84; exactly_right/huge_few ~0.44–0.50 jobs/s, encode share 83% против 61–64%; RSS до 950 MiB; 503 + Retry-After 5, recovery 7.653 s | `evidence/track1.json`, `evidence/track1.html` |
## Эксперименты и отказы
@@ -143,42 +143,32 @@ HAProxy; отказ БД или брокера в этом сценарии не
<!-- TRACK1:START -->
### Гипотеза
Маленькие изображения, которые не требуют масштабирования, дешевле на задание:
выше throughput и ниже RSS. Большие изображения (2400×1800) требуют декодирования
и downscale до 1280×960, поэтому очередь растёт, p95 time-to-ready увеличивается,
а память сильнее зависит от concurrency. Дополнительно проверялся компромисс
«latency против ресурсов»: больше concurrency/prefetch должно снижать queue lag,
но повышать RSS.
Стоимость задания = decode + scaling + encode. `exactly_right` (1280×1280) не
масштабирует optimized WebP и показывает нижнюю границу стоимости сжатия;
`huge_few` добавляет downscale. Ожидаем: на тяжёлых изображениях concurrency
снижает queue lag, но не throughput при 1 CPU, а 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.
- Профили: `serial` 1/1, `balanced` 4/4, `eager` 8/32 (concurrency/prefetch).
- Сценарии: `small_many` 30×192×128; `exactly_right` 18×1280×1280 (optimized
WebP без scaling); `huge_few` 12×2400×1800 (optimized → 1280×960).
- 9 ячеек; worker пересоздаётся на профиль, изображения загружаются параллельно,
все задания доводятся до терминального состояния.
- Queue lag, time-to-ready и processing — из `attachment_jobs`; throughput =
ready / (последний `finished_at` − первый `created_at`).
- Decode/scale/JPEG/WebP — из worker-лога; encode share =
`encode / (decode + scale + encode)`. Это wall-clock под данным профилем.
- RSS — `VmRSS` из `/proc/1/status` примерно каждые 100 мс.
- Worker 1 CPU, memory limit 2 GiB (в `.env` 1 GiB), чтобы `eager` не падал по
OOM; зафиксировано в JSON.
- Backpressure: `MAX_PENDING_JOBS=3`, worker остановлен, upload-ы до `503`, затем
recovery. Cap выбран намеренно; важны `Retry-After` и отсутствие потерь.
Команда:
```sh
make track1 BASE_URL=http://localhost:8080
# или
python3 scripts/track1_experiment.py --base-url http://localhost:8080
```
Сырые данные: `evidence/track1.json`; графики: `evidence/track1.html`;
@@ -186,63 +176,46 @@ python3 scripts/track1_experiment.py --base-url http://localhost:8080
### Результаты
| Профиль | Сценарий | 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 |
| Профиль | Сценарий | Jobs/s | Queue lag p95, ms | Ready p95, ms | Processing p95, ms | Encode p95, ms | Encode share, % | RSS peak, MiB | Max parallel |
| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| serial | small_many | 6.837 | 3 256 | 3 338 | 170 | 80 | 83.8 | 28.2 | 1 |
| serial | exactly_right | 0.475 | 33 591 | 35 714 | 2 180 | 1 722 | 82.0 | 174.3 | 1 |
| serial | huge_few | 0.436 | 23 668 | 25 896 | 2 359 | 1 508 | 63.8 | 212.9 | 1 |
| balanced | small_many | 13.694 | 1 147 | 1 274 | 396 | 90 | 83.8 | 28.9 | 4 |
| balanced | exactly_right | 0.495 | 31 510 | 35 764 | 8 174 | 6 562 | 83.1 | 433.8 | 4 |
| balanced | huge_few | 0.441 | 18 161 | 26 576 | 9 046 | 5 606 | 61.4 | 756.4 | 4 |
| eager | small_many | 15.576 | 924 | 1 166 | 410 | 95 | 79.9 | 32.1 | 8 |
| eager | exactly_right | 0.495 | 31 735 | 35 797 | 16 363 | 13 330 | 83.1 | 818.4 | 8 |
| eager | huge_few | 0.443 | 17 648 | 26 641 | 17 678 | 11 124 | 61.4 | 949.6 | 8 |
Backpressure: cap `3`; первые 3 upload-а получили `202`, четвёртый — `503` с
`Retry-After: 5` и `error_code=unavailable`. После старта worker три принятых
задания стали `ready` за **7.596 s** (включая запуск контейнера и healthcheck),
после чего probe upload получил `202` и дошёл до `ready`.
Backpressure: cap `3` задан намеренно; первый `503` пришёл с `Retry-After: 5`.
После старта worker принятые задания стали `ready` за **7.653 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-а и не увеличивает параллельную
обработку.
1. **Compression, not scaling, is the floor.** `exactly_right` даёт 82–83%
encode share и ~0.48 jobs/s; `huge_few` — 61–64% и ~0.44 jobs/s. Убрать
downscale недостаточно, чтобы 1280×1280 стал дешёвым: доминирует WebP.
На `huge_few` scale p95 выше (balanced: 3.4 s против 1.5 s), но optimized
output меньше (1.23 MP против 1.64 MP), поэтому throughput почти совпадает.
2. **Маленькие изображения масштабируются concurrency.** 6.84 → 13.69 →
15.58 jobs/s, RSS 28 → 32 MiB.
3. **Тяжёлые изображения CPU-bound.** ~0.44–0.50 jobs/s у всех профилей;
queue lag падает, ready p95 держится ~26–36 s, RSS растёт 174 → 818 MiB
(`exactly_right`) и 213 → 950 MiB (`huge_few`). Concurrency покупает latency
ценой памяти, а не throughput.
4. **Backpressure.** `503` + `Retry-After: 5`; принятые задания восстановились
за 7.65 s.
5. **Практический выбор.** `balanced` для тяжёлых, `eager` для лёгких.
### Ограничения эксперимента
### Ограничения
- Один 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, поэтому это верхняя оценка, а не время чистой обработки.
- `exactly_right` кодирует 1.64 MP WebP, `huge_few` после downscale — ~1.23 MP:
сценарий убирает scaling, но не уравнивает объём encode.
- PNG-фикстуры синтетические; один прогон на ячейку, p95 по 12–18 заданиям
чувствителен к выбросу.
- Время recovery включает `docker compose start` и healthcheck.
<!-- TRACK1:END -->
## Ограничения и следующие шаги
+178 -95
View File
@@ -49,18 +49,18 @@ code { background: #f1f5f9; padding: 1px 5px; border-radius: 4px; }
<body>
<main>
<h1>Lab5, трек 1: очередь под перегрузкой</h1>
<p class="lead">Сгенерировано 2026-11-14T21:42:03.122104+00:00. Стенд: http://172.18.0.1:8080,
<p class="lead">Сгенерировано 2026-11-20T16:02:07.856909+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.
<strong>Гипотеза.</strong> Стоимость задания складывается из decode, масштабирования
и сжатия. <em>exactly_right</em> (1280×1280) не масштабирует optimized-вариант,
поэтому показывает нижнюю границу стоимости сжатия; <em>huge_few</em> добавляет
downscale, а <em>small_many</em> почти не масштабируется, но и пикселей в нём
мало. Большие изображения при том же числе worker-ов увеличивают очередь,
p95 time-to-ready и RSS. Одновременно проверяем компромисс: <em>eager</em>
уменьшает ожидание, но повышает память; <em>serial</em> экономит память, но
ограничивает throughput.
</section>
<section class="card">
@@ -72,16 +72,15 @@ throughput.
</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>
small_many — 192×128, 30 jobs, many small images; almost no scaling; exactly_right — 1280×1280, 18 jobs, largest variant encodes at native 1280, so no scaling on the WebP path; 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 class="metric"><div class="value">9</div><div class="label">прогонов матрицы</div></div>
<div class="metric"><div class="value">950 MiB</div><div class="label">максимальный RSS worker</div></div>
<div class="metric"><div class="value">7.7 s</div><div class="label">восстановление после backpressure</div></div>
</div>
</section>
@@ -91,27 +90,34 @@ small_many — 192×128, 30 jobs, many small images; variants fit or crop withou
<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>
<text x="54" y="210.5" class="axis" text-anchor="end">5 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>
<text x="54" y="159.0" class="axis" text-anchor="end">9 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>
<text x="54" y="107.5" class="axis" text-anchor="end">14 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>
<text x="54" y="56.0" class="axis" text-anchor="end">18 jobs/s</text>
<rect x="83.2" y="181.4" width="45.1" height="76.6" fill="#64748b" rx="3"/>
<text x="105.8" y="176.4" class="bar-label" text-anchor="middle">6.84 jobs/s</text>
<rect x="138.2" y="104.5" width="45.1" height="153.5" fill="#0284c7" rx="3"/>
<text x="160.7" y="99.5" class="bar-label" text-anchor="middle">13.69 jobs/s</text>
<rect x="193.2" y="83.4" width="45.1" height="174.6" fill="#f59e0b" rx="3"/>
<text x="215.7" y="78.4" class="bar-label" text-anchor="middle">15.58 jobs/s</text>
<text x="176.7" y="282" class="axis" text-anchor="middle">small_many</text>
<rect x="308.6" y="252.7" width="45.1" height="5.3" fill="#64748b" rx="3"/>
<text x="331.1" y="247.7" class="bar-label" text-anchor="middle">0.47 jobs/s</text>
<rect x="363.5" y="252.5" width="45.1" height="5.5" fill="#0284c7" rx="3"/>
<text x="386.1" y="247.5" class="bar-label" text-anchor="middle">0.49 jobs/s</text>
<rect x="418.5" y="252.5" width="45.1" height="5.5" fill="#f59e0b" rx="3"/>
<text x="441.0" y="247.5" class="bar-label" text-anchor="middle">0.49 jobs/s</text>
<text x="402.0" y="282" class="axis" text-anchor="middle">exactly_right</text>
<rect x="533.9" y="253.1" width="45.1" height="4.9" fill="#64748b" rx="3"/>
<text x="556.4" y="248.1" class="bar-label" text-anchor="middle">0.44 jobs/s</text>
<rect x="588.9" y="253.1" width="45.1" height="4.9" fill="#0284c7" rx="3"/>
<text x="611.4" y="248.1" class="bar-label" text-anchor="middle">0.44 jobs/s</text>
<rect x="643.8" y="253.0" width="45.1" height="5.0" fill="#f59e0b" rx="3"/>
<text x="666.4" y="248.0" class="bar-label" text-anchor="middle">0.44 jobs/s</text>
<text x="627.3" 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"/>
@@ -126,27 +132,34 @@ small_many — 192×128, 30 jobs, many small images; variants fit or crop withou
<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>
<text x="54" y="210.5" class="axis" text-anchor="end">10560 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>
<text x="54" y="159.0" class="axis" text-anchor="end">21120 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>
<text x="54" y="107.5" class="axis" text-anchor="end">31680 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>
<text x="54" y="56.0" class="axis" text-anchor="end">42240 ms</text>
<rect x="83.2" y="241.7" width="45.1" height="16.3" fill="#64748b" rx="3"/>
<text x="105.8" y="236.7" class="bar-label" text-anchor="middle">3338 ms</text>
<rect x="138.2" y="251.8" width="45.1" height="6.2" fill="#0284c7" rx="3"/>
<text x="160.7" y="246.8" class="bar-label" text-anchor="middle">1274 ms</text>
<rect x="193.2" y="252.3" width="45.1" height="5.7" fill="#f59e0b" rx="3"/>
<text x="215.7" y="247.3" class="bar-label" text-anchor="middle">1166 ms</text>
<text x="176.7" y="282" class="axis" text-anchor="middle">small_many</text>
<rect x="308.6" y="83.8" width="45.1" height="174.2" fill="#64748b" rx="3"/>
<text x="331.1" y="78.8" class="bar-label" text-anchor="middle">35714 ms</text>
<rect x="363.5" y="83.6" width="45.1" height="174.4" fill="#0284c7" rx="3"/>
<text x="386.1" y="78.6" class="bar-label" text-anchor="middle">35764 ms</text>
<rect x="418.5" y="83.4" width="45.1" height="174.6" fill="#f59e0b" rx="3"/>
<text x="441.0" y="78.4" class="bar-label" text-anchor="middle">35797 ms</text>
<text x="402.0" y="282" class="axis" text-anchor="middle">exactly_right</text>
<rect x="533.9" y="131.7" width="45.1" height="126.3" fill="#64748b" rx="3"/>
<text x="556.4" y="126.7" class="bar-label" text-anchor="middle">25896 ms</text>
<rect x="588.9" y="128.4" width="45.1" height="129.6" fill="#0284c7" rx="3"/>
<text x="611.4" y="123.4" class="bar-label" text-anchor="middle">26576 ms</text>
<rect x="643.8" y="128.1" width="45.1" height="129.9" fill="#f59e0b" rx="3"/>
<text x="666.4" y="123.1" class="bar-label" text-anchor="middle">26641 ms</text>
<text x="627.3" 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"/>
@@ -161,27 +174,34 @@ small_many — 192×128, 30 jobs, many small images; variants fit or crop withou
<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>
<text x="54" y="210.5" class="axis" text-anchor="end">9909 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>
<text x="54" y="159.0" class="axis" text-anchor="end">19819 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>
<text x="54" y="107.5" class="axis" text-anchor="end">29728 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>
<text x="54" y="56.0" class="axis" text-anchor="end">39637 ms</text>
<rect x="83.2" y="241.1" width="45.1" height="16.9" fill="#64748b" rx="3"/>
<text x="105.8" y="236.1" class="bar-label" text-anchor="middle">3256 ms</text>
<rect x="138.2" y="252.0" width="45.1" height="6.0" fill="#0284c7" rx="3"/>
<text x="160.7" y="247.0" class="bar-label" text-anchor="middle">1147 ms</text>
<rect x="193.2" y="253.2" width="45.1" height="4.8" fill="#f59e0b" rx="3"/>
<text x="215.7" y="248.2" class="bar-label" text-anchor="middle">924 ms</text>
<text x="176.7" y="282" class="axis" text-anchor="middle">small_many</text>
<rect x="308.6" y="83.4" width="45.1" height="174.6" fill="#64748b" rx="3"/>
<text x="331.1" y="78.4" class="bar-label" text-anchor="middle">33591 ms</text>
<rect x="363.5" y="94.2" width="45.1" height="163.8" fill="#0284c7" rx="3"/>
<text x="386.1" y="89.2" class="bar-label" text-anchor="middle">31510 ms</text>
<rect x="418.5" y="93.1" width="45.1" height="164.9" fill="#f59e0b" rx="3"/>
<text x="441.0" y="88.1" class="bar-label" text-anchor="middle">31735 ms</text>
<text x="402.0" y="282" class="axis" text-anchor="middle">exactly_right</text>
<rect x="533.9" y="135.0" width="45.1" height="123.0" fill="#64748b" rx="3"/>
<text x="556.4" y="130.0" class="bar-label" text-anchor="middle">23668 ms</text>
<rect x="588.9" y="163.6" width="45.1" height="94.4" fill="#0284c7" rx="3"/>
<text x="611.4" y="158.6" class="bar-label" text-anchor="middle">18161 ms</text>
<rect x="643.8" y="166.3" width="45.1" height="91.7" fill="#f59e0b" rx="3"/>
<text x="666.4" y="161.3" class="bar-label" text-anchor="middle">17648 ms</text>
<text x="627.3" 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"/>
@@ -196,27 +216,76 @@ small_many — 192×128, 30 jobs, many small images; variants fit or crop withou
<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>
<text x="54" y="210.5" class="axis" text-anchor="end">280 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>
<text x="54" y="159.0" class="axis" text-anchor="end">560 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>
<text x="54" y="107.5" class="axis" text-anchor="end">840 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>
<text x="54" y="56.0" class="axis" text-anchor="end">1121 MiB</text>
<rect x="83.2" y="252.8" width="45.1" height="5.2" fill="#64748b" rx="3"/>
<text x="105.8" y="247.8" class="bar-label" text-anchor="middle">28 MiB</text>
<rect x="138.2" y="252.7" width="45.1" height="5.3" fill="#0284c7" rx="3"/>
<text x="160.7" y="247.7" class="bar-label" text-anchor="middle">29 MiB</text>
<rect x="193.2" y="252.1" width="45.1" height="5.9" fill="#f59e0b" rx="3"/>
<text x="215.7" y="247.1" class="bar-label" text-anchor="middle">32 MiB</text>
<text x="176.7" y="282" class="axis" text-anchor="middle">small_many</text>
<rect x="308.6" y="226.0" width="45.1" height="32.0" fill="#64748b" rx="3"/>
<text x="331.1" y="221.0" class="bar-label" text-anchor="middle">174 MiB</text>
<rect x="363.5" y="178.2" width="45.1" height="79.8" fill="#0284c7" rx="3"/>
<text x="386.1" y="173.2" class="bar-label" text-anchor="middle">434 MiB</text>
<rect x="418.5" y="107.5" width="45.1" height="150.5" fill="#f59e0b" rx="3"/>
<text x="441.0" y="102.5" class="bar-label" text-anchor="middle">818 MiB</text>
<text x="402.0" y="282" class="axis" text-anchor="middle">exactly_right</text>
<rect x="533.9" y="218.9" width="45.1" height="39.1" fill="#64748b" rx="3"/>
<text x="556.4" y="213.9" class="bar-label" text-anchor="middle">213 MiB</text>
<rect x="588.9" y="118.9" width="45.1" height="139.1" fill="#0284c7" rx="3"/>
<text x="611.4" y="113.9" class="bar-label" text-anchor="middle">756 MiB</text>
<rect x="643.8" y="83.4" width="45.1" height="174.6" fill="#f59e0b" rx="3"/>
<text x="666.4" y="78.4" class="bar-label" text-anchor="middle">950 MiB</text>
<text x="627.3" 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="Compression overhead: доля encode в pipeline CPU">
<text x="64" y="24" class="chart-title">Compression overhead: доля encode в pipeline CPU</text>
<text x="64" y="42" class="chart-sub">encode / (decode + scale + encode), % (меньше — дешевле сжатие).</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 %</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">25 %</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">49 %</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">74 %</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">99 %</text>
<rect x="83.2" y="83.4" width="45.1" height="174.6" fill="#64748b" rx="3"/>
<text x="105.8" y="78.4" class="bar-label" text-anchor="middle">83.8 %</text>
<rect x="138.2" y="83.4" width="45.1" height="174.6" fill="#0284c7" rx="3"/>
<text x="160.7" y="78.4" class="bar-label" text-anchor="middle">83.8 %</text>
<rect x="193.2" y="91.5" width="45.1" height="166.5" fill="#f59e0b" rx="3"/>
<text x="215.7" y="86.5" class="bar-label" text-anchor="middle">79.9 %</text>
<text x="176.7" y="282" class="axis" text-anchor="middle">small_many</text>
<rect x="308.6" y="87.2" width="45.1" height="170.8" fill="#64748b" rx="3"/>
<text x="331.1" y="82.2" class="bar-label" text-anchor="middle">82.0 %</text>
<rect x="363.5" y="84.9" width="45.1" height="173.1" fill="#0284c7" rx="3"/>
<text x="386.1" y="79.9" class="bar-label" text-anchor="middle">83.1 %</text>
<rect x="418.5" y="84.9" width="45.1" height="173.1" fill="#f59e0b" rx="3"/>
<text x="441.0" y="79.9" class="bar-label" text-anchor="middle">83.1 %</text>
<text x="402.0" y="282" class="axis" text-anchor="middle">exactly_right</text>
<rect x="533.9" y="125.1" width="45.1" height="132.9" fill="#64748b" rx="3"/>
<text x="556.4" y="120.1" class="bar-label" text-anchor="middle">63.8 %</text>
<rect x="588.9" y="130.1" width="45.1" height="127.9" fill="#0284c7" rx="3"/>
<text x="611.4" y="125.1" class="bar-label" text-anchor="middle">61.4 %</text>
<rect x="643.8" y="130.1" width="45.1" height="127.9" fill="#f59e0b" rx="3"/>
<text x="666.4" y="125.1" class="bar-label" text-anchor="middle">61.4 %</text>
<text x="627.3" 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"/>
@@ -229,11 +298,16 @@ small_many — 192×128, 30 jobs, many small images; variants fit or crop withou
<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>
<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>Encode p95, ms</th><th>Encode share, %</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.84</td><td>3256</td><td>3338</td><td>170</td><td>80</td><td>83.8</td><td>28</td><td>1</td><td>27</td></tr><tr><td>serial</td><td>exactly_right</td><td>18</td><td>0.47</td><td>33591</td><td>35714</td><td>2180</td><td>1722</td><td>82.0</td><td>174</td><td>1</td><td>18</td></tr><tr><td>serial</td><td>huge_few</td><td>12</td><td>0.44</td><td>23668</td><td>25896</td><td>2359</td><td>1508</td><td>63.8</td><td>213</td><td>1</td><td>12</td></tr><tr><td>balanced</td><td>small_many</td><td>30</td><td>13.69</td><td>1147</td><td>1274</td><td>396</td><td>90</td><td>83.8</td><td>29</td><td>4</td><td>24</td></tr><tr><td>balanced</td><td>exactly_right</td><td>18</td><td>0.49</td><td>31510</td><td>35764</td><td>8174</td><td>6562</td><td>83.1</td><td>434</td><td>4</td><td>18</td></tr><tr><td>balanced</td><td>huge_few</td><td>12</td><td>0.44</td><td>18161</td><td>26576</td><td>9046</td><td>5606</td><td>61.4</td><td>756</td><td>4</td><td>12</td></tr><tr><td>eager</td><td>small_many</td><td>30</td><td>15.58</td><td>924</td><td>1166</td><td>410</td><td>95</td><td>79.9</td><td>32</td><td>8</td><td>22</td></tr><tr><td>eager</td><td>exactly_right</td><td>18</td><td>0.49</td><td>31735</td><td>35797</td><td>16363</td><td>13330</td><td>83.1</td><td>818</td><td>8</td><td>18</td></tr><tr><td>eager</td><td>huge_few</td><td>12</td><td>0.44</td><td>17648</td><td>26641</td><td>17678</td><td>11124</td><td>61.4</td><td>950</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>.
Encode = JPEG thumbnail + JPEG crop + WebP optimized; encode share =
<code>encode / (decode + scale + encode)</code> из worker-лога.
Суммы байт вариантов и оригинала остаются в JSON, но не выносятся в заголовок:
синтетический PNG сжимается слишком хорошо, чтобы отношение байт было честной
метрикой эффективности кодека.
RSS — VmRSS процесса worker, сэмплирование примерно каждые 100 мс.
Max parallel — максимум одновременно обрабатываемых заданий; max backlog —
максимум принятых, но ещё не готовых заданий.</p>
@@ -242,20 +316,22 @@ Max parallel — максимум одновременно обрабатыва
<section class="card">
<h2>Backpressure и восстановление</h2>
<p>Перед этим прогоном API пересоздан с <code>MAX_PENDING_JOBS=3</code>, worker
остановлен. Последовательные upload-ы показывают, где заканчивается принятая
работа. Затем worker запускается, принятые задания должны дойти до ready.</p>
остановлен. Cap выбран намеренно: важно не число принятых заданий, а то, что
API возвращает <code>503</code> с <code>Retry-After</code> и не теряет уже
подтверждённую работу. Затем 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>
<tbody><tr><td>1</td><td class="ok">202</td><td>26.7</td><td>—</td><td>—</td></tr><tr><td>2</td><td class="ok">202</td><td>20.3</td><td>—</td><td>—</td></tr><tr><td>3</td><td class="ok">202</td><td>13.8</td><td>—</td><td>—</td></tr><tr><td>4</td><td class="blocked">503</td><td>2.4</td><td>5</td><td>unavailable</td></tr></tbody>
</table>
<p class="note">Recovery: 3 принятых заданий
стали ready за 7.60 с после старта worker.
стали ready за 7.65 с после старта 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>
<ul><li>small_many: eager быстрее serial в 2.3× по throughput.</li><li>small_many: пиковый RSS eager относится к serial как 1.1×.</li><li>exactly_right: throughput eager и serial практически одинаков.</li><li>exactly_right: пиковый RSS eager относится к serial как 4.7×.</li><li>huge_few: throughput eager и serial практически одинаков.</li><li>huge_few: пиковый RSS eager относится к serial как 4.5×.</li><li>При balanced p95 time-to-ready для huge_few в 20.9× больше, чем для small_many: размер изображения меняет стоимость задания, а не только число заданий.</li><li>Compression vs scaling (balanced): exactly_right — encode share 83.1%, scale p95 1527 ms; huge_few — encode share 61.4%, scale p95 3448 ms. На exactly_right optimized WebP кодируется в native 1280, поэтому это нижняя граница стоимости сжатия; на huge_few к ней добавляется downscale.</li><li>На huge_few eager почти не поднял throughput (1.02×): worker ограничен 1.0 CPU, а декодирование и масштабирование упираются в CPU. Concurrency снижает queue lag, но при этом растёт RSS; это и есть компромисс latency/ресурсы, а не бесплатное ускорение.</li><li>serial ограничивает одновременно обрабатываемые задания одним, поэтому queue lag растёт, но RSS остаётся минимальным. eager держит больше заданий в работе и в prefetch-окне брокера.</li><li>Backpressure: cap=3 выставлен намеренно, поэтому число принятых заданий — следствие настройки, а не открытие. Значимо то, что API вернул 503 с Retry-After=5, а после старта worker очередь восстановилась за 7.7 с.</li></ul>
</section>
<section class="card">
@@ -263,8 +339,15 @@ Max parallel — максимум одновременно обрабатыва
<ul>
<li>Один worker, один RabbitMQ и один PostgreSQL: это сравнение настроек, а не
HA-кластер. Числа зависят от CPU/диска конкретной машины.</li>
<li>PNG-фикстуры синтетические и хорошо сжимаются; доминирует стоимость декодирования
и масштабирования, а не передача по сети. Размер в байтах указан в JSON.</li>
<li>PNG-фикстуры синтетические и хорошо сжимаются; absolute encode time зависит
от паттерна, но сравнение сценариев при одном паттерне остаётся корректным.
Размер в байтах указан в JSON.</li>
<li>Timing-поля читаются из worker-лога. Это wall-clock внутри процесса, поэтому
при concurrency &gt; 1 в них входит и планировщик, что как раз и нужно для
сравнения профилей.</li>
<li>exactly_right кодирует 1.64 MP WebP, а huge_few после downscale — около
1.23 MP. Сценарий убирает scaling, но не уравнивает объём encode; это указано,
чтобы не сравнивать throughput как «одинаковую работу».</li>
<li>RSS сэмплируется из <code>/proc/1/status</code>; короткий прогон не заменяет
длительный memory profile и p99.</li>
<li>Backpressure cap приблизительный: каждая API-реплика считает pending-задания
+2061 -444
View File
File diff suppressed because it is too large Load Diff
+13 -10
View File
@@ -1,16 +1,19 @@
# Lab5 track 1 — queue under load
Generated: `2026-11-14T21:42:03.122104+00:00`
Generated: `2026-11-20T16:02:07.856909+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 |
| Profile | Scenario | Jobs | Jobs/s | Queue lag p95, ms | Ready p95, ms | Encode p95, ms | Encode share, % | RSS peak, MiB |
| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| serial | small_many | 30 | 6.84 | 3256 | 3338 | 80 | 83.8 | 28 |
| serial | exactly_right | 18 | 0.47 | 33591 | 35714 | 1722 | 82.0 | 174 |
| serial | huge_few | 12 | 0.44 | 23668 | 25896 | 1508 | 63.8 | 213 |
| balanced | small_many | 30 | 13.69 | 1147 | 1274 | 90 | 83.8 | 29 |
| balanced | exactly_right | 18 | 0.49 | 31510 | 35764 | 6562 | 83.1 | 434 |
| balanced | huge_few | 12 | 0.44 | 18161 | 26576 | 5606 | 61.4 | 756 |
| eager | small_many | 30 | 15.58 | 924 | 1166 | 95 | 79.9 | 32 |
| eager | exactly_right | 18 | 0.49 | 31735 | 35797 | 13330 | 83.1 | 818 |
| eager | huge_few | 12 | 0.44 | 17648 | 26641 | 11124 | 61.4 | 950 |
Backpressure: cap=3, accepted=3, first 503 Retry-After=5, recovery=7.60s, probe HTTP 202.
Backpressure: cap=3 (deliberate), first 503 Retry-After=5, recovery=7.65s, probe HTTP 202.
+194 -30
View File
@@ -1,13 +1,14 @@
#!/usr/bin/env python3
"""Lab5 grade-5 track 1: queue behaviour under small vs huge images.
"""Track 1: queue behaviour under small, exact and huge images.
The experiment is deliberately short and self-contained:
profiles: serial (concurrency 1, prefetch 1)
balanced (4/4)
eager (8/32)
scenarios: small_many (30 x 192x128 PNG, variants mostly fit without scaling)
huge_few (12 x 2400x1800 PNG, every job needs heavy scaling)
scenarios: small_many (30 x 192x128 PNG, almost no scaling)
exactly_right (18 x 1280x1280 PNG, optimized WebP at native size)
huge_few (12 x 2400x1800 PNG, every path needs heavy scaling)
For each cell the worker is recreated with the profile, the images are uploaded
concurrently, and the script records:
@@ -16,6 +17,8 @@ concurrently, and the script records:
* queue lag: created_at -> processing_started_at (95th percentile),
* time-to-ready: created_at -> finished_at (p50/p95),
* worker RSS baseline/peak sampled from /proc/1/status,
* decode / scale / JPEG / WebP timing from the worker's ready log,
* variant bytes versus the original (compression ratio),
* upload latency and max in-flight jobs.
A final backpressure run caps MAX_PENDING_JOBS at 3, stops the worker, shows
@@ -40,6 +43,7 @@ import json
import math
import os
import platform
import re
import struct
import subprocess
import sys
@@ -79,7 +83,9 @@ PROFILES = [
SCENARIOS = [
{"name": "small_many", "width": 192, "height": 128,
"description": "many small images; variants fit or crop without large scaling"},
"description": "many small images; almost no scaling"},
{"name": "exactly_right", "width": 1280, "height": 1280,
"description": "largest variant encodes at native 1280, so no scaling on the WebP path"},
{"name": "huge_few", "width": 2400, "height": 1800,
"description": "few 4.32 MP images; optimized variant must scale down to 1280"},
]
@@ -330,6 +336,68 @@ def wait_for_terminal(attachment_ids, started_at, timeout=240):
raise Failure(f"jobs did not finish within {timeout}s; last={rows}")
LOGFIELD_RE = re.compile(r'(\w+)=("(?:[^"\\]|\\.)*"|\S+)')
def job_timings(attachment_ids):
"""Read the worker's ready log. The worker is recreated per run, so the
lines belong to this cell; the attachment ID is still checked explicitly."""
if not attachment_ids:
return {}
wanted = set(attachment_ids)
output = compose_capture("logs", "--no-color", "--no-log-prefix", "worker")
timings = {}
for line in output.splitlines():
if 'msg="attachment ready"' not in line:
continue
fields = {key: value.strip('"') for key, value in LOGFIELD_RE.findall(line)}
attachment_id = fields.get("attachment_id")
if attachment_id not in wanted:
continue
try:
timings[attachment_id] = {
name: int(fields[name])
for name in (
"decode_us", "scale_us", "jpeg_encode_us",
"webp_encode_us", "pipeline_us",
)
}
except (KeyError, ValueError):
continue
return timings
def variant_stats(attachment_ids):
"""Variant sizes come from the committed metadata, not from the client."""
if not attachment_ids:
return {}
quoted = ",".join("'" + item + "'" for item in attachment_ids)
sql = (
"SELECT a.id, a.size_bytes, "
"coalesce(sum((v->>'size_bytes')::bigint), 0), "
"coalesce(sum((v->>'size_bytes')::bigint) FILTER (WHERE v->>'name' = 'thumbnail'), 0), "
"coalesce(sum((v->>'size_bytes')::bigint) FILTER (WHERE v->>'name' = 'crop'), 0), "
"coalesce(sum((v->>'size_bytes')::bigint) FILTER (WHERE v->>'name' = 'optimized'), 0) "
"FROM attachments a "
"LEFT JOIN LATERAL jsonb_array_elements(a.variants) v ON true "
f"WHERE a.id IN ({quoted}) "
"GROUP BY a.id, a.size_bytes"
)
result = {}
for line in psql(sql):
parts = line.split("|")
if len(parts) != 6:
continue
result[parts[0]] = {
"original_bytes": int(parts[1]),
"variants_bytes": int(parts[2]),
"thumbnail_bytes": int(parts[3]),
"crop_bytes": int(parts[4]),
"optimized_bytes": int(parts[5]),
}
return result
def measure_run(base_url, actor, chat_id, profile, scenario, count, data, digest,
cpu_limit="1.0", mem_limit="2G"):
wait_drained()
@@ -371,6 +439,45 @@ def measure_run(base_url, actor, chat_id, profile, scenario, count, data, digest
if failed:
raise Failure(f"jobs failed in {profile['name']}/{scenario['name']}: {failed[:2]}")
row_ids = [row["attachment_id"] for row in rows]
timings = job_timings(row_ids)
if len(timings) != len(rows):
raise Failure(
f"timing logs found for {len(timings)}/{len(rows)} jobs in "
f"{profile['name']}/{scenario['name']}"
)
variants = variant_stats(row_ids)
if len(variants) != len(rows):
raise Failure(
f"variant metadata found for {len(variants)}/{len(rows)} jobs in "
f"{profile['name']}/{scenario['name']}"
)
decode_ms = [timings[item]["decode_us"] / 1000 for item in row_ids]
scale_ms = [timings[item]["scale_us"] / 1000 for item in row_ids]
jpeg_ms = [timings[item]["jpeg_encode_us"] / 1000 for item in row_ids]
webp_ms = [timings[item]["webp_encode_us"] / 1000 for item in row_ids]
encode_ms = [jpeg_ms[index] + webp_ms[index] for index in range(len(row_ids))]
pipeline_ms = [timings[item]["pipeline_us"] / 1000 for item in row_ids]
cpu_us = sum(
timings[item]["decode_us"] + timings[item]["scale_us"]
+ timings[item]["jpeg_encode_us"] + timings[item]["webp_encode_us"]
for item in row_ids
)
encode_us = sum(
timings[item]["jpeg_encode_us"] + timings[item]["webp_encode_us"]
for item in row_ids
)
encode_share_pct = 100 * encode_us / cpu_us if cpu_us else None
variant_bytes = {
name: sum(item[f"{name}_bytes"] for item in variants.values())
for name in ("thumbnail", "crop", "optimized")
}
original_bytes = sum(item["original_bytes"] for item in variants.values())
variants_bytes = sum(item["variants_bytes"] for item in variants.values())
compression_ratio = variants_bytes / original_bytes if original_bytes else None
queue_lag = [
(row["processing_started_at"] - row["created_at"]) * 1000
for row in rows
@@ -446,6 +553,24 @@ def measure_run(base_url, actor, chat_id, profile, scenario, count, data, digest
"time_to_ready_max_ms": r(max(time_to_ready) if time_to_ready else None, 1),
"processing_p50_ms": r(percentile(processing, 50), 1),
"processing_p95_ms": r(percentile(processing, 95), 1),
"decode_ms_p50": r(percentile(decode_ms, 50), 2),
"decode_ms_p95": r(percentile(decode_ms, 95), 2),
"scale_ms_p50": r(percentile(scale_ms, 50), 2),
"scale_ms_p95": r(percentile(scale_ms, 95), 2),
"jpeg_encode_ms_p50": r(percentile(jpeg_ms, 50), 2),
"jpeg_encode_ms_p95": r(percentile(jpeg_ms, 95), 2),
"webp_encode_ms_p50": r(percentile(webp_ms, 50), 2),
"webp_encode_ms_p95": r(percentile(webp_ms, 95), 2),
"encode_ms_p50": r(percentile(encode_ms, 50), 2),
"encode_ms_p95": r(percentile(encode_ms, 95), 2),
"pipeline_ms_p50": r(percentile(pipeline_ms, 50), 2),
"pipeline_ms_p95": r(percentile(pipeline_ms, 95), 2),
"encode_share_pct": r(encode_share_pct, 1),
"timing_jobs": len(timings),
"original_bytes": original_bytes,
"variants_bytes": variants_bytes,
"variant_bytes": variant_bytes,
"compression_ratio": r(compression_ratio, 3),
"max_backlog_jobs": max_backlog,
"max_parallel_jobs": max_parallel,
"rss_baseline_mib": r(baseline_kb / 1024 if baseline_kb else None, 1),
@@ -637,6 +762,11 @@ def build_html(evidence):
"VmRSS процесса worker во время задания (меньше — экономнее).",
scenarios, profiles, series_for("rss_peak_mib"), " MiB", digits=0, lower_better=True,
),
svg_chart(
"Compression overhead: доля encode в pipeline CPU",
"encode / (decode + scale + encode), % (меньше — дешевле сжатие).",
scenarios, profiles, series_for("encode_share_pct"), " %", digits=1, lower_better=True,
),
]
def fmt(value, digits=1, suffix=""):
@@ -653,6 +783,8 @@ def build_html(evidence):
f"<td>{fmt(run['queue_lag_p95_ms'], 0)}</td>"
f"<td>{fmt(run['time_to_ready_p95_ms'], 0)}</td>"
f"<td>{fmt(run['processing_p95_ms'], 0)}</td>"
f"<td>{fmt(run['encode_ms_p95'], 0)}</td>"
f"<td>{fmt(run['encode_share_pct'], 1)}</td>"
f"<td>{fmt(run['rss_peak_mib'], 0)}</td>"
f"<td>{run['max_parallel_jobs']}</td>"
f"<td>{run['max_backlog_jobs']}</td>"
@@ -679,6 +811,7 @@ def build_html(evidence):
f"{scenario}: пиковый RSS eager относится к serial как {ratio:.1f}×."
)
balanced = lookup.get(("balanced", "small_many"))
exact = lookup.get(("balanced", "exactly_right"))
huge = lookup.get(("balanced", "huge_few"))
if balanced and huge and balanced["time_to_ready_p95_ms"] and huge["time_to_ready_p95_ms"]:
observations.append(
@@ -687,6 +820,15 @@ def build_html(evidence):
"больше, чем для small_many: размер изображения меняет стоимость задания, "
"а не только число заданий."
)
if exact and huge and exact["encode_share_pct"] is not None and huge["encode_share_pct"] is not None:
observations.append(
"Compression vs scaling (balanced): exactly_right — encode share "
f"{exact['encode_share_pct']:.1f}%, scale p95 {exact['scale_ms_p95']:.0f} ms; "
f"huge_few — encode share {huge['encode_share_pct']:.1f}%, "
f"scale p95 {huge['scale_ms_p95']:.0f} ms. На exactly_right optimized "
"WebP кодируется в native 1280, поэтому это нижняя граница стоимости "
"сжатия; на huge_few к ней добавляется downscale."
)
huge_serial = lookup.get(("serial", "huge_few"))
huge_eager = lookup.get(("eager", "huge_few"))
if huge_serial and huge_eager and huge_serial["throughput_jobs_per_s"]:
@@ -711,10 +853,10 @@ def build_html(evidence):
"заданий в работе и в prefetch-окне брокера."
)
observations.append(
"Backpressure: при MAX_PENDING_JOBS=3 API принял "
f"{evidence['backpressure']['accepted_before_503']} задания, затем вернул 503 "
f"с Retry-After={evidence['backpressure']['blocked_retry_after']}; после старта "
f"worker очередь восстановилась за {evidence['backpressure']['recovery_seconds']:.1f} с."
"Backpressure: cap=3 выставлен намеренно, поэтому число принятых заданий — "
"следствие настройки, а не открытие. Значимо то, что API вернул 503 "
f"с Retry-After={evidence['backpressure']['blocked_retry_after']}, а после "
f"старта worker очередь восстановилась за {evidence['backpressure']['recovery_seconds']:.1f} с."
)
backpressure_rows = "".join(
@@ -786,14 +928,14 @@ code {{ background: #f1f5f9; padding: 1px 5px; border-radius: 4px; }}
{evidence['environment']['cpu_count']} CPU, Docker {html.escape(evidence['environment']['docker_version'])}.</p>
<section class="card hypothesis">
<strong>Гипотеза.</strong> Маленькие изображения, которые почти не требуют
масштабирования, должны давать высокий throughput и низкий RSS на задание.
Большие изображения требуют декодирования и downscale, поэтому каждое задание
дороже: при том же числе worker-ов очередь растёт, p95 time-to-ready
увеличивается, а пиковый RSS зависит от concurrency сильнее, чем у маленьких
файлов. Одновременно проверяем компромисс: <em>eager</em> уменьшает ожидание,
но повышает потребление памяти; <em>serial</em> экономит память, но ограничивает
throughput.
<strong>Гипотеза.</strong> Стоимость задания складывается из decode, масштабирования
и сжатия. <em>exactly_right</em> (1280×1280) не масштабирует optimized-вариант,
поэтому показывает нижнюю границу стоимости сжатия; <em>huge_few</em> добавляет
downscale, а <em>small_many</em> почти не масштабируется, но и пикселей в нём
мало. Большие изображения при том же числе worker-ов увеличивают очередь,
p95 time-to-ready и RSS. Одновременно проверяем компромисс: <em>eager</em>
уменьшает ожидание, но повышает память; <em>serial</em> экономит память, но
ограничивает throughput.
</section>
<section class="card">
@@ -813,7 +955,6 @@ throughput.
<div class="metrics">
<div class="metric"><div class="value">{len(runs)}</div><div class="label">прогонов матрицы</div></div>
<div class="metric"><div class="value">{max(run['rss_peak_mib'] or 0 for run in runs):.0f} MiB</div><div class="label">максимальный RSS worker</div></div>
<div class="metric"><div class="value">{evidence['backpressure']['accepted_before_503']}</div><div class="label">принято до первого 503</div></div>
<div class="metric"><div class="value">{evidence['backpressure']['recovery_seconds']:.1f} s</div><div class="label">восстановление после backpressure</div></div>
</div>
</section>
@@ -823,11 +964,16 @@ throughput.
<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>
<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>Encode p95, ms</th><th>Encode share, %</th><th>RSS peak, MiB</th><th>Max parallel</th><th>Max backlog</th></tr></thead>
<tbody>{''.join(table_rows)}</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>.
Encode = JPEG thumbnail + JPEG crop + WebP optimized; encode share =
<code>encode / (decode + scale + encode)</code> из worker-лога.
Суммы байт вариантов и оригинала остаются в JSON, но не выносятся в заголовок:
синтетический PNG сжимается слишком хорошо, чтобы отношение байт было честной
метрикой эффективности кодека.
RSS — VmRSS процесса worker, сэмплирование примерно каждые 100 мс.
Max parallel — максимум одновременно обрабатываемых заданий; max backlog —
максимум принятых, но ещё не готовых заданий.</p>
@@ -836,8 +982,10 @@ Max parallel — максимум одновременно обрабатыва
<section class="card">
<h2>Backpressure и восстановление</h2>
<p>Перед этим прогоном API пересоздан с <code>MAX_PENDING_JOBS=3</code>, worker
остановлен. Последовательные upload-ы показывают, где заканчивается принятая
работа. Затем worker запускается, принятые задания должны дойти до ready.</p>
остановлен. Cap выбран намеренно: важно не число принятых заданий, а то, что
API возвращает <code>503</code> с <code>Retry-After</code> и не теряет уже
подтверждённую работу. Затем 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>{backpressure_rows}</tbody>
@@ -857,8 +1005,15 @@ Max parallel — максимум одновременно обрабатыва
<ul>
<li>Один worker, один RabbitMQ и один PostgreSQL: это сравнение настроек, а не
HA-кластер. Числа зависят от CPU/диска конкретной машины.</li>
<li>PNG-фикстуры синтетические и хорошо сжимаются; доминирует стоимость декодирования
и масштабирования, а не передача по сети. Размер в байтах указан в JSON.</li>
<li>PNG-фикстуры синтетические и хорошо сжимаются; absolute encode time зависит
от паттерна, но сравнение сценариев при одном паттерне остаётся корректным.
Размер в байтах указан в JSON.</li>
<li>Timing-поля читаются из worker-лога. Это wall-clock внутри процесса, поэтому
при concurrency &gt; 1 в них входит и планировщик, что как раз и нужно для
сравнения профилей.</li>
<li>exactly_right кодирует 1.64 MP WebP, а huge_few после downscale — около
1.23 MP. Сценарий убирает scaling, но не уравнивает объём encode; это указано,
чтобы не сравнивать throughput как «одинаковую работу».</li>
<li>RSS сэмплируется из <code>/proc/1/status</code>; короткий прогон не заменяет
длительный memory profile и p99.</li>
<li>Backpressure cap приблизительный: каждая API-реплика считает pending-задания
@@ -879,20 +1034,21 @@ def write_markdown(evidence, path):
"",
"Synthetic images; no tokens or credentials are stored.",
"",
"| Profile | Scenario | Jobs | Jobs/s | Queue lag p95, ms | Ready p95, ms | RSS peak, MiB |",
"| --- | --- | ---: | ---: | ---: | ---: | ---: |",
"| Profile | Scenario | Jobs | Jobs/s | Queue lag p95, ms | Ready p95, ms | Encode p95, ms | Encode share, % | RSS peak, MiB |",
"| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
]
for run in evidence["runs"]:
lines.append(
f"| {run['profile']} | {run['scenario']} | {run['jobs']} | "
f"{run['throughput_jobs_per_s']:.2f} | {run['queue_lag_p95_ms']:.0f} | "
f"{run['time_to_ready_p95_ms']:.0f} | {run['rss_peak_mib']:.0f} |"
f"{run['time_to_ready_p95_ms']:.0f} | {run['encode_ms_p95']:.0f} | "
f"{run['encode_share_pct']:.1f} | {run['rss_peak_mib']:.0f} |"
)
bp = evidence["backpressure"]
lines.extend(
[
"",
f"Backpressure: cap={bp['cap']}, accepted={bp['accepted_before_503']}, "
f"Backpressure: cap={bp['cap']} (deliberate), "
f"first 503 Retry-After={bp['blocked_retry_after']}, "
f"recovery={bp['recovery_seconds']:.2f}s, probe HTTP {bp['probe_status']}.",
"",
@@ -909,6 +1065,7 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
parser.add_argument("--small-jobs", type=int, default=30)
parser.add_argument("--exactly-jobs", type=int, default=18)
parser.add_argument("--huge-jobs", type=int, default=12)
parser.add_argument(
"--worker-cpu-limit",
@@ -941,9 +1098,14 @@ def main():
client = Client(base_url, timeout=60)
alice, _bob, _eve, chat = client.bootstrap()
counts = {
"small_many": args.small_jobs,
"exactly_right": args.exactly_jobs,
"huge_few": args.huge_jobs,
}
scenarios = []
for item in SCENARIOS:
count = args.small_jobs if item["name"] == "small_many" else args.huge_jobs
count = counts[item["name"]]
data = make_png(item["width"], item["height"])
scenarios.append({**item, "count": count, "bytes": len(data)})
@@ -978,6 +1140,7 @@ def main():
f" throughput={result['throughput_jobs_per_s']} jobs/s "
f"queue_p95={result['queue_lag_p95_ms']} ms "
f"ready_p95={result['time_to_ready_p95_ms']} ms "
f"encode_share={result['encode_share_pct']}% "
f"rss_peak={result['rss_peak_mib']} MiB",
flush=True,
)
@@ -1046,9 +1209,10 @@ def main():
),
},
"hypothesis": (
"Small images that fit the variants without large scaling should be cheaper "
"per job; huge images force decode+downscale, so each job costs more memory "
"and time. More concurrency should raise throughput and RSS but reduce queue lag."
"Job cost is decode + scale + encode. exactly_right (1280x1280) keeps the "
"optimized WebP at native size, so it measures the compression floor; "
"huge_few adds downscale, and small_many has few pixels. More concurrency "
"should raise throughput and RSS but reduce queue lag."
),
"profiles": PROFILES,
"scenarios": scenarios,