forked from mtusi2026/mtusi2026lab2
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>
94 lines
3.4 KiB
Python
94 lines
3.4 KiB
Python
import json
|
|
from datetime import UTC, datetime, timedelta
|
|
from pathlib import Path
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
|
|
from messenger.attachments.domain.jobs import Job, RetryPolicy
|
|
from messenger.attachments.domain.variants import fit, variant_key
|
|
from messenger.attachments.entrypoints.schemas import JobMessage
|
|
from messenger.attachments.infrastructure.jitter import RandomJitter
|
|
|
|
SCHEMA = json.loads(
|
|
(Path(__file__).resolve().parents[2] / "contracts" / "jobs.schema.json").read_text()
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("size", "fitted"),
|
|
[
|
|
((320, 200), (256, 160)),
|
|
((300, 200), (256, 170)),
|
|
((801, 601), (256, 192)),
|
|
((17, 1000), (4, 256)),
|
|
((3000, 2), (256, 1)),
|
|
((2, 3000), (1, 256)),
|
|
((64, 64), (64, 64)),
|
|
((256, 100), (256, 100)),
|
|
((257, 257), (256, 256)),
|
|
],
|
|
)
|
|
def test_thumbnail_fits_the_box_rounding_down(
|
|
size: tuple[int, int], fitted: tuple[int, int]
|
|
) -> None:
|
|
assert fit(*size, 256) == fitted
|
|
|
|
|
|
@pytest.mark.parametrize(("spread", "share"), [(0.0, 0.5), (0.5, 0.75), (0.999, 0.9995)])
|
|
def test_retry_delay_has_equal_jitter_up_to_the_cap(spread: float, share: float) -> None:
|
|
policy = RetryPolicy(max_attempts=5, base_seconds=2, cap_seconds=10)
|
|
delays = [policy.delay(attempt, spread) for attempt in range(1, 6)]
|
|
ceilings = [2, 4, 8, 10]
|
|
assert delays[:4] == [timedelta(seconds=ceiling * share) for ceiling in ceilings]
|
|
assert delays[4] is None
|
|
assert policy.exhausted(5)
|
|
assert not policy.exhausted(4)
|
|
|
|
|
|
def test_jitter_spreads_retries_between_half_and_full_delay() -> None:
|
|
policy, jitter = RetryPolicy(5, 2, 60), RandomJitter()
|
|
delays = {policy.delay(3, jitter.spread()) for _ in range(200)}
|
|
assert all(timedelta(seconds=4) <= delay < timedelta(seconds=8) for delay in delays if delay)
|
|
assert len(delays) > 150
|
|
|
|
|
|
def test_job_message_follows_the_contract_schema() -> None:
|
|
job = Job(uuid4(), uuid4(), 1, 3, datetime(2026, 9, 1, 12, 0, tzinfo=UTC))
|
|
payload = job.payload()
|
|
assert set(SCHEMA["required"]) <= set(payload) <= set(SCHEMA["properties"])
|
|
assert payload["schema_version"] == SCHEMA["properties"]["schema_version"]["const"]
|
|
assert payload["type"] == SCHEMA["properties"]["type"]["const"]
|
|
assert payload["created_at"] == "2026-09-01T12:00:00.000000Z"
|
|
assert JobMessage.model_validate_json(json.dumps(payload)).job() == job
|
|
assert job.retried(4).payload()["job_id"] == payload["job_id"]
|
|
|
|
|
|
@pytest.mark.parametrize("example", SCHEMA["examples"])
|
|
def test_contract_examples_are_accepted(example: dict[str, object]) -> None:
|
|
assert JobMessage.model_validate_json(json.dumps(example)).attempt == example["attempt"]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"change",
|
|
[
|
|
{"schema_version": 2},
|
|
{"type": "attachment.process.v2"},
|
|
{"attempt": 0},
|
|
{"pipeline_version": 0},
|
|
{"filename": "a.png"},
|
|
{"traceparent": "01-xyz"},
|
|
{"created_at": "2026-09-01T12:00:00"},
|
|
],
|
|
)
|
|
def test_messages_off_the_schema_are_rejected(change: dict[str, object]) -> None:
|
|
message = {**SCHEMA["examples"][0], **change}
|
|
with pytest.raises(ValueError, match="validation error"):
|
|
JobMessage.model_validate_json(json.dumps(message))
|
|
|
|
|
|
def test_variant_keys_carry_version_and_content_hash() -> None:
|
|
attachment = uuid4()
|
|
key = variant_key(attachment, 2, "thumbnail", "ab" * 32, "jpg")
|
|
assert key == f"variants/{attachment}/2/thumbnail-{'ab' * 8}.jpg"
|