Renew job leases, spread retries with jitter and add crash points

Leases: the worker renews its lease before the first side effect and
every JOB_TIMEOUT_SECONDS/3 while the variants are produced; a renewal
that finds the lease taken cancels the work (and its render process)
and settles the job as fenced without writing anything.

Retries: the delay before attempt n+1 is drawn from [d/2, d] with
d = min(cap, base * 2^(n-1)) (equal jitter), the next attempt time is
computed by PostgreSQL and the delay is kept in the job event.

Faults: the Faults port is async; relay reaches after_commit_before_publish
and after_publish_before_confirm, worker reaches after_claim_before_side_effect,
stall_after_claim (once, FAULT_STALL_SECONDS), after_s3_write_before_commit
and after_commit_before_ack. Crashes are os._exit(137).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-29 03:08:31 +03:00
co-authored by Claude Opus 5.5
parent f2242eb39d
commit ecb4827e75
14 changed files with 432 additions and 70 deletions
@@ -11,19 +11,27 @@ from messenger.attachments.application.commands import (
from messenger.attachments.application.ports import (
AttachmentsUnitOfWork,
Faults,
Jitter,
JobPublisher,
ObjectStorage,
VariantRenderer,
)
from messenger.attachments.domain.errors import UnreadableImage
from messenger.attachments.domain.errors import LeaseLost, UnreadableImage
from messenger.attachments.domain.events import JobSettled
from messenger.attachments.domain.jobs import Claim, FailureCode, Job, Lease, Outcome, RetryPolicy
from messenger.attachments.domain.models import original_key
from messenger.attachments.domain.variants import Variant, variant_key
from messenger.shared.application.errors import Unavailable
from messenger.shared.application.ports import Clock, IdGenerator
from messenger.shared.application.ports import IdGenerator
TRANSIENT_FAULT = "transient_error"
TRANSIENT_ERROR = "transient_error"
STALL_AFTER_CLAIM = "stall_after_claim"
AFTER_COMMIT_BEFORE_PUBLISH = "after_commit_before_publish"
AFTER_PUBLISH_BEFORE_CONFIRM = "after_publish_before_confirm"
AFTER_CLAIM = "after_claim_before_side_effect"
AFTER_S3_WRITE = "after_s3_write_before_commit"
AFTER_COMMIT_BEFORE_ACK = "after_commit_before_ack"
RENEWALS = 3
def settled(
@@ -45,7 +53,7 @@ def settled(
class ProcessJobHandler:
__slots__ = ("_clock", "_faults", "_ids", "_lease", "_policy", "_renderer", "_storage", "_uow")
__slots__ = ("_faults", "_ids", "_jitter", "_lease", "_policy", "_renderer", "_storage", "_uow")
def __init__(
self,
@@ -54,8 +62,8 @@ class ProcessJobHandler:
renderer: VariantRenderer,
faults: Faults,
*,
clock: Clock,
ids: IdGenerator,
jitter: Jitter,
policy: RetryPolicy,
lease: timedelta,
) -> None:
@@ -63,8 +71,8 @@ class ProcessJobHandler:
self._storage = storage
self._renderer = renderer
self._faults = faults
self._clock = clock
self._ids = ids
self._jitter = jitter
self._policy = policy
self._lease = lease
@@ -77,19 +85,47 @@ class ProcessJobHandler:
await self._uow.commit()
if claim is None:
return Outcome.DUPLICATE
await self._faults.reach(AFTER_CLAIM)
await self._faults.reach(STALL_AFTER_CLAIM)
try:
variants = await self._produce(claim)
variants = await self._held(claim)
except LeaseLost:
return await self._fenced(claim.lease)
except UnreadableImage as error:
return await self._fail(claim.lease, FailureCode.INVALID_IMAGE, error)
except Unavailable as error:
return await self._retry(claim.lease, error)
except Exception as error:
return await self._fail(claim.lease, FailureCode.PROCESSING_FAILED, error)
return await self._complete(claim.lease, variants)
await self._faults.reach(AFTER_S3_WRITE)
outcome = await self._complete(claim.lease, variants)
await self._faults.reach(AFTER_COMMIT_BEFORE_ACK)
return outcome
async def _held(self, claim: Claim) -> list[Variant]:
await self._renew(claim.lease)
work = asyncio.ensure_future(self._produce(claim))
try:
while not work.done():
await asyncio.wait({work}, timeout=self._lease.total_seconds() / RENEWALS)
if not work.done():
await self._renew(claim.lease)
except BaseException:
work.cancel()
await asyncio.wait({work})
raise
return work.result()
async def _renew(self, lease: Lease) -> None:
async with self._uow.transaction():
held = await self._uow.jobs.renew(lease, self._lease)
await self._uow.commit()
if not held:
raise LeaseLost("аренду задания забрал другой держатель")
async def _produce(self, claim: Claim) -> list[Variant]:
job = claim.lease.job
self._faults.reach(TRANSIENT_FAULT)
await self._faults.reach(TRANSIENT_ERROR)
data = await self._storage.read(claim.source_key)
renditions = await self._renderer.render(data, job.pipeline_version)
if claim.staged:
@@ -123,14 +159,20 @@ class ProcessJobHandler:
await self._uow.commit()
return outcome
async def _fenced(self, lease: Lease) -> Outcome:
async with self._uow.transaction():
await self._uow.jobs.note(lease.job, Outcome.FENCED)
self._uow.record(settled(lease.job, Outcome.FENCED))
await self._uow.commit()
return Outcome.FENCED
async def _retry(self, lease: Lease, error: Exception) -> Outcome:
delay = self._policy.delay(lease.job.attempt)
delay = self._policy.delay(lease.job.attempt, self._jitter.spread())
if delay is None:
return await self._fail(lease, FailureCode.RETRY_EXHAUSTED, error)
async with self._uow.transaction():
at = self._clock.now() + delay
job = await self._uow.jobs.reschedule(
lease, at, Outcome.RESCHEDULED, type(error).__name__
lease, delay, Outcome.RESCHEDULED, type(error).__name__
)
outcome = Outcome.FENCED if job is None else Outcome.RESCHEDULED
if job is None:
@@ -151,22 +193,25 @@ class ProcessJobHandler:
class PublishOutboxHandler:
__slots__ = ("_publisher", "_uow")
__slots__ = ("_faults", "_publisher", "_uow")
def __init__(self, uow: AttachmentsUnitOfWork, publisher: JobPublisher) -> None:
def __init__(self, uow: AttachmentsUnitOfWork, publisher: JobPublisher, faults: Faults) -> None:
self._uow = uow
self._publisher = publisher
self._faults = faults
async def __call__(self, command: PublishOutbox) -> int:
failure: Unavailable | None = None
published: list[int] = []
async with self._uow.transaction():
for entry in await self._uow.outbox.pending(command.limit):
await self._faults.reach(AFTER_COMMIT_BEFORE_PUBLISH)
try:
await self._publisher.publish(entry.job_id, entry.body)
except Unavailable as error:
failure = error
break
await self._faults.reach(AFTER_PUBLISH_BEFORE_CONFIRM)
published.append(entry.id)
if published:
await self._uow.outbox.published(published)
@@ -177,25 +222,24 @@ class PublishOutboxHandler:
class RecoverExpiredLeasesHandler:
__slots__ = ("_clock", "_policy", "_uow")
__slots__ = ("_policy", "_uow")
def __init__(self, uow: AttachmentsUnitOfWork, clock: Clock, policy: RetryPolicy) -> None:
def __init__(self, uow: AttachmentsUnitOfWork, policy: RetryPolicy) -> None:
self._uow = uow
self._clock = clock
self._policy = policy
async def __call__(self, command: RecoverExpiredLeases) -> int:
async with self._uow.transaction():
leases = await self._uow.jobs.expired(command.limit)
for lease in leases:
if self._policy.delay(lease.job.attempt) is None:
if self._policy.exhausted(lease.job.attempt):
await self._uow.jobs.fail(
lease, FailureCode.RETRY_EXHAUSTED, Outcome.LEASE_EXPIRED.value
)
outcome = Outcome.FAILED
else:
await self._uow.jobs.reschedule(
lease, self._clock.now(), Outcome.LEASE_EXPIRED, Outcome.LEASE_EXPIRED.value
lease, timedelta(0), Outcome.LEASE_EXPIRED, Outcome.LEASE_EXPIRED.value
)
outcome = Outcome.LEASE_EXPIRED
self._uow.record(settled(lease.job, outcome))
@@ -70,7 +70,12 @@ class JobPublisher(Protocol):
@runtime_checkable
class Faults(Protocol):
def reach(self, point: str) -> None: ...
async def reach(self, point: str) -> None: ...
@runtime_checkable
class Jitter(Protocol):
def spread(self) -> float: ...
@runtime_checkable
@@ -106,9 +111,11 @@ class JobRepository(Protocol):
) -> Outcome: ...
async def reschedule(
self, lease: Lease, at: datetime, kind: Outcome, error: str
self, lease: Lease, delay: timedelta, kind: Outcome, error: str
) -> Job | None: ...
async def renew(self, lease: Lease, duration: timedelta) -> bool: ...
async def fail(self, lease: Lease, code: FailureCode, error: str) -> bool: ...
async def note(self, job: Job, kind: Outcome) -> None: ...