Render variants in killable processes with time and memory limits

The renderer adapter keeps one single-process pool per WORKER_CONCURRENCY
slot. A render that exceeds RENDER_TIMEOUT_SECONDS is killed and its slot
is respawned, the render process has RLIMIT_AS = RENDER_MEMORY_MB on
Linux, so both limits end in ImageTooDemanding, a permanent
processing_failed. A render process killed from outside is a transient
error. A cancelled render (lost lease, shutdown) kills its process too.
The worker container limit grows to 1g: two 448 MiB render processes
plus the worker itself.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-29 03:02:16 +03:00
co-authored by Claude Opus 5.5
parent 431b82fd43
commit f2242eb39d
10 changed files with 228 additions and 20 deletions
+26
View File
@@ -10,6 +10,8 @@ from httpx import AsyncClient
from test_attachments import storage, trio, upload
from conftest import DATABASE, actor
from messenger.attachments.application.ports import Rendition
from messenger.attachments.domain.errors import ImageTooDemanding
from messenger.attachments.domain.jobs import Job, Outcome, RetryPolicy
from messenger.attachments.entrypoints.schemas import JobMessage
from messenger.shared.application.errors import Unavailable
@@ -205,6 +207,30 @@ async def test_undecodable_image_fails_without_retries(client: AsyncClient) -> N
)
class DemandingRenderer:
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
raise ImageTooDemanding("рендер дольше допустимого времени")
@pytest.mark.parametrize("cause", ["limit", "missing"])
async def test_limits_and_lost_original_fail_without_retries(
client: AsyncClient, cause: str
) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
if cause == "limit":
pipeline.renderer = DemandingRenderer()
else:
del (await storage(client)).objects[f"staging/{attachment_id}"]
await pipeline.drain()
failed = await state(attachment_id)
assert (failed["status"], failed["error_code"], failed["attempt"]) == (
"failed",
"processing_failed",
1,
)
async def test_expired_lease_is_recovered_and_old_holder_is_fenced(client: AsyncClient) -> None:
_, _, attachment_id = await accepted(client)
pipeline = await pipeline_of(client)
+15 -3
View File
@@ -18,11 +18,16 @@ from messenger.attachments.application.pipeline import (
PublishOutboxHandler,
RecoverExpiredLeasesHandler,
)
from messenger.attachments.application.ports import Faults, ObjectStorage, VariantRenderer
from messenger.attachments.application.ports import (
Faults,
ObjectStorage,
Rendition,
VariantRenderer,
)
from messenger.attachments.domain.jobs import Job, Outcome, RetryPolicy
from messenger.attachments.entrypoints.schemas import JobMessage
from messenger.attachments.infrastructure.faults import EnvironmentFaults
from messenger.attachments.infrastructure.images import PillowVariantRenderer, RenderLimits
from messenger.attachments.infrastructure.images import RenderLimits, render_variants
from messenger.attachments.infrastructure.postgres import PostgresAttachmentsUnitOfWork
from messenger.shared.application.errors import Unavailable
from messenger.shared.infrastructure.clock import MonotonicUtcClock
@@ -34,6 +39,13 @@ LIMITS = RenderLimits(10_485_760, 40_000_000)
FAST = RetryPolicy(max_attempts=5, base_seconds=0.001, cap_seconds=0.001)
class InlineRenderer:
__slots__ = ()
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
return render_variants(data, LIMITS)
class CapturingPublisher:
__slots__ = ("bodies", "failing", "job_ids")
@@ -65,7 +77,7 @@ class InlinePipeline:
self.policy = policy
self.lease = lease
self.publisher = CapturingPublisher()
self.renderer: VariantRenderer = PillowVariantRenderer(LIMITS, 2)
self.renderer: VariantRenderer = InlineRenderer()
self.faults: Faults = EnvironmentFaults("", NullLogger())
def uow(self) -> PostgresAttachmentsUnitOfWork:
+91
View File
@@ -0,0 +1,91 @@
import asyncio
import os
import sys
import time
from collections.abc import AsyncIterator
import pytest
from messenger.attachments.application.ports import Rendition
from messenger.attachments.domain.errors import ImageTooDemanding
from messenger.attachments.infrastructure.images import (
ProcessVariantRenderer,
RenderLimits,
render_variants,
)
from messenger.shared.application.errors import Unavailable
from pictures import SAMPLE
LIMITS = RenderLimits(max_bytes=10_485_760, max_pixels=40_000_000)
HOG_BYTES = 512 << 20
def misbehaving(data: bytes, limits: RenderLimits) -> list[Rendition]:
if data == b"slow":
time.sleep(30)
if data == b"crash":
os._exit(1)
if data == b"oom":
raise MemoryError
if data == b"hog":
bytearray(HOG_BYTES)
return render_variants(data, limits)
@pytest.fixture
async def renderer() -> AsyncIterator[ProcessVariantRenderer]:
pool = ProcessVariantRenderer(
LIMITS,
concurrency=1,
timeout=3.0,
memory_bytes=256 << 20,
tasks_per_child=10,
render=misbehaving,
)
yield pool
pool.close()
async def test_renders_in_a_separate_process(renderer: ProcessVariantRenderer) -> None:
assert await renderer.render(SAMPLE, 1) == render_variants(SAMPLE, LIMITS)
async def test_timeout_kills_the_render_and_frees_the_slot(
renderer: ProcessVariantRenderer,
) -> None:
started = time.monotonic()
with pytest.raises(ImageTooDemanding):
await renderer.render(b"slow", 1)
assert time.monotonic() - started < 10
assert len(await renderer.render(SAMPLE, 1)) == 3
async def test_crashed_render_process_is_a_transient_error(
renderer: ProcessVariantRenderer,
) -> None:
with pytest.raises(Unavailable):
await renderer.render(b"crash", 1)
assert len(await renderer.render(SAMPLE, 1)) == 3
async def test_memory_error_is_a_permanent_error(renderer: ProcessVariantRenderer) -> None:
with pytest.raises(ImageTooDemanding):
await renderer.render(b"oom", 1)
assert len(await renderer.render(SAMPLE, 1)) == 3
async def test_cancelled_render_does_not_block_the_slot(renderer: ProcessVariantRenderer) -> None:
slow = asyncio.create_task(renderer.render(b"slow", 1))
await asyncio.sleep(1)
slow.cancel()
with pytest.raises(asyncio.CancelledError):
await slow
assert len(await asyncio.wait_for(renderer.render(SAMPLE, 1), 10)) == 3
@pytest.mark.skipif(sys.platform != "linux", reason="RLIMIT_AS применяется только в Linux")
async def test_address_space_limit_applies_to_the_render_process(
renderer: ProcessVariantRenderer,
) -> None:
with pytest.raises(ImageTooDemanding):
await renderer.render(b"hog", 1)