This commit is contained in:
2026-10-25 21:43:03 +03:00
parent 276dbdad8a
commit a591243d80
103 changed files with 10857 additions and 36 deletions
+29
View File
@@ -0,0 +1,29 @@
python student-tests/attachment_failover.py
uploaded 111817 bytes -> 202 queued, sha256 99ea7533c441f79c..., served by api replica b0db3e40abfe
SERVICE CONTAINER STATE STARTED AT (UTC)
api b0db3e40abfe running (healthy) 2026-10-25T18:23:36.991
api ef44b0d4c0a1 running (healthy) 2026-10-25T18:23:36.756
broker 9f909ed7ecea running (healthy) 2026-10-25T18:23:53.670
lb 8be67a2e86b7 running (healthy) 2026-10-25T18:20:04.043
migrate e6c2c825d38d exited 2026-10-25T18:28:07.167
postgres d2bfd48385f1 running (healthy) 2026-10-25T18:19:54.204
s3 892c7ca290f2 running (healthy) 2026-10-25T18:19:54.206
s3-init 08c2e7925d67 exited 2026-10-25T18:28:07.169
valkey 4e223cb9301e running (healthy) 2026-10-25T18:19:54.202
worker d9eced386d93 running (healthy) 2026-10-25T18:28:09.870
stopped b0db3e40abfe (docker stop) right after 202; HAProxy: api1 DOWN, api2 UP
the worker finished the job without that replica: status ready, variants ['thumbnail', 'crop', 'optimized']
downloaded 4 times through ['ef44b0d4c0a1']: same SHA-256 as uploaded
restored b0db3e40abfe; HAProxy: api1 UP, api2 UP
SERVICE CONTAINER STATE STARTED AT (UTC)
api b0db3e40abfe running (healthy) 2026-10-25T18:28:33.999
api ef44b0d4c0a1 running (healthy) 2026-10-25T18:23:36.756
broker 9f909ed7ecea running (healthy) 2026-10-25T18:23:53.670
lb 8be67a2e86b7 running (healthy) 2026-10-25T18:20:04.043
migrate e6c2c825d38d exited 2026-10-25T18:28:07.167
postgres d2bfd48385f1 running (healthy) 2026-10-25T18:19:54.204
s3 892c7ca290f2 running (healthy) 2026-10-25T18:19:54.206
s3-init 08c2e7925d67 exited 2026-10-25T18:28:07.169
valkey 4e223cb9301e running (healthy) 2026-10-25T18:19:54.202
worker d9eced386d93 running (healthy) 2026-10-25T18:28:09.870
PASS: the replica that accepted the upload was stopped right after 202; the job still became ready and another replica returned the same bytes (the original lives in S3, not on the replica)
+2
View File
@@ -0,0 +1,2 @@
python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
+13
View File
@@ -0,0 +1,13 @@
python student-tests/concurrency.py
time s | processing (DB) | unacked (broker) | waiting in queue
2.5 | 2 | 0 | 0
7.1 | 2 | 2 | 4
10.4 | 2 | 2 | 2
13.4 | 2 | 2 | 2
16.1 | 2 | 2 | 2
20.5 | 2 | 2 | 0
23.3 | 2 | 2 | 0
26.5 | 2 | 2 | 0
29.4 | 0 | 0 | 0
peak: 2 jobs in processing, 2 unacknowledged messages, up to 4 waiting in the queue; all 6 ready after 29.4 s
PASS: at most WORKER_CONCURRENCY=2 jobs run at once and the broker gives the worker at most prefetch=2 messages; the rest wait in the durable queue
+43
View File
@@ -0,0 +1,43 @@
docker compose --profile tools run --rm db-test
Container mtusi-lab5-postgres-1 Running
Container mtusi-lab5-postgres-1 Waiting
Container mtusi-lab5-postgres-1 Healthy
Container mtusi-lab5-db-test-run-436c3e33e3cf Creating
Container mtusi-lab5-db-test-run-436c3e33e3cf Created
test_backoff_bounds (test_jobs.JobsIntegrationTest.test_backoff_bounds) ... ok
test_claim_once_and_concurrent_claims (test_jobs.JobsIntegrationTest.test_claim_once_and_concurrent_claims) ...
10 concurrent claims of one job: 1 claimed, 9 in_progress
ok
test_expired_lease_and_dead_predecessor (test_jobs.JobsIntegrationTest.test_expired_lease_and_dead_predecessor) ... ok
test_fencing_and_duplicates (test_jobs.JobsIntegrationTest.test_fencing_and_duplicates) ... ok
test_outbox_rows_are_taken_by_one_relay (test_jobs.JobsIntegrationTest.test_outbox_rows_are_taken_by_one_relay) ... ok
test_permanent_error_fails_at_once (test_jobs.JobsIntegrationTest.test_permanent_error_fails_at_once) ... ok
test_replay_rules (test_jobs.JobsIntegrationTest.test_replay_rules) ... ok
test_retry_backoff_then_exhausted (test_jobs.JobsIntegrationTest.test_retry_backoff_then_exhausted) ... ok
test_upload_creates_job_and_outbox_in_one_transaction (test_jobs.JobsIntegrationTest.test_upload_creates_job_and_outbox_in_one_transaction) ... ok
test_concurrent_registration_has_one_winner (test_store.StoreIntegrationTest.test_concurrent_registration_has_one_winner) ... ok
test_concurrent_same_idempotency_key_creates_one_row (test_store.StoreIntegrationTest.test_concurrent_same_idempotency_key_creates_one_row) ...
20 параллельных create_user: 1 создан, 19 получили Conflict (409)
ok
test_create_chat_rolls_back_when_failing_midway (test_store.StoreIntegrationTest.test_create_chat_rolls_back_when_failing_midway) ...
20 одновременных add_message с одним ключом: 1 строка, 1 новое + 19 повторов с тем же сообщением
чат с несуществующим участником: транзакция откатилась, строк chats/chat_members не осталось
ok
test_database_rejects_message_from_non_member (test_store.StoreIntegrationTest.test_database_rejects_message_from_non_member) ...
INSERT сообщения от не-участника напрямую в БД: ForeignKeyViolation
ok
test_migrations_rerun_is_noop (test_store.StoreIntegrationTest.test_migrations_rerun_is_noop) ...
schema_migrations: ['001_core', '002_sessions', '003_text_as_bytes', '004_message_idempotency', '005_attachments', '006_jobs']; повторный migrate() ничего не применил
ok
test_old_version_insert_without_key_still_works (test_store.StoreIntegrationTest.test_old_version_insert_without_key_still_works) ...
INSERT как в lab2 (без ключа) после миграции 004 работает: старая версия совместима со схемой
ok
test_same_key_other_body_is_conflict (test_store.StoreIntegrationTest.test_same_key_other_body_is_conflict) ...
тот же ключ с другим телом: Conflict (409), в базе по-прежнему одна строка
ok
----------------------------------------------------------------------
Ran 16 tests in 0.624s
OK
+64
View File
@@ -0,0 +1,64 @@
python student-tests/run_failover.py
hook: scripts/stop-one.cmd; api replicas: ['b0db3e40abfe', 'ef44b0d4c0a1']
=== run 1: containers before (HAProxy: api1 UP, api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api b0db3e40abfe running (healthy) 2026-10-25T18:28:33.999
api ef44b0d4c0a1 running (healthy) 2026-10-25T18:23:36.756
broker 9f909ed7ecea running (healthy) 2026-10-25T18:23:53.670
lb 8be67a2e86b7 running (healthy) 2026-10-25T18:20:04.043
migrate e6c2c825d38d exited 2026-10-25T18:28:07.167
postgres d2bfd48385f1 running (healthy) 2026-10-25T18:19:54.204
s3 892c7ca290f2 running (healthy) 2026-10-25T18:29:00.995
s3-init 08c2e7925d67 exited 2026-10-25T18:28:07.169
valkey 4e223cb9301e running (healthy) 2026-10-25T18:19:54.202
worker d9eced386d93 running (healthy) 2026-10-25T18:28:09.870
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 119, "failed_attempts": 0, "first_recovery_seconds": 5.11}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
containers after (HAProxy: api1 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api b0db3e40abfe running (healthy) 2026-10-25T18:28:33.999
api ef44b0d4c0a1 exited 2026-10-25T18:23:36.756
broker 9f909ed7ecea running (healthy) 2026-10-25T18:23:53.670
lb 8be67a2e86b7 running (healthy) 2026-10-25T18:20:04.043
migrate e6c2c825d38d exited 2026-10-25T18:28:07.167
postgres d2bfd48385f1 running (healthy) 2026-10-25T18:19:54.204
s3 892c7ca290f2 running (healthy) 2026-10-25T18:29:00.995
s3-init 08c2e7925d67 exited 2026-10-25T18:28:07.169
valkey 4e223cb9301e running (healthy) 2026-10-25T18:19:54.202
worker d9eced386d93 running (healthy) 2026-10-25T18:28:09.870
the hook stopped ef44b0d4c0a1 (X-Instance-Id of that replica = container ID); other api containers, postgres, valkey, s3 and lb kept running
restored: docker start ef44b0d4c0a1 -> healthy and back in HAProxy (api1 UP, api2 UP)
=== run 2: containers before (HAProxy: api1 UP, api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api b0db3e40abfe running (healthy) 2026-10-25T18:28:33.999
api ef44b0d4c0a1 running (healthy) 2026-10-25T18:30:14.430
broker 9f909ed7ecea running (healthy) 2026-10-25T18:23:53.670
lb 8be67a2e86b7 running (healthy) 2026-10-25T18:20:04.043
migrate e6c2c825d38d exited 2026-10-25T18:28:07.167
postgres d2bfd48385f1 running (healthy) 2026-10-25T18:19:54.204
s3 892c7ca290f2 running (healthy) 2026-10-25T18:29:00.995
s3-init 08c2e7925d67 exited 2026-10-25T18:28:07.169
valkey 4e223cb9301e running (healthy) 2026-10-25T18:19:54.202
worker d9eced386d93 running (healthy) 2026-10-25T18:28:09.870
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 125, "failed_attempts": 0, "first_recovery_seconds": 5.531}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
containers after (HAProxy: api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api b0db3e40abfe exited 2026-10-25T18:28:33.999
api ef44b0d4c0a1 running (healthy) 2026-10-25T18:30:14.430
broker 9f909ed7ecea running (healthy) 2026-10-25T18:23:53.670
lb 8be67a2e86b7 running (healthy) 2026-10-25T18:20:04.043
migrate e6c2c825d38d exited 2026-10-25T18:28:07.167
postgres d2bfd48385f1 running (healthy) 2026-10-25T18:19:54.204
s3 892c7ca290f2 running (healthy) 2026-10-25T18:29:00.995
s3-init 08c2e7925d67 exited 2026-10-25T18:28:07.169
valkey 4e223cb9301e running (healthy) 2026-10-25T18:19:54.202
worker d9eced386d93 running (healthy) 2026-10-25T18:28:09.870
the hook stopped b0db3e40abfe (X-Instance-Id of that replica = container ID); other api containers, postgres, valkey, s3 and lb kept running
restored: docker start b0db3e40abfe -> healthy and back in HAProxy (api1 UP, api2 UP)
PASS: public failover test passed 2 times; every api replica was stopped once and restored
+36
View File
@@ -0,0 +1,36 @@
python student-tests/failure_s3.py
=== s3 stopped
SERVICE CONTAINER STATE STARTED AT (UTC)
api b0db3e40abfe running (healthy) 2026-10-25T18:28:33.999
api ef44b0d4c0a1 running (healthy) 2026-10-25T18:23:36.756
broker 9f909ed7ecea running (healthy) 2026-10-25T18:23:53.670
lb 8be67a2e86b7 running (healthy) 2026-10-25T18:20:04.043
migrate e6c2c825d38d exited 2026-10-25T18:28:07.167
postgres d2bfd48385f1 running (healthy) 2026-10-25T18:19:54.204
s3 892c7ca290f2 exited 2026-10-25T18:19:54.206
s3-init 08c2e7925d67 exited 2026-10-25T18:28:07.169
valkey 4e223cb9301e running (healthy) 2026-10-25T18:19:54.202
worker d9eced386d93 running (healthy) 2026-10-25T18:28:09.870
both api replicas are out of the balancer after 1.0 s: api1 DOWN, api2 DOWN
replica b0db3e40abfe: /health/live 200, /health/ready 503
replica ef44b0d4c0a1: /health/live 200, /health/ready 503
GET /health/ready -> 503 unavailable in 0.00 s (answered by the balancer)
POST /api/v1/chats/6f457b5b-fe8c-45c4-a569-dcb9e04b2539/attachments -> 503 unavailable in 0.00 s (answered by the balancer)
GET /api/v1/attachments/9605875a-7999-471f-8e6b-500c0d99ccb6/content -> 503 unavailable in 0.00 s (answered by the balancer)
GET /api/v1/chats/6f457b5b-fe8c-45c4-a569-dcb9e04b2539/messages -> 503 unavailable in 0.00 s (answered by the balancer)
=== s3 started
replicas are back in the balancer after 23.7 s: api1 UP, api2 UP
the file uploaded before the outage is intact (sha256 99ea7533c441f79c...)
new upload -> 202 -> ready (cd112988-40ba-4267-951d-033ea82b1ca3)
SERVICE CONTAINER STATE STARTED AT (UTC)
api b0db3e40abfe running (healthy) 2026-10-25T18:28:33.999
api ef44b0d4c0a1 running (healthy) 2026-10-25T18:23:36.756
broker 9f909ed7ecea running (healthy) 2026-10-25T18:23:53.670
lb 8be67a2e86b7 running (healthy) 2026-10-25T18:20:04.043
migrate e6c2c825d38d exited 2026-10-25T18:28:07.167
postgres d2bfd48385f1 running (healthy) 2026-10-25T18:19:54.204
s3 892c7ca290f2 running (healthy) 2026-10-25T18:29:00.995
s3-init 08c2e7925d67 exited 2026-10-25T18:28:07.169
valkey 4e223cb9301e running (healthy) 2026-10-25T18:19:54.202
worker d9eced386d93 running (healthy) 2026-10-25T18:28:09.870
PASS: S3 down -> replicas not ready (live 200, ready 503), the balancer answers 503 in the contract format, no 500 and no hanging; after S3 is back the original is intact and uploads work again
+23
View File
@@ -0,0 +1,23 @@
docker compose --profile tools run --rm imaging-test
Container mtusi-lab5-imaging-test-run-522cead2dfe0 Creating
Container mtusi-lab5-imaging-test-run-522cead2dfe0 Created
test_alpha_is_white_in_jpeg_and_kept_in_webp (test_imaging.ImagingTest.test_alpha_is_white_in_jpeg_and_kept_in_webp) ... ok
test_broken_jpeg_scan_is_invalid (test_imaging.ImagingTest.test_broken_jpeg_scan_is_invalid) ... ok
test_exif_orientation_is_applied (test_imaging.ImagingTest.test_exif_orientation_is_applied) ...
EXIF orientation 6: stored 400×200 -> variants 128×256 / 200×400, upright like a viewer shows it
ok
test_fixture_variants (test_imaging.ImagingTest.test_fixture_variants) ...
fixture 320×200 -> thumbnail JPEG 256×160, crop JPEG 128×128, optimized WebP 320×200
ok
test_geometry (test_imaging.ImagingTest.test_geometry) ... ok
test_limits_in_child_process (test_imaging.ImagingTest.test_limits_in_child_process) ...
36 Mpx RGBA in a child process: ok in 3.78 s with 640 MiB; MemoryError -> image_too_large with 200 MiB; timeout 0.2 s -> killed after 0.21 s; 1000 px limit -> image_too_large
ok
test_metadata_is_stripped (test_imaging.ImagingTest.test_metadata_is_stripped) ... ok
test_modes (test_imaging.ImagingTest.test_modes) ... ok
test_same_input_same_bytes (test_imaging.ImagingTest.test_same_input_same_bytes) ... ok
----------------------------------------------------------------------
Ran 9 tests in 5.420s
OK
+9
View File
@@ -0,0 +1,9 @@
python student-tests/lease_takeover.py
1. long job (35 s > lease 30 s) on d9eced386d93/507dfab2: lease_until moved forward 2 times: 18:26:08 -> 18:26:10 -> 18:26:20
2. worker B 3b645a26424d started (the job is still held by A's lease)
worker A d9eced386d93 frozen (docker pause): no more renewals
lease expired -> attempt 2 -> ready 31 s after the freeze; result committed by worker-3b645a26424d/a5b5d050
events: queued(1) -> claimed(1) -> lease_expired(1) -> retry_scheduled(1) -> claimed(2) -> ready(2)
3. worker A unpaused: Задание cd53da75-5133-44f3-a33f-038d4dbfd6ca: lease забрал другой worker — работа брошена
still exactly one result: status ready, attempt 2, 3 variant rows, metadata unchanged
PASS: a running worker keeps its lease by renewing it; a frozen one loses it, the job moves to another worker, and the stale worker cannot overwrite the result (fencing token)
+19
View File
@@ -0,0 +1,19 @@
python student-tests/outbox_crash.py
A. api_after_commit: the client got 502 instead of 202, but the attachment 44f59913-f920-4d36-82d5-fea3d61ce5b7 and its outbox row were committed before the crash
ready without creating a new job by hand; api restarted by Docker: ['ef44b0d4c0a1']
outbox: row 41 published 2026-10-25T18:23:23.278264+00:00 by relay-b0db3e40abfe
events: queued -> claimed -> ready
B. relay_before_publish: upload -> 202 (0d6338d9-fa65-459d-9d54-53cc385700d4); every relay that takes the row crashes before publishing
crashed and restarted: ['b0db3e40abfe', 'ef44b0d4c0a1']; after restart the row was published once -> ready
outbox: row 42 published 2026-10-25T18:23:32.331225+00:00 by relay-ef44b0d4c0a1
events: queued -> claimed -> ready
C. relay_after_publish: upload -> 202 (cf7c7e33-78ee-48c1-9bc5-7acefbf49d40); the broker confirms, the relay crashes before marking the row
crashed and restarted: ['b0db3e40abfe', 'ef44b0d4c0a1']; the same message was delivered again 1 time(s): duplicate_ignored
outbox: row 43 published 2026-10-25T18:23:40.297286+00:00 by relay-ef44b0d4c0a1
events: queued -> claimed -> ready -> duplicate_ignored
still one set of variants: 3 rows, 3 objects
D. broker stopped: upload -> 202 (094e50ca-898e-4c19-9d39-1b80721409ab), after 5 s status queued, outbox row 44 not published yet (it waits in PostgreSQL)
broker started: the relay published the row, ready 6.4 s later
outbox: row 44 published 2026-10-25T18:24:08.645165+00:00 by relay-ef44b0d4c0a1
events: queued -> claimed -> ready
PASS: a crash between COMMIT and publish (A, B) loses nothing — the outbox row is published later and the job becomes ready without manual action; a crash after publish (C) only causes a duplicate delivery, which the worker acknowledges without a second set of variants; while the broker is down (D) uploads are still accepted and the jobs wait in the outbox
+37
View File
@@ -0,0 +1,37 @@
python student-tests/run_persistence.py
hook: scripts/restart.cmd
=== containers before
SERVICE CONTAINER STATE STARTED AT (UTC)
api b0db3e40abfe running (healthy) 2026-10-25T18:30:40.428
api ef44b0d4c0a1 running (healthy) 2026-10-25T18:30:14.430
broker 9f909ed7ecea running (healthy) 2026-10-25T18:23:53.670
lb 8be67a2e86b7 running (healthy) 2026-10-25T18:20:04.043
migrate e6c2c825d38d exited 2026-10-25T18:28:07.167
postgres d2bfd48385f1 running (healthy) 2026-10-25T18:19:54.204
s3 892c7ca290f2 running (healthy) 2026-10-25T18:29:00.995
s3-init 08c2e7925d67 exited 2026-10-25T18:28:07.169
valkey 4e223cb9301e running (healthy) 2026-10-25T18:19:54.202
worker d9eced386d93 running (healthy) 2026-10-25T18:28:09.870
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.␍
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
=== containers after (test took 44.6 s: hook + waiting for readiness + data checks)
SERVICE CONTAINER STATE STARTED AT (UTC)
api b0db3e40abfe running (healthy) 2026-10-25T18:31:28.449
api ef44b0d4c0a1 running (healthy) 2026-10-25T18:31:28.805
broker 9f909ed7ecea running (healthy) 2026-10-25T18:30:56.986
lb 8be67a2e86b7 running (healthy) 2026-10-25T18:31:31.925
migrate e6c2c825d38d exited 2026-10-25T18:31:11.567
postgres d2bfd48385f1 running (healthy) 2026-10-25T18:30:55.983
s3 892c7ca290f2 running (healthy) 2026-10-25T18:31:10.564
s3-init 08c2e7925d67 exited 2026-10-25T18:31:26.062
valkey 4e223cb9301e running (healthy) 2026-10-25T18:30:56.073
worker d9eced386d93 running (healthy) 2026-10-25T18:31:28.448
api ef44b0d4c0a1: same container, start time 18:30:14 -> 18:31:28
api b0db3e40abfe: same container, start time 18:30:40 -> 18:31:28
broker 9f909ed7ecea: same container, start time 18:23:53 -> 18:30:56
lb 8be67a2e86b7: same container, start time 18:20:04 -> 18:31:31
postgres d2bfd48385f1: same container, start time 18:19:54 -> 18:30:55
s3 892c7ca290f2: same container, start time 18:29:00 -> 18:31:10
valkey 4e223cb9301e: same container, start time 18:19:54 -> 18:30:56
worker d9eced386d93: same container, start time 18:28:09 -> 18:31:28
PASS: api replicas, worker, postgres, valkey, s3, broker and lb were restarted (same containers and volumes, new start time); data, the attachment bytes and the existing token survived
+8
View File
@@ -0,0 +1,8 @@
python student-tests/redelivery.py
1. attachment a8404f7e-b179-4332-a562-4508d5a31ee5 ready: 3 variant rows, objects ['variants/a8404f7e-b179-4332-a562-4508d5a31ee5/v1/crop.jpg', 'variants/a8404f7e-b179-4332-a562-4508d5a31ee5/v1/optimized.webp', 'variants/a8404f7e-b179-4332-a562-4508d5a31ee5/v1/thumbnail.jpg']
2. the same message (same job_id and attempt) published twice more
3. both duplicates acknowledged without processing: duplicate_ignored(задание уже ready: повторная доставка, ack без обработки), duplicate_ignored(задание уже ready: повторная доставка, ack без обработки)
variants: [('crop', '97bf1400b30a'), ('optimized', '1090d84ed841'), ('thumbnail', '7bc40bf315c8')] — same rows, same objects, status ready, attempt 1
4. 3 messages that do not match jobs.schema.json -> reject -> DLQ attachments.dead: 8 -> 11
the worker keeps working: a new upload became ready
PASS: redelivery of a finished job is a no-op with ack (no second set of variants); malformed messages go to the DLQ without crashing the worker
+12
View File
@@ -0,0 +1,12 @@
python student-tests/retry_replay.py
A. transient errors twice, then success: ready at attempt 3
pauses before attempts: #2: 1.83 s, #3: 2.17 s (backoff 2^n with random jitter in [d/2, d])
events: queued(1) -> claimed(1) -> retry_scheduled(1) -> claimed(2) -> retry_scheduled(2) -> claimed(3) -> ready(3)
B. transient error every time: 5 attempts -> failed, error_code=retry_exhausted (last error storage_unavailable)
pauses: #2: 1.84 s, #3: 2.45 s, #4: 6.81 s, #5: 15.37 s
DLQ attachments.dead: 11 -> 12; registry: python -m messenger.jobs failed lists it; content -> 409, attach -> 409
C. permanent error: broken JPEG scan -> failed at attempt 1, error_code=invalid_image (no retries)
D. replay of the failed job: {'result': 'queued', 'attempt': 6, 'previous_error': 'retry_exhausted'} -> ready at attempt 6; audit: operator:student-test: replay оператора: было retry_exhausted (последняя ошибка storage_unavailable); новая попытка 6, ещё 5 попыток
replay of the now ready job: {'result': 'noop', 'reason': 'ready'} — no new message, variants unchanged (3 rows), status ready
replay of the permanent failure: {'result': 'queued', 'attempt': 2, 'previous_error': 'invalid_image'} -> failed again with invalid_image
PASS: bounded retries with backoff and jitter; permanent errors fail at once; final failures go to the DLQ and the failed registry; replay re-runs only failed jobs and is audited
+23
View File
@@ -0,0 +1,23 @@
python student-tests/s3_checks.py
object keys are server-generated: staging/<attachment uuid> -> originals/<attachment uuid>, variants/<attachment uuid>/v1/<variant> (filename is not used in keys)
anonymous_get_object: HTTP 403
anonymous_list_bucket: HTTP 403
anonymous_list_buckets: HTTP 403
API key GetObject: same SHA-256 as uploaded (the bytes are in the bucket)
API key list_buckets: ['messenger-attachments']
API key create_bucket: AccessDenied
API key make_bucket_public: AccessDenied
API key delete_bucket: AccessDenied
SeaweedFS admin/UI port 9333 inside the network: closed
SeaweedFS admin/UI port 8888 inside the network: closed
SeaweedFS admin/UI port 8080 inside the network: closed
host 127.0.0.1:9000, :9333, :8888: closed (S3 is not published)
attachments columns: id:uuid, chat_id:uuid, owner_id:uuid, filename:text, content_type:text, size_bytes:bigint, sha256:text, width:integer, height:integer, storage_key:text, status:text, created_at:timestamp with time zone, updated_at:timestamp with time zone, error_code:text, staging_key:text
api b0db3e40abfe: files with the same SHA-256 on disk: 0
api ef44b0d4c0a1: files with the same SHA-256 on disk: 0
worker d9eced386d93: files with the same SHA-256 on disk: 0
broker message (243 bytes): ['attachment_id', 'attempt', 'created_at', 'job_id', 'pipeline_version', 'schema_version', 'type'] — only IDs and service fields
s3-init run 1: exit 0: s3-init: bucket messenger-attachments already exists; anonymous access: 403 (private)
s3-init run 2: exit 0: s3-init: bucket messenger-attachments already exists; anonymous access: 403 (private)
objects in bucket before/after bootstrap: 164/164; the file still downloads
PASS: bucket is private outside the API, the API S3 user has least privilege, the console is closed, bytes are only in S3, bucket bootstrap is idempotent
+39
View File
@@ -0,0 +1,39 @@
python student-tests/check_stack.py
docker: 29.6.2
compose: 5.3.1
container_name: not set for any service (replicas of one service are possible)
api replicas running: 2 -> ['b0db3e40abfe', 'ef44b0d4c0a1'] (deploy.replicas = 2)
service container cpus memory published ports networks
valkey 4e223cb9301e 0.50 128Mi - backend
s3 892c7ca290f2 0.50 512Mi - backend
lb 8be67a2e86b7 0.50 128Mi 127.0.0.1:8080->8080/tcp, 127.0.0.1:8081->8081/tcp, 127.0.0.1:8404->8404/tcp edge
broker 9f909ed7ecea 1.00 512Mi - backend
api b0db3e40abfe 1.00 512Mi - backend, edge
postgres d2bfd48385f1 1.00 512Mi - backend
worker d9eced386d93 1.00 1024Mi - backend
api ef44b0d4c0a1 1.00 512Mi - backend, edge
published: only lb, only on 127.0.0.1 (api replicas have no ports)
balancer: every api server is under the /health/ready check, no backup servers -> api1 UP (L7OK), api2 UP (L7OK)
limits: every running container has CPU and RAM limits
networks: lb -> edge; api -> edge + backend; postgres, valkey, s3, broker, worker -> backend (internal: no way out)
broker: rabbitmq:4.2.9-alpine, volume rabbitmqdata, hostname broker, no ports, no web console; worker: separate service (1 running), no ports
s3: no published ports; master/filer web UIs only on 127.0.0.1 inside the container; IAM API off; pinned image; volume s3data
secrets: api -> broker_url, cache_url, database_url, s3_access_key_id, s3_secret_access_key; worker -> broker_url, database_url, s3_access_key_id, s3_secret_access_key; broker -> broker_credentials; migrate -> database_url; lb -> none; postgres -> postgres_password; valkey -> valkey_acl; s3 -> s3_config; s3-init -> s3_root_password, s3_root_user
images: lb haproxy:3.2.25-alpine; api mtusi-messenger:lab5; worker mtusi-messenger:lab5; postgres postgres:17.10-bookworm; valkey valkey/valkey:8.1.9; s3 chrislusf/seaweedfs:4.44; broker rabbitmq:4.2.9-alpine
PASS: one entry point (lb on 127.0.0.1), >= 2 api replicas without ports and container_name, only ready replicas get traffic, CPU/RAM limits everywhere, stores (incl. S3) only on the internal network, S3 admin credentials only in s3-init; broker and worker are separate services
docker compose ps -a --format "table {{.Service}}\t{{.ID}}\t{{.Status}}"
SERVICE CONTAINER ID STATUS
api b0db3e40abfe Up 34 seconds (healthy)
api ef44b0d4c0a1 Up 34 seconds (healthy)
broker 9f909ed7ecea Up 43 seconds (healthy)
lb 8be67a2e86b7 Up 33 seconds (healthy)
migrate e6c2c825d38d Exited (0) 35 seconds ago
postgres d2bfd48385f1 Up 43 seconds (healthy)
s3 892c7ca290f2 Up 43 seconds (healthy)
s3-init 08c2e7925d67 Exited (0) 35 seconds ago
valkey 4e223cb9301e Up 43 seconds (healthy)
worker d9eced386d93 Up 34 seconds (healthy)
s3-init-1 | s3-init: bucket messenger-attachments created; anonymous access: 403 (private)
migrate-1 | 2026-10-25 18:20:01,879 INFO messenger.db: Миграции применены: 001_core, 002_sessions, 003_text_as_bytes, 004_message_idempotency, 005_attachments, 006_jobs
+10
View File
@@ -0,0 +1,10 @@
python student-tests/staging_cleanup.py
1. ready 232becfa-7e6d-44da-bb4d-e72e9d0cc9fd: staging removed by the worker right after COMMIT; original and variants kept
2. prepared: staging leftover of a ready attachment, orphan staging, orphan variant, staging of a failed attachment, staging of a queued job (worker stopped)
3. dry-run: {"staging_after_ready": 2, "staging_failed_expired": 0, "orphan": 2} found, deleted 0
grace 900 s: deleted 0 — everything is younger than the grace period
grace 2 s: {"staging_after_ready": 2, "staging_failed_expired": 0, "orphan": 2}, deleted 4; kept: ready original and variants, staging of the queued job, staging of the failed attachment (retention)
retention 0 s: failed staging deleted ({"staging_after_ready": 0, "staging_failed_expired": 3, "orphan": 0}); replay now: {'result': 'refused', 'reason': 'source_missing', 'detail': 'оригинал в staging уже удалён (истёк STAGING_RETENTION_SECONDS)'}
repeated run: deleted 0
4. worker started: f8dce515-9269-42bf-a961-6ef73c87d763 ready, its staging removed
PASS: staging is removed after the result is committed; objects without a reference in the database are removed only after the grace period; the staging of failed uploads is kept for replay until retention ends; dry-run and repeated runs are safe
+90
View File
@@ -0,0 +1,90 @@
python -m unittest discover -s student-tests -p "test_*.py" -v
test_auth_checked_before_access_and_body (test_api.MessengerApiTest.test_auth_checked_before_access_and_body) ... ok
test_bad_cursor_returns_400 (test_api.MessengerApiTest.test_bad_cursor_returns_400) ... ok
test_chat_list_pagination (test_api.MessengerApiTest.test_chat_list_pagination) ... ok
test_chat_membership_rules (test_api.MessengerApiTest.test_chat_membership_rules) ... ok
test_duplicate_username_returns_409 (test_api.MessengerApiTest.test_duplicate_username_returns_409) ... ok
test_empty_blank_and_too_long_messages_return_400 (test_api.MessengerApiTest.test_empty_blank_and_too_long_messages_return_400) ... ok
test_malformed_json_returns_400 (test_api.MessengerApiTest.test_malformed_json_returns_400) ... ok
test_nul_character_is_stored (test_api.MessengerApiTest.test_nul_character_is_stored) ... ok
test_outsider_gets_404_for_foreign_chat (test_api.MessengerApiTest.test_outsider_gets_404_for_foreign_chat) ... ok
test_pagination_walks_several_pages (test_api.MessengerApiTest.test_pagination_walks_several_pages) ... ok
test_unicode_roundtrip (test_api.MessengerApiTest.test_unicode_roundtrip) ... ok
test_wrong_types_and_extra_fields_return_400 (test_api.MessengerApiTest.test_wrong_types_and_extra_fields_return_400) ... ok
test_attachment_rules_without_500 (test_attachments.AttachmentTest.test_attachment_rules_without_500) ... ok
test_broken_scan_becomes_failed_and_cannot_be_attached (test_attachments.AttachmentTest.test_broken_scan_becomes_failed_and_cannot_be_attached) ... ok
test_corrupted_images_are_415 (test_attachments.AttachmentTest.test_corrupted_images_are_415) ... ok
test_dangerous_filenames_are_400 (test_attachments.AttachmentTest.test_dangerous_filenames_are_400) ... ok
test_exact_limits (test_attachments.AttachmentTest.test_exact_limits) ... ok
test_idempotency_with_attachments (test_attachments.AttachmentTest.test_idempotency_with_attachments) ... ok
test_large_real_image_within_limits_is_accepted (test_attachments.AttachmentTest.test_large_real_image_within_limits_is_accepted) ... ok
test_message_with_attachments (test_attachments.AttachmentTest.test_message_with_attachments) ... ok
test_mime_spoofing_is_415 (test_attachments.AttachmentTest.test_mime_spoofing_is_415) ... ok
test_outsider_and_anonymous_cannot_upload (test_attachments.AttachmentTest.test_outsider_and_anonymous_cannot_upload) ... ok
test_pixel_bomb_is_413 (test_attachments.AttachmentTest.test_pixel_bomb_is_413) ... ok
test_png_and_jpeg_roundtrip_for_member (test_attachments.AttachmentTest.test_png_and_jpeg_roundtrip_for_member) ... ok
test_too_large_is_413_before_reading (test_attachments.AttachmentTest.test_too_large_is_413_before_reading) ... ok
test_too_large_stream_is_413 (test_attachments.AttachmentTest.test_too_large_stream_is_413) ... ok
test_variants_and_bad_ids (test_attachments.AttachmentTest.test_variants_and_bad_ids) ... ok
test_variants_follow_the_contract (test_attachments.AttachmentTest.test_variants_follow_the_contract) ... ok
test_bearer_required_on_business_endpoints (test_auth.AuthTest.test_bearer_required_on_business_endpoints) ... ok
test_login_returns_opaque_token_with_expiry (test_auth.AuthTest.test_login_returns_opaque_token_with_expiry) ... ok
test_logout_revokes_only_current_session (test_auth.AuthTest.test_logout_revokes_only_current_session) ... ok
test_malformed_basic_returns_401 (test_auth.AuthTest.test_malformed_basic_returns_401) ... ok
test_password_length_rules (test_auth.AuthTest.test_password_length_rules) ... ok
test_password_with_colon_and_unicode (test_auth.AuthTest.test_password_with_colon_and_unicode) ... ok
test_relogin_after_logout (test_auth.AuthTest.test_relogin_after_logout) ... ok
test_user_never_contains_password (test_auth.AuthTest.test_user_never_contains_password) ... ok
test_wrong_password_and_unknown_user_look_the_same (test_auth.AuthTest.test_wrong_password_and_unknown_user_look_the_same) ... ok
test_x_user_id_does_not_change_identity (test_auth.AuthTest.test_x_user_id_does_not_change_identity) ... ok
test_instance_id_on_errors_and_health (test_balancing.BalancingTest.test_instance_id_on_errors_and_health) ... ok
test_logout_applies_on_every_replica (test_balancing.BalancingTest.test_logout_applies_on_every_replica) ... ok
test_one_session_is_served_by_every_replica (test_balancing.BalancingTest.test_one_session_is_served_by_every_replica) ... ok
test_session_cache_is_shared_between_replicas (test_balancing.BalancingTest.test_session_cache_is_shared_between_replicas) ... ok
test_write_on_one_replica_read_on_another (test_balancing.BalancingTest.test_write_on_one_replica_read_on_another) ... ok
test_failed_request_does_not_burn_key (test_idempotency.IdempotencyTest.test_failed_request_does_not_burn_key) ... ok
test_json_formatting_does_not_matter (test_idempotency.IdempotencyTest.test_json_formatting_does_not_matter) ... ok
test_key_is_required_and_validated (test_idempotency.IdempotencyTest.test_key_is_required_and_validated) ... ok
test_key_scope_is_user_and_chat (test_idempotency.IdempotencyTest.test_key_scope_is_user_and_chat) ... ok
test_parallel_different_bodies_same_key (test_idempotency.IdempotencyTest.test_parallel_different_bodies_same_key) ... ok
test_parallel_same_key_through_replicas_creates_one_message (test_idempotency.IdempotencyTest.test_parallel_same_key_through_replicas_creates_one_message) ... ok
test_replay_rechecks_session_and_access (test_idempotency.IdempotencyTest.test_replay_rechecks_session_and_access) ... ok
test_replay_through_another_replica_returns_same_message (test_idempotency.IdempotencyTest.test_replay_through_another_replica_returns_same_message) ... ok
test_same_key_other_body_is_409 (test_idempotency.IdempotencyTest.test_same_key_other_body_is_409) ... ok
----------------------------------------------------------------------
Ran 52 tests in 24.217s
OK
10 485 760 байт и 6400×6250 = 40 000 000 px: 202 -> ready; на 1 байт/пиксель больше: 413
fixture 320×200 -> thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized 320×200 WebP; 48×32 -> {'thumbnail': (48, 32), 'crop': (128, 128), 'optimized': (48, 32)}
X-Instance-Id есть в health, 404, 401 и 400
logout через одну реплику -> 401 на ['b0db3e40abfe', 'ef44b0d4c0a1']
20 x GET /users/me с одним токеном -> реплики {'ef44b0d4c0a1': 10, 'b0db3e40abfe': 10}; это ID запущенных контейнеров api, повторный вход не нужен
10 x GET /users/me через реплики {'ef44b0d4c0a1': 5, 'b0db3e40abfe': 5}: попаданий в кэш +20, промахов +0 — кэш общий
сообщение записала реплика ef44b0d4c0a1, сразу прочитали ['b0db3e40abfe', 'ef44b0d4c0a1']
с тем же ключом: сначала 400 (пустой текст), потом 201 — ошибка ключ не заняла
тот же JSON с другими пробелами и переносами -> тот же 201 и то же сообщение
нет ключа, пустой, 129 символов, пробел, '/', кириллица -> 400; 128 символов и ._:- -> 201
тот же ключ у другого пользователя и в другом чате -> независимые сообщения
10 одновременных разных тел с одним ключом: 201 x1, 409 x9, в истории 1 сообщение
20 одновременных POST с одним ключом через реплики {'b0db3e40abfe': 10, 'ef44b0d4c0a1': 10}: все 201 с одним id, в истории 1 сообщение
повтор: посторонний -> 404, после logout -> 401, после нового входа -> то же сообщение
1 запрос + 4 повтора через реплики ['b0db3e40abfe', 'ef44b0d4c0a1']: 201 и то же сообщение, в истории 1
другой текст с тем же ключом -> 409 conflict, второе сообщение не создано
+2
View File
@@ -0,0 +1,2 @@
python tests/smoke.py --base-url "http://127.0.0.1:8080"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
+9
View File
@@ -0,0 +1,9 @@
python student-tests/worker_crash.py
A. worker_after_objects armed; upload -> 202 (7d0b4994-daec-489f-ab0c-fbad47e60ff5)
the worker crashed after writing objects (restart count 0 -> 1); objects left by the crashed attempt: 3
events: queued(1) -> claimed(1) -> lease_expired(1) -> retry_scheduled(1) -> claimed(2) -> ready(2)
ready at attempt 2; same keys and the same SHA-256 as the crashed attempt wrote: ['crop.jpg', 'optimized.webp', 'thumbnail.jpg']; 3 variant rows
B. worker_after_commit armed; upload -> 202 (d37dd53f-e784-47ba-9351-af5c9b091bd5)
events: queued(1) -> claimed(1) -> ready(1) -> duplicate_ignored(1)
the redelivered message found the job ready and was acknowledged without processing
PASS: a worker crash after writing objects but before ack is finished by a retry with the same result; a crash after COMMIT but before ack ends with a no-op redelivery
+13
View File
@@ -0,0 +1,13 @@
python student-tests/worker_outage.py
1. worker stopped: no running worker containers
2. upload -> 202 queued, attachment_id=58fc7ebe-6b35-4894-8af6-aad8f620136a
GET -> queued, /content -> 409, /content?variant=thumbnail -> 409
3. message with the queued attachment -> 201 (72038a80-6630-48ce-990a-4c37d5442ea4); text message -> 201 (d2a39236-0930-4973-ac60-f8089e57fc00)
4. after 5 s still queued: the API does not resize synchronously
5. job 8006a767-095b-412d-9493-fed8b6382c6d attempt 1: outbox row published at 2026-10-25T18:22:00.036515+00:00 by relay-ef44b0d4c0a1; queues: {'attachments.process': (1, 0), 'attachments.dead': (7, 0)}
6. api replicas restarted (same containers, volumes kept)
broker restarted with volume rabbitmqdata; queues after restart: {'attachments.process': (1, 0), 'attachments.dead': (7, 0)}
7. worker started -> ready after 3.2 s
thumbnail 256×160 JPEG, original SHA-256 unchanged, message 72038a80-6630-48ce-990a-4c37d5442ea4 keeps the attachment; outbox rows for the job: 1 (published once, before the broker restart)
job events: queued(1) -> claimed(1) -> ready(1)
PASS: with the worker down uploads are accepted (202) and wait; the accepted job survives API and broker restarts and becomes ready once the worker is started