fix: address pipeline-reliability verify findings

Close the source image after converting to RGBA so PNGs at the pixel limit
fit the render memory limit. Strengthen the fencing test so that it fails
without the attempt check, and measure worker and relay stops under load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 18:55:38 +03:00
co-authored by Claude Opus 5.5
parent 6bd60532aa
commit 399da054f2
19 changed files with 596 additions and 41 deletions
+25 -10
View File
@@ -61,10 +61,13 @@
pause|unpause worker заморозка контейнера (зависший worker)
run-worker K=V… второй worker `<FAULT_PROJECT>-worker-extra` с
этим окружением
run-worker-second K=V… третий worker `<FAULT_PROJECT>-worker-second-extra`:
вторая попытка рядом с замороженной первой
run-relay K=V… второй relay `<FAULT_PROJECT>-relay-extra`
stop-extra убрать дополнительные контейнеры
extra-log worker|relay журнал дополнительного контейнера
kill-extra|pause-extra|unpause-extra worker
extra-log worker|worker-second|relay
журнал дополнительного контейнера
kill-extra|pause-extra|unpause-extra worker|worker-second
то же с дополнительным worker
expire-lease <id> срок аренды задания вложения — в прошлом: окно,
где таймеры прежней попытки ещё не сработали
@@ -756,7 +759,8 @@ BROKER_LIMIT_RE = re.compile(r"^[0-9]+(MiB|GiB|MB|GB)?$")
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
# варианты контракта: имя в DELETE_VARIANT_SQL
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
EXTRA_SERVICES = ("worker", "relay")
SECOND_WORKER = "worker-second"
EXTRA_SERVICES = ("worker", SECOND_WORKER, "relay")
COMMIT_STALL_TIMEOUT_S = 15
# аргументы replay: значения проверяет сама команда, а эти — чтобы в compose
# run не ушло лишнее
@@ -1221,8 +1225,15 @@ def extra_name(project: str, name: str) -> str:
return f"{project}-{name}-extra"
def run_extra(project: str, name: str, pairs: list[str]) -> str:
"""Второй процесс сервиса с этим окружением; прежний такой убирается."""
def run_extra(
project: str,
name: str,
pairs: list[str],
*,
service: str | None = None,
) -> str:
"""Ещё один процесс сервиса с этим окружением; прежний такой убирается.
`service` — сервис compose, если он не совпадает с именем процесса."""
for pair in pairs:
if not EXTRA_ENV_RE.fullmatch(pair):
raise HookError(f"bad environment pair: {pair!r}")
@@ -1241,7 +1252,7 @@ def run_extra(project: str, name: str, pairs: list[str]) -> str:
"--name",
container,
*options,
name,
service or name,
)
return ""
@@ -1718,16 +1729,20 @@ def run(project: str, action: str, args: list[str]) -> str:
return container_state(service_container(project, "relay"))
if action == "run-worker":
return run_extra(project, "worker", args)
if action == "run-worker-second":
return run_extra(project, SECOND_WORKER, args, service="worker")
if action == "run-relay":
return run_extra(project, "relay", args)
if action == "stop-extra" and not args:
return stop_extra(project)
if action == "extra-log" and len(args) == 1:
return docker("logs", extra_name(project, args[0]))
if action in ("kill-extra", "pause-extra", "unpause-extra") and args == [
"worker",
]:
docker(action.split("-")[0], extra_name(project, "worker"))
if (
action in ("kill-extra", "pause-extra", "unpause-extra")
and len(args) == 1
and args[0] in ("worker", SECOND_WORKER)
):
docker(action.split("-")[0], extra_name(project, args[0]))
return ""
if action == "expire-lease" and len(args) == 1:
return row_change(project, EXPIRE_LEASE_SQL, args[0], "")
+30
View File
@@ -335,6 +335,36 @@ def png_rgba_large(width: int = 8000, height: int = 5000) -> bytes:
return buffer.getvalue()
def png_at_pixel_limit(
color: int,
depth: int,
*,
transparent: bool = False,
width: int = 8000,
height: int = 5000,
) -> bytes:
"""PNG любого типа на 40 млн пикселей из нулей: файл мал, а декодирование
разворачивает все пиксели. `transparent` — чанк tRNS (прозрачный цвет):
Pillow открывает такой файл без альфы и переводит в RGBA отдельным шагом."""
row = b"\x00" * (1 + (width * depth * _CHANNELS[color] + 7) // 8)
compressor = zlib.compressobj(9)
parts = [compressor.compress(row) for _ in range(height)]
parts.append(compressor.flush())
data = png(
width,
height,
color=color,
depth=depth,
idat=b"".join(parts),
)
if not transparent:
return data
# tRNS — после IHDR и PLTE (перед первым IDAT): у палитры индекс, иначе цвет
index = data.index(b"IDAT") - 4
body = b"\x00" if color == 3 else b"\x00" * (6 if color == 2 else 2)
return data[:index] + chunk(b"tRNS", body) + data[index:]
def png_stripes(
stripes: tuple[tuple[int, tuple[int, int, int]], ...] = (
(100, (255, 0, 0)),
+1
View File
@@ -382,6 +382,7 @@ def main() -> int:
s3_name,
scheduled_name,
f"{project}-worker-extra",
f"{project}-worker-second-extra",
f"{project}-relay-extra",
]
@@ -36,6 +36,7 @@ VARIANT_TYPES = {
"optimized": "image/webp",
}
VARIANT_NAMES = tuple(VARIANT_TYPES)
LARGE_BODY_CLIENT_TIMEOUT_S = 30
def thumbnail_of(
@@ -242,6 +243,41 @@ def test_thumbnail_format_variants(
variant_of(api, alice, attachment, variant)
@pytest.mark.spec("attachment-processing", "Изображение в лимите пикселей")
@pytest.mark.parametrize(
("color", "depth", "transparent"),
[
pytest.param(4, 8, False, id="gray-alpha-8"),
pytest.param(2, 8, True, id="rgb-8-trns"),
pytest.param(2, 16, True, id="rgb-16-trns"),
pytest.param(3, 8, True, id="palette-trns"),
pytest.param(0, 16, False, id="gray-16"),
],
)
def test_pixel_limit_png_modes(
base_url: str,
alice: Actor,
chat: dict[str, Any],
color: int,
depth: int,
transparent: bool,
) -> None:
"""Контракт разрешает 40 млн пикселей в любом типе PNG. Эти типы
переводятся в другой режим при подготовке: держать исходник на время
перевода и масштаба — пик выше лимита памяти процесса обработки."""
data = images.png_at_pixel_limit(color, depth, transparent=transparent)
# срок клиента: тело на 40 млн пикселей проверяется дольше 5 с по умолчанию
with Api(base_url, timeout=LARGE_BODY_CLIENT_TIMEOUT_S) as slow:
attachment = slow.upload_ready(alice, chat["id"], data)
sizes = {
"thumbnail": (256, 160),
"crop": (128, 128),
"optimized": (1280, 800),
}
for name, size in sizes.items():
assert variant_of(slow, alice, attachment, name).size == size
@pytest.mark.spec("attachment-processing", "Crop большого изображения")
def test_crop_center(
api: Api,
+112 -8
View File
@@ -1761,17 +1761,18 @@ def wait_extra_record(
event: str,
*,
timeout: float = 30,
extra: str = "worker",
**fields: Any,
) -> dict[str, Any]:
deadline = time.monotonic() + timeout
while True:
for record in extra_records(stand):
for record in extra_records(stand, extra):
if record.get("event") == event and all(
record.get(name) == value for name, value in fields.items()
):
return record
assert time.monotonic() < deadline, (
f"no extra worker record {event!r} with {fields} in {timeout} s"
f"no {extra} record {event!r} with {fields} in {timeout} s"
)
time.sleep(0.3)
@@ -5260,18 +5261,121 @@ def test_render_killed(
assert done["attempt"] == 2, done
@pytest.mark.spec("attachment-processing", "Зависший worker")
@pytest.mark.spec("attachment-processing", "Прежняя попытка при живой новой")
def test_hung_worker_lease_fencing(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Первый worker — со сроками больше времени теста: разморозка застаёт его
таймеры живыми, и он доходит до фиксации, где решает только номер попытки (с
обычными сроками его прервал бы таймер, а не fencing). Аренду делает истекшей
hook, а не ожидание: при таком сроке попытки её не дождаться. Второй процесс —
основной worker стенда."""
"""Первая попытка размораживается, когда вторая жива: задание в `processing`,
блокировки строки нет. Решает только номер попытки: по `state` фиксация первой
прошла бы. Оба worker — со сроками больше времени теста, иначе при разморозке
их прервал бы таймер, а не fencing. S3 заморожен, пока вторая не взята: она
ждёт его и не успеет зафиксировать результат раньше своей заморозки. Итог даёт
только вторая. Аренду делает истекшей hook: при таком сроке её не дождаться."""
second = "worker-second"
timers = (
"WORKER__JOB_TIMEOUT_SECONDS=120",
"WORKER__RENDER_TIMEOUT_SECONDS=60",
"S3__TIMEOUT_SECONDS=60",
)
seen_relay = len(relay_records(stand))
try:
with worker_stopped(stand):
accepted = api.upload(alice, chat["id"], images.sample_png())
attachment_id = accepted["id"]
wait_queue_messages(stand, 1)
with outage(stand, "pause", "s3"):
stand("run-worker", *timers)
wait_job(stand, attachment_id, state="processing", attempt=1)
wait_extra_record(
stand,
"Started job attempt",
attachment_id=attachment_id,
attempt=1,
)
stand("pause-extra", "worker")
stand("expire-lease", attachment_id)
wait_relay_record(
stand,
"Recovered expired lease",
skip=seen_relay,
attachment_id=attachment_id,
)
stand("run-worker-second", *timers)
wait_job(stand, attachment_id, state="processing", attempt=2)
wait_extra_record(
stand,
"Started job attempt",
extra=second,
attachment_id=attachment_id,
attempt=2,
)
stand("pause-extra", second)
# вторая взята и заморожена в вызове S3: транзакции нет
assert stand("attachment-free", attachment_id)
taken = job_row(stand, attachment_id)
assert taken is not None
assert taken["state"] == "processing", taken
assert taken["attempt"] == 2, taken
stand("unpause-extra", "worker")
wait_extra_record(
stand,
"Skipped job message",
attachment_id=attachment_id,
attempt=1,
reason="superseded",
)
assert job_row(stand, attachment_id) == taken
assert (
assert_ok(
api.attachment_meta(alice, attachment_id),
200,
"Attachment",
)["status"]
== "processing"
)
stand("unpause-extra", second)
meta = api.wait_attachment(
alice,
attachment_id,
timeout=JOB_WAIT_S,
)
wait_extra_record(
stand,
"Attachment became ready",
extra=second,
attachment_id=attachment_id,
attempt=2,
)
job = job_row(stand, attachment_id)
assert job is not None
assert job["state"] == "succeeded", job
assert job["attempt"] == 2, job
assert not [
record
for record in extra_records(stand)
if record.get("event") == "Attachment became ready"
and record.get("attachment_id") == attachment_id
]
finally:
stand("stop-extra")
assert_variants(api, stand, alice, meta)
@pytest.mark.spec("attachment-processing", "Зависший worker")
def test_hung_worker_thawed_after_ready(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
"""Вторая попытка уже дала `ready`, первая разморожена: итог её не меняет.
Первый worker — со сроками больше времени теста: разморозка застаёт его
таймеры живыми, и он доходит до фиксации (с обычными сроками его прервал бы
таймер, а не fencing). Здесь решает и `state`; номер попытки —
`test_hung_worker_lease_fencing`. Второй процесс — основной worker стенда."""
seen_relay = len(relay_records(stand))
with worker_stopped(stand):
accepted = api.upload(alice, chat["id"], images.sample_png())