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
+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,