Complete versioned attachment processing and fault invariants
This commit is contained in:
@@ -15,6 +15,9 @@ SCRIPTS_PY = scripts/capture_evidence.py alembic scripts/scaling.py tools script
|
||||
scripts/make_images.py scripts/pipeline_suite.py scripts/pipeline_evidence.py
|
||||
SCENARIO ?= failover-upload
|
||||
PSQL = $(COMPOSE) exec -T postgres psql -U messenger -d messenger -X -q
|
||||
TRACK2_OUTPUT ?= evidence/track2.json
|
||||
TRACK2_SCENARIOS = smoke_pipeline,duplicate_after_ready,crash_commit_publish,crash_publish_confirm,crash_after_s3_before_commit,crash_after_commit_before_ack,lease_expiry_fencing,crash_before_side_effect,worker_kill_mid_task,duplicate_in_flight,reorder_attempts,reorder_versions,stale_after_new_version
|
||||
PIPELINE_VERSION ?= 2
|
||||
PYTEST_ARGS ?=
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover \
|
||||
@@ -273,3 +276,12 @@ dlq:
|
||||
pipeline-evidence:
|
||||
$(PYTHON) scripts/pipeline_evidence.py --base-url "$(BASE_URL)" > evidence/pipeline-stand.txt; \
|
||||
status=$$?; cat evidence/pipeline-stand.txt; exit $$status
|
||||
|
||||
.PHONY: track2 reprocess
|
||||
|
||||
track2:
|
||||
BASE_URL="$(BASE_URL)" $(PYTHON) scripts/pipeline_suite.py --level 5 --only "$(TRACK2_SCENARIOS)" --output "$(TRACK2_OUTPUT)"
|
||||
|
||||
reprocess:
|
||||
@test -n "$(ID)" || (echo "Set ID=<attachment_id>"; exit 2)
|
||||
$(COMPOSE) run --rm --no-deps -T worker python -m messenger.admin reprocess --attachment-id "$(ID)" --pipeline-version "$(PIPELINE_VERSION)"
|
||||
|
||||
@@ -20,3 +20,5 @@ Production defaults: JOB_MAX_ATTEMPTS=5, lease=60 s, backoff base=2/cap=60 s, sw
|
||||
Первый прогон level4.txt был намеренно прерван SIGINT (exit -2), до failed_retention. Обнаруженный major: сценарий снижал глобальный retention до 1 s и мог удалить чужой staging. В e9ce6d0 исправлен только этот критичный риск: состаривается одна созданная suite строка по id+chat_id на действующий retention+1, глобальный retention не меняется. Исправленный сценарий прошёл; подробности findings.json. Прерванный прогон не считается успехом.
|
||||
|
||||
Minor из grade3/findings.json остаются: ошибочное сравнение порядка secrets в limits.py и legacy reconciler demo. Полный глобальный inventory S3 в suite отмечен SKIP; наличие удаления staging подтверждено отдельно для ready и expired failed. Сохранённая DLQ начиналась с 2 записей и выросла до 3 ровно от malformed message; данные не очищались. Итоговый REPORT выполняется отдельным агентом.
|
||||
|
||||
Уточнение инвентаризации: rc object list для пути отдельного файла возвращает пустой каталог и само по себе не доказывает отсутствие объекта. Прямой object stat в ready-staging-stat.txt вернул structured not_found (ожидаемый exit 5). Окончательная повторная квалификация уровня 4 в цикле трека 2 использует HEAD для staging/original и listing каталогов вариантов для каждого принятого ID; прежние пустые listing не считаются самостоятельным доказательством.
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
date: 2026-11-06T06:44:28Z commit: e9e1ce576c52dc91ded310bcd1f4f5920a215678
|
||||
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-sqlalchemy"}
|
||||
$ docker compose run --rm --no-deps -T s3-cli object stat --json root/messenger-attachments/staging/01a1af90-6ce1-71d3-bbcf-9f22d40268ea
|
||||
{
|
||||
"error": "Failed to inspect root/messenger-attachments/staging/01a1af90-6ce1-71d3-bbcf-9f22d40268ea: Not found: root/messenger-attachments/staging/01a1af90-6ce1-71d3-bbcf-9f22d40268ea",
|
||||
"code": 5,
|
||||
"details": {
|
||||
"type": "not_found",
|
||||
"message": "Failed to inspect root/messenger-attachments/staging/01a1af90-6ce1-71d3-bbcf-9f22d40268ea: Not found: root/messenger-attachments/staging/01a1af90-6ce1-71d3-bbcf-9f22d40268ea",
|
||||
"suggestion": "Check the alias, bucket, or object path and retry the command.",
|
||||
"retryable": false
|
||||
}
|
||||
}
|
||||
|
||||
exit_code: 5 elapsed_seconds: 0.373
|
||||
@@ -3,12 +3,12 @@
|
||||
- [x] 1.2 Проверить существующие ограничения/Alembic: новой схемы не требуется; Context7 SQLAlchemy и FastStream проверены.
|
||||
|
||||
## 2. Версии в attachments
|
||||
- [ ] 2.1 Добавить команду/результат, handler и SQLAlchemy JobRepository с сериализацией постановки и безопасным failure нескольких версий.
|
||||
- [ ] 2.2 Добавить recipe v1/v2 и передачу версии в отдельный render process.
|
||||
- [ ] 2.3 Связать операторский CLI, аудит и DI; проверить конкурентность, reorder, старого держателя и ошибки собственными тестами.
|
||||
- [x] 2.1 Добавить команду/результат, handler и SQLAlchemy JobRepository с сериализацией постановки и безопасным failure нескольких версий.
|
||||
- [x] 2.2 Добавить recipe v1/v2 и передачу версии в отдельный render process.
|
||||
- [x] 2.3 Связать операторский CLI, аудит и DI; проверить конкурентность, reorder, старого держателя и ошибки собственными тестами.
|
||||
|
||||
## 3. Доказательства
|
||||
- [ ] 3.1 Усилить suite: принудительное v2→v1, snapshots/hashes, scoped S3 inventory, фактический SIGKILL; make track2.
|
||||
- [x] 3.1 Усилить suite: принудительное v2→v1, snapshots/hashes, scoped S3 inventory, фактический SIGKILL; make track2.
|
||||
- [ ] 3.2 make check/validate/lint/student-test, сборка и публичные smoke/persistence/failover/restore на финальном коде.
|
||||
- [ ] 3.3 Полный level4 на финальном коде и три последовательных track2 с сырыми результатами.
|
||||
- [ ] 3.4 Сохранить методику/гипотезу/сравнение/ограничения, синхронизировать specs, архивировать завершённый change после make lint.
|
||||
|
||||
+82
-18
@@ -107,9 +107,11 @@ staging_left:
|
||||
WHERE id = ANY(:'ids'::uuid[]) AND status = 'ready' AND staging_key IS NOT NULL
|
||||
|
||||
object_keys:
|
||||
SELECT object_key AS key FROM attachment_variants
|
||||
UNION ALL SELECT original_key FROM attachments WHERE original_key IS NOT NULL
|
||||
UNION ALL SELECT staging_key FROM attachments WHERE staging_key IS NOT NULL
|
||||
SELECT object_key AS key FROM attachment_variants WHERE attachment_id = ANY(:'ids'::uuid[])
|
||||
UNION ALL SELECT original_key FROM attachments
|
||||
WHERE id = ANY(:'ids'::uuid[]) AND original_key IS NOT NULL
|
||||
UNION ALL SELECT staging_key FROM attachments
|
||||
WHERE id = ANY(:'ids'::uuid[]) AND staging_key IS NOT NULL
|
||||
|
||||
columns:
|
||||
SELECT table_name, column_name FROM information_schema.columns
|
||||
@@ -252,6 +254,35 @@ class Stack:
|
||||
out = self.rabbitmqadmin(*command, json.dumps(properties), stdin=json.dumps(payload))
|
||||
check("routed successfully" in out, "broker did not route the injected job")
|
||||
|
||||
def s3_json(self, *argv, missing=False):
|
||||
done = subprocess.run(
|
||||
[*self.base, "run", "--rm", "--no-deps", "-T", "s3-cli", *argv, "--json"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
check=False,
|
||||
)
|
||||
body = json.loads(done.stdout)
|
||||
if missing and done.returncode == 5 and body.get("details", {}).get("type") == "not_found":
|
||||
return None
|
||||
check(done.returncode == 0, "S3 inventory command failed: exit " + str(done.returncode))
|
||||
return body
|
||||
|
||||
def objects(self, ids):
|
||||
bucket = self.dc("exec", "-T", self.args.relay, "printenv", "S3_BUCKET").strip()
|
||||
keys = set()
|
||||
for ident in ids:
|
||||
for prefix in ("staging", "originals"):
|
||||
body = self.s3_json(
|
||||
"object", "stat", f"root/{bucket}/{prefix}/{ident}", missing=True
|
||||
)
|
||||
if body is not None:
|
||||
keys.add(body["name"])
|
||||
body = self.s3_json("object", "list", "--recursive", f"root/{bucket}/variants/{ident}/")
|
||||
check(not body["truncated"], "S3 variant inventory is truncated")
|
||||
keys.update(item["key"] for item in body["items"])
|
||||
return keys
|
||||
|
||||
def admin(self, *argv):
|
||||
command = shlex.split(self.args.admin) + list(argv)
|
||||
out = self.dc("run", "--rm", "--no-deps", "-T", self.args.worker, *command)
|
||||
@@ -728,11 +759,19 @@ class Suite:
|
||||
poll(lambda: self.record(ident)["status"] == "processing", 30, "processing")
|
||||
self.stack.kill(self.args.worker)
|
||||
code = self.stack.wait_exit(self.args.worker)
|
||||
containers = self.stack.dc(
|
||||
"ps", "-a", "--format", "{{.Name}} {{.ID}} {{.State}} {{.Status}}", self.args.worker
|
||||
).splitlines()
|
||||
self.stack.launch(self.args.worker)
|
||||
ready = self.api.wait(ident, timeout=self.args.recovery_timeout)
|
||||
self.drained()
|
||||
self.verify(ready)
|
||||
return {"attachment_id": ident, "exit_code": code, "jobs": self.stack.sql("jobs", id=ident)}
|
||||
return {
|
||||
"attachment_id": ident,
|
||||
"exit_code": code,
|
||||
"containers": containers,
|
||||
"jobs": self.stack.sql("jobs", id=ident),
|
||||
}
|
||||
|
||||
def duplicate_in_flight(self):
|
||||
self.stack.stop(self.args.worker)
|
||||
@@ -775,36 +814,52 @@ class Suite:
|
||||
def reorder_versions(self):
|
||||
self.stack.stop(self.args.worker, self.args.relay)
|
||||
ident = self.api.fixture()["id"]
|
||||
self.reprocess(ident)
|
||||
check(self.reprocess(ident)["result"] == "queued", "version 2 was not scheduled")
|
||||
check(self.reprocess(ident)["result"] == "noop", "duplicate reprocess was not a noop")
|
||||
self.stack.publish(self.payload(ident, 2))
|
||||
self.queued(1)
|
||||
self.stack.launch(self.args.relay)
|
||||
self.queued(3)
|
||||
self.stack.launch(self.args.worker)
|
||||
self.published(ident, 2)
|
||||
self.api.wait(ident)
|
||||
before = self.snapshot(ident)
|
||||
self.stack.launch(self.args.relay)
|
||||
poll(lambda: all(r["published"] for r in self.stack.sql("outbox", id=ident)), 30, "outbox")
|
||||
self.drained()
|
||||
final = self.snapshot(ident)
|
||||
check(final["published"] == 2, f"published_version rolled back to {final['published']}")
|
||||
check(before["public"] == final["public"], "late v1 changed the published v2 variants")
|
||||
served = {v["name"]: v["sha256"] for v in final["public"]}
|
||||
stored = {r["name"]: r["sha256"] for r in final["rows"] if r["pipeline_version"] == 2}
|
||||
check(served == stored, "API serves variants of a version that is not published")
|
||||
jobs = self.stack.sql("jobs", id=ident)
|
||||
check(
|
||||
{j["pipeline_version"]: j["status"] for j in jobs} == {1: "superseded", 2: "done"},
|
||||
"v1 did not finish after v2",
|
||||
)
|
||||
self.verify(self.api.get(ident))
|
||||
return {"attachment_id": ident, "jobs": self.stack.sql("jobs", id=ident)}
|
||||
return {"attachment_id": ident, "jobs": jobs, "v2_before_v1": before, "after_v1": final}
|
||||
|
||||
def stale_after_new_version(self):
|
||||
ident = self.api.fixture()["id"]
|
||||
self.api.wait(ident)
|
||||
self.reprocess(ident)
|
||||
first = self.snapshot(ident)
|
||||
check(self.reprocess(ident)["result"] == "queued", "version 2 was not scheduled")
|
||||
check(self.api.get(ident)["status"] == "ready", "reprocess rolled back ready")
|
||||
self.published(ident, 2)
|
||||
self.drained()
|
||||
before = self.snapshot(ident)
|
||||
check(first["public"] != before["public"], "recipes did not produce distinct results")
|
||||
self.stack.publish(self.payload(ident, 1))
|
||||
self.drained()
|
||||
time.sleep(1)
|
||||
after = self.snapshot(ident)
|
||||
check(before == after and after["published"] == 2, "stale v1 job changed the v2 result")
|
||||
return {"attachment_id": ident, "published_version": after["published"]}
|
||||
return {
|
||||
"attachment_id": ident,
|
||||
"published_version": after["published"],
|
||||
"v1": first,
|
||||
"v2_before_stale": before,
|
||||
"v2_after_stale": after,
|
||||
}
|
||||
|
||||
def invariants(self, dead_before):
|
||||
ids = self.api.accepted
|
||||
@@ -851,13 +906,21 @@ class Suite:
|
||||
check(queues[QUEUE] == (0, 0), "messages left in " + QUEUE)
|
||||
expected = dead_before + self.dead_letters
|
||||
check(queues[DLQ][0] == expected, f"unexpected dead letters: {queues[DLQ]}")
|
||||
if not self.args.s3_list:
|
||||
return {"queues": queues, "s3": "SKIP: --s3-list is not set"}
|
||||
keys = {r["key"] for r in self.stack.sql("object_keys")}
|
||||
listing = run(shlex.split(self.args.s3_list)).splitlines()
|
||||
stray = [k for k in (x.split()[-1] for x in listing if x.strip()) if k not in keys]
|
||||
check(not stray, f"S3 objects without metadata: {stray[:5]}")
|
||||
return {"queues": queues, "s3_objects": len(listing)}
|
||||
keys = {r["key"] for r in self.stack.sql("object_keys", ids=array)}
|
||||
if self.args.s3_list:
|
||||
listing = {
|
||||
x.split()[-1]
|
||||
for x in run(shlex.split(self.args.s3_list)).splitlines()
|
||||
if x.strip()
|
||||
}
|
||||
listing = {key for key in listing if any("/" + ident in key for ident in ids)}
|
||||
else:
|
||||
listing = self.stack.objects(ids)
|
||||
check(
|
||||
listing == keys,
|
||||
f"S3 mismatch: extra={sorted(listing - keys)}, missing={sorted(keys - listing)}",
|
||||
)
|
||||
return {"queues": queues, "s3_objects": len(listing), "scoped_attachments": len(ids)}
|
||||
|
||||
def no_loss():
|
||||
known = {r["id"] for r in self.stack.sql("known", ids=array)}
|
||||
@@ -958,6 +1021,7 @@ class Suite:
|
||||
finally:
|
||||
self.stack.up(self.args.s3)
|
||||
self.stack.restore()
|
||||
report["accepted_ids"] = self.api.accepted if self.api else []
|
||||
report["scenarios"] = results
|
||||
return self.finish(report, results + report.get("invariants", []))
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import sys
|
||||
|
||||
from dishka import make_async_container
|
||||
|
||||
from messenger.attachments.domain.jobs import ReplayResult
|
||||
from messenger.attachments.domain.jobs import ReplayResult, ReprocessResult
|
||||
from messenger.attachments.entrypoints.admin import rendered, run
|
||||
from messenger.attachments.entrypoints.ioc import AdminProvider
|
||||
from messenger.attachments.entrypoints.journal import LOG_FIELDS, subscribe_journal
|
||||
@@ -26,7 +26,7 @@ async def serve(argv: list[str]) -> int:
|
||||
await bus.stop()
|
||||
await container.close()
|
||||
sys.stdout.write(rendered(report) + "\n")
|
||||
return int(report.get("result") == ReplayResult.NOT_FOUND)
|
||||
return int(report.get("result") in (ReplayResult.NOT_FOUND, ReprocessResult.CONFLICT))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
@@ -49,6 +49,13 @@ class ReplayAttachment(Command):
|
||||
operator: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ReprocessAttachment(Command):
|
||||
attachment_id: UUID
|
||||
pipeline_version: int
|
||||
operator: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ReconcileStorage(Command):
|
||||
apply: bool
|
||||
|
||||
@@ -8,6 +8,7 @@ from messenger.attachments.application.commands import (
|
||||
PublishOutbox,
|
||||
RecoverExpiredLeases,
|
||||
ReplayAttachment,
|
||||
ReprocessAttachment,
|
||||
)
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentsUnitOfWork,
|
||||
@@ -18,20 +19,26 @@ from messenger.attachments.application.ports import (
|
||||
VariantRenderer,
|
||||
)
|
||||
from messenger.attachments.domain.errors import LeaseLost, UnreadableImage
|
||||
from messenger.attachments.domain.events import AttachmentReplayRequested, JobSettled
|
||||
from messenger.attachments.domain.events import (
|
||||
AttachmentReplayRequested,
|
||||
AttachmentReprocessRequested,
|
||||
JobSettled,
|
||||
)
|
||||
from messenger.attachments.domain.jobs import (
|
||||
PIPELINE_VERSIONS,
|
||||
Claim,
|
||||
FailureCode,
|
||||
Job,
|
||||
Lease,
|
||||
Outcome,
|
||||
ReplayResult,
|
||||
ReprocessResult,
|
||||
RetryPolicy,
|
||||
)
|
||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus, original_key
|
||||
from messenger.attachments.domain.variants import Variant, variant_key
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import IdGenerator
|
||||
from messenger.shared.application.ports import Clock, IdGenerator
|
||||
|
||||
TRANSIENT_ERROR = "transient_error"
|
||||
STALL_AFTER_CLAIM = "stall_after_claim"
|
||||
@@ -299,3 +306,39 @@ class ReplayAttachmentHandler:
|
||||
return ReplayResult.EXPIRED
|
||||
job = await self._uow.jobs.replay(attachment, operator)
|
||||
return ReplayResult.NOOP if job is None else ReplayResult.REPLAYED
|
||||
|
||||
|
||||
class ReprocessAttachmentHandler:
|
||||
__slots__ = ("_clock", "_ids", "_uow")
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork, ids: IdGenerator, clock: Clock) -> None:
|
||||
self._uow = uow
|
||||
self._ids = ids
|
||||
self._clock = clock
|
||||
|
||||
async def __call__(self, command: ReprocessAttachment) -> ReprocessResult:
|
||||
if command.pipeline_version not in PIPELINE_VERSIONS:
|
||||
raise ValueError("неподдерживаемая версия pipeline")
|
||||
async with self._uow.transaction():
|
||||
attachment = await self._uow.attachments.lock(command.attachment_id)
|
||||
result = await self._schedule(attachment, command)
|
||||
self._uow.record(
|
||||
AttachmentReprocessRequested(
|
||||
command.attachment_id, command.pipeline_version, command.operator, result.value
|
||||
)
|
||||
)
|
||||
await self._uow.commit()
|
||||
return result
|
||||
|
||||
async def _schedule(
|
||||
self, attachment: Attachment | None, command: ReprocessAttachment
|
||||
) -> ReprocessResult:
|
||||
if attachment is None:
|
||||
return ReprocessResult.NOT_FOUND
|
||||
if attachment.status in (AttachmentStatus.PENDING, AttachmentStatus.FAILED):
|
||||
return ReprocessResult.CONFLICT
|
||||
if command.pipeline_version <= attachment.published_version:
|
||||
return ReprocessResult.NOOP
|
||||
job = Job(self._ids.new_id(), attachment.id, command.pipeline_version, 1, self._clock.now())
|
||||
added = await self._uow.jobs.reprocess(job, command.operator)
|
||||
return ReprocessResult.QUEUED if added else ReprocessResult.NOOP
|
||||
|
||||
@@ -124,6 +124,8 @@ class AttachmentRepository(Protocol):
|
||||
class JobRepository(Protocol):
|
||||
async def add(self, job: Job) -> None: ...
|
||||
|
||||
async def reprocess(self, job: Job, operator: str) -> bool: ...
|
||||
|
||||
async def claim(self, job: Job, token: UUID, lease: timedelta) -> Claim | None: ...
|
||||
|
||||
async def complete(
|
||||
|
||||
@@ -33,6 +33,15 @@ class JobSettled(DomainEvent):
|
||||
name: str = field(init=False, default="job.settled")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentReprocessRequested(DomainEvent):
|
||||
attachment_id: UUID
|
||||
pipeline_version: int
|
||||
operator: str
|
||||
result: str
|
||||
name: str = field(init=False, default="attachment.reprocess_requested")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentReplayRequested(DomainEvent):
|
||||
attachment_id: UUID
|
||||
|
||||
@@ -6,6 +6,7 @@ from uuid import UUID
|
||||
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
SCHEMA_VERSION = 1
|
||||
PIPELINE_VERSIONS = (1, 2)
|
||||
|
||||
|
||||
class FailureCode(StrEnum):
|
||||
@@ -21,6 +22,13 @@ class ReplayResult(StrEnum):
|
||||
NOT_FOUND = "not_found"
|
||||
|
||||
|
||||
class ReprocessResult(StrEnum):
|
||||
QUEUED = "queued"
|
||||
NOOP = "noop"
|
||||
CONFLICT = "conflict"
|
||||
NOT_FOUND = "not_found"
|
||||
|
||||
|
||||
class Outcome(StrEnum):
|
||||
DONE = "done"
|
||||
DUPLICATE = "duplicate_noop"
|
||||
|
||||
@@ -9,9 +9,9 @@ from uuid import UUID
|
||||
from dishka import AsyncContainer
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import ReplayAttachment
|
||||
from messenger.attachments.application.commands import ReplayAttachment, ReprocessAttachment
|
||||
from messenger.attachments.application.ports import AttachmentDirectory
|
||||
from messenger.attachments.domain.jobs import ReplayResult
|
||||
from messenger.attachments.domain.jobs import PIPELINE_VERSIONS, ReplayResult, ReprocessResult
|
||||
|
||||
REGISTRY_LIMIT = 20
|
||||
|
||||
@@ -26,6 +26,10 @@ def parser() -> argparse.ArgumentParser:
|
||||
replay = commands.add_parser("replay", help="вернуть failed-вложение в очередь")
|
||||
replay.add_argument("--attachment-id", type=UUID, required=True)
|
||||
replay.add_argument("--operator", default=os.environ.get("OPERATOR", "cli"))
|
||||
reprocess = commands.add_parser("reprocess", help="поставить новую версию pipeline")
|
||||
reprocess.add_argument("--attachment-id", type=UUID, required=True)
|
||||
reprocess.add_argument("--pipeline-version", type=int, choices=PIPELINE_VERSIONS, required=True)
|
||||
reprocess.add_argument("--operator", default=os.environ.get("OPERATOR", "cli"))
|
||||
return root
|
||||
|
||||
|
||||
@@ -36,10 +40,20 @@ async def run(container: AsyncContainer, argv: list[str]) -> dict[str, Any]:
|
||||
directory = await scope.get(AttachmentDirectory)
|
||||
return {"failed": [asdict(job) for job in await directory.failed_jobs(args.limit)]}
|
||||
bus = await scope.get(AttachmentsCommandBus)
|
||||
result: ReplayResult = await bus.execute(
|
||||
ReplayAttachment(args.attachment_id, args.operator)
|
||||
command = (
|
||||
ReprocessAttachment(args.attachment_id, args.pipeline_version, args.operator)
|
||||
if args.command == "reprocess"
|
||||
else ReplayAttachment(args.attachment_id, args.operator)
|
||||
)
|
||||
return {"result": result.value, "attachment_id": args.attachment_id, "operator": args.operator}
|
||||
result: ReplayResult | ReprocessResult = await bus.execute(command)
|
||||
report = {
|
||||
"result": result.value,
|
||||
"attachment_id": args.attachment_id,
|
||||
"operator": args.operator,
|
||||
}
|
||||
if args.command == "reprocess":
|
||||
report["pipeline_version"] = args.pipeline_version
|
||||
return report
|
||||
|
||||
|
||||
def plain(value: object) -> str:
|
||||
|
||||
@@ -12,6 +12,7 @@ from messenger.attachments.application.commands import (
|
||||
PublishOutbox,
|
||||
RecoverExpiredLeases,
|
||||
ReplayAttachment,
|
||||
ReprocessAttachment,
|
||||
SweepAbandonedUploads,
|
||||
UploadAttachment,
|
||||
)
|
||||
@@ -26,6 +27,7 @@ from messenger.attachments.application.pipeline import (
|
||||
PublishOutboxHandler,
|
||||
RecoverExpiredLeasesHandler,
|
||||
ReplayAttachmentHandler,
|
||||
ReprocessAttachmentHandler,
|
||||
)
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentDirectory,
|
||||
@@ -262,9 +264,10 @@ class AdminProvider(Provider):
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self, uow: AttachmentsUnitOfWork, publisher: EventPublisher
|
||||
self, uow: AttachmentsUnitOfWork, publisher: EventPublisher, ids: IdGenerator, clock: Clock
|
||||
) -> AttachmentsCommandBus:
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
ReplayAttachment: ReplayAttachmentHandler(uow)
|
||||
ReplayAttachment: ReplayAttachmentHandler(uow),
|
||||
ReprocessAttachment: ReprocessAttachmentHandler(uow, ids, clock),
|
||||
}
|
||||
return AttachmentsCommandBus(handlers, uow, publisher)
|
||||
|
||||
@@ -2,6 +2,7 @@ from messenger.attachments.domain.events import (
|
||||
AttachmentDiscarded,
|
||||
AttachmentQueued,
|
||||
AttachmentReplayRequested,
|
||||
AttachmentReprocessRequested,
|
||||
JobSettled,
|
||||
)
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
@@ -69,6 +70,15 @@ class AttachmentsJournal:
|
||||
result=event.result,
|
||||
)
|
||||
|
||||
async def on_reprocess_requested(self, event: AttachmentReprocessRequested) -> None:
|
||||
self._logger.info(
|
||||
"audit.attachment_reprocess",
|
||||
attachment_id=str(event.attachment_id),
|
||||
pipeline_version=event.pipeline_version,
|
||||
operator=event.operator,
|
||||
result=event.result,
|
||||
)
|
||||
|
||||
|
||||
def subscribe_journal(bus: EventBus, logger: Logger) -> None:
|
||||
journal = AttachmentsJournal(logger)
|
||||
@@ -76,3 +86,4 @@ def subscribe_journal(bus: EventBus, logger: Logger) -> None:
|
||||
bus.subscribe(AttachmentDiscarded, journal.on_attachment_discarded)
|
||||
bus.subscribe(JobSettled, journal.on_job_settled)
|
||||
bus.subscribe(AttachmentReplayRequested, journal.on_replay_requested)
|
||||
bus.subscribe(AttachmentReprocessRequested, journal.on_reprocess_requested)
|
||||
|
||||
@@ -34,8 +34,8 @@ BOMBS = (Image.DecompressionBombError, Image.DecompressionBombWarning)
|
||||
JPEG_SCALE = 8
|
||||
WIDE_MODES = frozenset({"I", "I;16", "I;16B", "I;16L", "I;16N"})
|
||||
ALPHA_MODES = frozenset({"LA", "La", "PA", "RGBa"})
|
||||
JPEG = {"quality": 85, "optimize": True}
|
||||
WEBP = {"quality": 80, "method": 4}
|
||||
JPEG = {1: {"quality": 85, "optimize": True}, 2: {"quality": 90, "optimize": True}}
|
||||
WEBP = {1: {"quality": 80, "method": 4}, 2: {"quality": 85, "method": 4}}
|
||||
ENCODINGS = {"JPEG": (ImageKind.JPEG.value, "jpg"), "WEBP": ("image/webp", "webp")}
|
||||
REDUCING_GAP = 3.0
|
||||
|
||||
@@ -128,15 +128,27 @@ def decoded(data: bytes, max_pixels: int) -> tuple[Image.Image, int, int]:
|
||||
raise UnreadableImage("изображение не декодируется") from error
|
||||
|
||||
|
||||
def render_variants(data: bytes, limits: RenderLimits) -> list[Rendition]:
|
||||
def render_variants(
|
||||
data: bytes, limits: RenderLimits, pipeline_version: int = 1
|
||||
) -> list[Rendition]:
|
||||
if len(data) > limits.max_bytes:
|
||||
raise ImageTooDemanding("оригинал больше допустимого размера")
|
||||
upright, width, height = decoded(data, limits.max_pixels)
|
||||
square = ImageOps.fit(upright, (CROP_SIDE, CROP_SIDE), Image.Resampling.LANCZOS)
|
||||
return [
|
||||
encoded(THUMBNAIL, scaled(upright, fit(width, height, THUMBNAIL_BOX)), "JPEG", **JPEG),
|
||||
encoded(CROP, square, "JPEG", **JPEG),
|
||||
encoded(OPTIMIZED, scaled(upright, fit(width, height, OPTIMIZED_BOX)), "WEBP", **WEBP),
|
||||
encoded(
|
||||
THUMBNAIL,
|
||||
scaled(upright, fit(width, height, THUMBNAIL_BOX)),
|
||||
"JPEG",
|
||||
**JPEG[pipeline_version],
|
||||
),
|
||||
encoded(CROP, square, "JPEG", **JPEG[pipeline_version]),
|
||||
encoded(
|
||||
OPTIMIZED,
|
||||
scaled(upright, fit(width, height, OPTIMIZED_BOX)),
|
||||
"WEBP",
|
||||
**WEBP[pipeline_version],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@@ -145,7 +157,7 @@ def limit_memory(limit_bytes: int) -> None:
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit_bytes, limit_bytes))
|
||||
|
||||
|
||||
type Render = Callable[[bytes, RenderLimits], list[Rendition]]
|
||||
type Render = Callable[[bytes, RenderLimits, int], list[Rendition]]
|
||||
|
||||
|
||||
class ProcessVariantRenderer:
|
||||
@@ -173,7 +185,9 @@ class ProcessVariantRenderer:
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
pool = await self._idle.get()
|
||||
try:
|
||||
future = asyncio.wrap_future(pool.submit(self._render, data, self._limits))
|
||||
future = asyncio.wrap_future(
|
||||
pool.submit(self._render, data, self._limits, pipeline_version)
|
||||
)
|
||||
return await asyncio.wait_for(future, self._timeout)
|
||||
except TimeoutError as error:
|
||||
pool = self._replace(pool)
|
||||
|
||||
@@ -519,6 +519,19 @@ class PostgresJobRepository:
|
||||
await self._enqueue(job)
|
||||
await self._note(job, "enqueued")
|
||||
|
||||
async def reprocess(self, job: Job, operator: str) -> bool:
|
||||
existing = await self._session.scalar(
|
||||
select(JobRow.job_id).where(
|
||||
JobRow.attachment_id == job.attachment_id,
|
||||
JobRow.pipeline_version == job.pipeline_version,
|
||||
)
|
||||
)
|
||||
if existing is not None:
|
||||
return False
|
||||
await self.add(job)
|
||||
await self._note(job, "reprocess_requested", {"operator": operator})
|
||||
return True
|
||||
|
||||
async def claim(self, job: Job, token: UUID, lease: timedelta) -> Claim | None:
|
||||
row = (
|
||||
await self._session.execute(
|
||||
@@ -686,8 +699,31 @@ class PostgresJobRepository:
|
||||
)
|
||||
if attempt is None:
|
||||
return False
|
||||
await self._move(
|
||||
lease.job.attachment_id, ["queued", "processing"], "failed", error_code=code.value
|
||||
await self._session.execute(
|
||||
select(AttachmentRow.id)
|
||||
.where(AttachmentRow.id == lease.job.attachment_id)
|
||||
.with_for_update()
|
||||
)
|
||||
active = (
|
||||
select(JobRow.job_id)
|
||||
.where(
|
||||
JobRow.attachment_id == lease.job.attachment_id,
|
||||
JobRow.status.in_(["queued", "processing"]),
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
await self._session.execute(
|
||||
update(AttachmentRow)
|
||||
.where(
|
||||
AttachmentRow.id == lease.job.attachment_id,
|
||||
AttachmentRow.status.in_(["queued", "processing"]),
|
||||
~active,
|
||||
)
|
||||
.values(
|
||||
status="failed",
|
||||
error_code=code.value,
|
||||
updated_at=func.greatest(func.now(), AttachmentRow.created_at),
|
||||
)
|
||||
)
|
||||
await self._note(
|
||||
lease.job.retried(attempt), "failed", {"error_code": code.value, "error": error}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import asyncio
|
||||
import json
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from test_pipeline import accepted, job_of, rows
|
||||
|
||||
from conftest import DATABASE, actor
|
||||
from messenger.admin import serve
|
||||
from messenger.attachments.application.commands import ReprocessAttachment
|
||||
from messenger.attachments.application.pipeline import AFTER_S3_WRITE, ReprocessAttachmentHandler
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.errors import ImageTooDemanding
|
||||
from messenger.attachments.domain.jobs import Outcome, ReprocessResult
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
from messenger.shared.infrastructure.ids import Uuid7Generator
|
||||
from pipeline import InlinePipeline, InlineRenderer, pipeline_of
|
||||
|
||||
|
||||
async def reprocess(pipeline: InlinePipeline, ident: str, version: int = 2) -> ReprocessResult:
|
||||
handler = ReprocessAttachmentHandler(pipeline.uow(), Uuid7Generator(), MonotonicUtcClock())
|
||||
return await handler(ReprocessAttachment(UUID(ident), version, "test"))
|
||||
|
||||
|
||||
async def attachment(ident: str) -> dict:
|
||||
(row,) = await rows(
|
||||
"SELECT status, published_version, error_code FROM attachments WHERE id = $1", ident
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
async def versions(pipeline: InlinePipeline, ident: str) -> dict:
|
||||
return {
|
||||
job.pipeline_version: job
|
||||
for job in await pipeline.publish()
|
||||
if str(job.attachment_id) == ident
|
||||
}
|
||||
|
||||
|
||||
async def test_concurrent_reprocess_creates_one_job_and_outbox(client: AsyncClient) -> None:
|
||||
_, _, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
results = await asyncio.gather(*(reprocess(pipeline, ident) for _ in range(6)))
|
||||
assert results.count(ReprocessResult.QUEUED) == 1
|
||||
assert results.count(ReprocessResult.NOOP) == 5
|
||||
jobs = await rows(
|
||||
"SELECT pipeline_version, count(*) FROM jobs WHERE attachment_id = $1 GROUP BY 1", ident
|
||||
)
|
||||
assert {r["pipeline_version"]: r["count"] for r in jobs} == {1: 1, 2: 1}
|
||||
assert len(await versions(pipeline, ident)) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("order", [(1, 2), (2, 1)])
|
||||
async def test_version_order_never_reverts_published_bytes(
|
||||
client: AsyncClient, order: tuple[int, int]
|
||||
) -> None:
|
||||
_, bob, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
|
||||
jobs = await versions(pipeline, ident)
|
||||
for version in order:
|
||||
outcome = await pipeline.process(jobs[version])
|
||||
assert outcome is (Outcome.SUPERSEDED if order == (2, 1) and version == 1 else Outcome.DONE)
|
||||
assert (await attachment(ident))["status"] == "ready"
|
||||
await pipeline.clean()
|
||||
assert (await attachment(ident))["published_version"] == 2
|
||||
public = (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json()
|
||||
stored = await rows(
|
||||
"SELECT pipeline_version, name, sha256 FROM attachment_variants WHERE attachment_id = $1",
|
||||
ident,
|
||||
)
|
||||
current = {r["name"]: r["sha256"] for r in stored if r["pipeline_version"] == 2}
|
||||
older = {r["name"]: r["sha256"] for r in stored if r["pipeline_version"] == 1}
|
||||
assert current != older
|
||||
assert {r["name"]: r["sha256"] for r in public["variants"]} == current
|
||||
assert await pipeline.process(jobs[1]) is Outcome.DUPLICATE
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.NOOP
|
||||
assert (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json() == public
|
||||
|
||||
|
||||
class PausedEffect:
|
||||
def __init__(self) -> None:
|
||||
self.reached = asyncio.Event()
|
||||
self.resume = asyncio.Event()
|
||||
|
||||
async def reach(self, point: str) -> None:
|
||||
if point == AFTER_S3_WRITE:
|
||||
self.reached.set()
|
||||
await self.resume.wait()
|
||||
|
||||
|
||||
async def test_old_holder_finishes_after_new_publication(client: AsyncClient) -> None:
|
||||
_, bob, ident = await accepted(client)
|
||||
old, new = await pipeline_of(client), await pipeline_of(client)
|
||||
old.faults = pause = PausedEffect()
|
||||
job = await job_of(ident)
|
||||
running = asyncio.create_task(old.process(job))
|
||||
try:
|
||||
await asyncio.wait_for(pause.reached.wait(), 5)
|
||||
assert await reprocess(new, ident) is ReprocessResult.QUEUED
|
||||
jobs = await versions(new, ident)
|
||||
assert await new.process(jobs[2]) is Outcome.DONE
|
||||
public = (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json()
|
||||
pause.resume.set()
|
||||
assert await asyncio.wait_for(running, 5) is Outcome.SUPERSEDED
|
||||
assert (await attachment(ident))["published_version"] == 2
|
||||
assert (
|
||||
await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))
|
||||
).json() == public
|
||||
finally:
|
||||
pause.resume.set()
|
||||
await running
|
||||
|
||||
|
||||
class RejectingRenderer:
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
raise ImageTooDemanding("test limit")
|
||||
|
||||
|
||||
async def test_failed_old_version_keeps_other_version_active(client: AsyncClient) -> None:
|
||||
_, _, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
|
||||
jobs = await versions(pipeline, ident)
|
||||
pipeline.renderer = RejectingRenderer()
|
||||
assert await pipeline.process(jobs[1]) is Outcome.FAILED
|
||||
assert (await attachment(ident))["status"] in ("queued", "processing")
|
||||
pipeline.renderer = InlineRenderer()
|
||||
assert await pipeline.process(jobs[2]) is Outcome.DONE
|
||||
assert (await attachment(ident))["published_version"] == 2
|
||||
|
||||
|
||||
async def test_concurrent_failures_leave_no_stuck_attachment(client: AsyncClient) -> None:
|
||||
_, _, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
|
||||
jobs = await versions(pipeline, ident)
|
||||
pipeline.renderer = RejectingRenderer()
|
||||
assert await asyncio.gather(*(pipeline.process(job) for job in jobs.values())) == [
|
||||
Outcome.FAILED,
|
||||
Outcome.FAILED,
|
||||
]
|
||||
assert (await attachment(ident))["status"] == "failed"
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.CONFLICT
|
||||
assert await pipeline.publish() == []
|
||||
|
||||
|
||||
async def test_failed_new_version_keeps_ready_original(client: AsyncClient) -> None:
|
||||
_, bob, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
public = (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json()
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
|
||||
assert (await attachment(ident))["status"] == "ready"
|
||||
jobs = await versions(pipeline, ident)
|
||||
pipeline.renderer = RejectingRenderer()
|
||||
assert await pipeline.process(jobs[2]) is Outcome.FAILED
|
||||
assert (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json() == public
|
||||
|
||||
|
||||
async def test_reprocess_rejects_unknown_id_and_version(client: AsyncClient) -> None:
|
||||
pipeline = await pipeline_of(client)
|
||||
assert await reprocess(pipeline, str(uuid4())) is ReprocessResult.NOT_FOUND
|
||||
with pytest.raises(ValueError, match="версия"):
|
||||
await reprocess(pipeline, str(uuid4()), 3)
|
||||
|
||||
|
||||
async def test_operator_cli_schedules_version_once(
|
||||
client: AsyncClient, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
_, _, ident = await accepted(client)
|
||||
monkeypatch.setenv("DATABASE_URL", DATABASE["url"])
|
||||
monkeypatch.setenv("LOG_LEVEL", "WARNING")
|
||||
args = ["reprocess", "--attachment-id", ident, "--pipeline-version", "2"]
|
||||
for expected in ("queued", "noop"):
|
||||
assert await serve(args) == 0
|
||||
report = json.loads(capsys.readouterr().out.splitlines()[-1])
|
||||
assert report["result"] == expected
|
||||
assert report["pipeline_version"] == 2
|
||||
@@ -56,7 +56,7 @@ class InlineRenderer:
|
||||
__slots__ = ()
|
||||
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
return render_variants(data, LIMITS)
|
||||
return render_variants(data, LIMITS, pipeline_version)
|
||||
|
||||
|
||||
class CapturingPublisher:
|
||||
|
||||
@@ -20,7 +20,7 @@ LIMITS = RenderLimits(max_bytes=10_485_760, max_pixels=40_000_000)
|
||||
HOG_BYTES = 512 << 20
|
||||
|
||||
|
||||
def misbehaving(data: bytes, limits: RenderLimits) -> list[Rendition]:
|
||||
def misbehaving(data: bytes, limits: RenderLimits, pipeline_version: int) -> list[Rendition]:
|
||||
if data == b"slow":
|
||||
time.sleep(30)
|
||||
if data == b"crash":
|
||||
@@ -29,7 +29,7 @@ def misbehaving(data: bytes, limits: RenderLimits) -> list[Rendition]:
|
||||
raise MemoryError
|
||||
if data == b"hog":
|
||||
bytearray(HOG_BYTES)
|
||||
return render_variants(data, limits)
|
||||
return render_variants(data, limits, pipeline_version)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -89,3 +89,11 @@ async def test_address_space_limit_applies_to_the_render_process(
|
||||
) -> None:
|
||||
with pytest.raises(ImageTooDemanding):
|
||||
await renderer.render(b"hog", 1)
|
||||
|
||||
|
||||
async def test_process_uses_the_requested_recipe(renderer: ProcessVariantRenderer) -> None:
|
||||
first = await renderer.render(SAMPLE, 1)
|
||||
second = await renderer.render(SAMPLE, 2)
|
||||
assert second == render_variants(SAMPLE, LIMITS, 2)
|
||||
assert first != second
|
||||
assert await renderer.render(SAMPLE, 2) == second
|
||||
|
||||
Reference in New Issue
Block a user