This commit is contained in:
Матвей
2026-10-26 15:49:31 +03:00
parent 4f6e69cfac
commit a1bb6f8bde
18 changed files with 820 additions and 195 deletions
+7 -5
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Attachment contract checks against the running lab4 stack."""
"""Attachment contract checks against the running lab5 stack."""
import hashlib
import http.client
from io import BytesIO
@@ -23,16 +23,17 @@ def main():
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
def upload(data, mime='image/png', filename='photo.png', status=201, actor=alice):
def upload(data, mime='image/png', filename='photo.png', status=202, actor=alice):
return c.call('POST', path + quote(filename, safe=''), status, actor=actor, raw=data,
headers={'Content-Type': mime}, schema='Attachment' if status == 201 else None)
headers={'Content-Type': mime}, schema='Attachment' if status == 202 else None)
for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
buf = BytesIO()
Image.new('RGB', (32, 20), 'blue').save(buf, fmt)
data = buf.getvalue()
att = upload(data, mime)['json']
check(att['variants'] == [] and att['status'] == 'ready', 'wrong attachment state')
check(att['variants'] == [] and att['status'] == 'queued', 'wrong attachment state')
att = c.wait_ready(bob, att)
check(att['sha256'] == hashlib.sha256(data).hexdigest(), 'wrong checksum')
content_path = '/api/v1/attachments/' + att['id']
check(c.call('GET', content_path, actor=bob, schema='Attachment')['json'] == att,
@@ -41,7 +42,7 @@ def main():
c.call('GET', content_path, 404, actor=eve)
c.call('GET', content_path + '/content', 404, actor=eve)
c.call('GET', content_path + '/content', 401)
c.call('GET', content_path + '/content?variant=thumbnail', 404, actor=bob)
c.call('GET', content_path + '/content?variant=thumbnail', actor=bob)
message = c.message(bob, chat, '', attachments=[att['id']])['json']
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages',
actor=alice, schema='MessagePage')['json']['items']
@@ -98,6 +99,7 @@ def main():
# Exact limits are accepted; original bytes (including PNG trailing data) survive.
exact = png + b'\0' * (10485760 - len(png))
att = upload(exact)['json']
c.wait_ready(bob, att)
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == exact,
'10 MiB original changed')
buf = BytesIO()
+107
View File
@@ -0,0 +1,107 @@
"""Offline regression checks for delivery and terminal-state safety."""
import asyncio
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from io import BytesIO
import json
from pathlib import Path
import sys
from types import SimpleNamespace
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.storage.postgres import PostgresStore
from src.worker import process_locked as process, settle_delivery
from concurrent.futures import Future
from src.broker import _publish_to
class CriticalTests(unittest.IsolatedAsyncioTestCase):
def test_failed_or_unrecorded_work_is_requeued(self):
for result in (False, None, RuntimeError('database unavailable')):
future, channel = Future(), MagicMock()
if isinstance(result, Exception):
future.set_exception(result)
else:
future.set_result(result)
settle_delivery(channel, 7, future)
channel.basic_ack.assert_not_called()
channel.basic_nack.assert_called_once_with(7, requeue=True)
def test_durable_success_is_acked(self):
future, channel = Future(), MagicMock()
future.set_result(True)
settle_delivery(channel, 7, future)
channel.basic_ack.assert_called_once_with(7)
channel.basic_nack.assert_not_called()
async def test_outbox_decodes_jsonb(self):
store = PostgresStore('unused')
store._pool = AsyncMock()
payload = {'type': 'attachment.process.v1', 'attachment_id': str(uuid4())}
store.pool.fetch.return_value = [{'id': uuid4(), 'payload': json.dumps(payload)}]
event, = await store.due_outbox_events()
self.assertEqual(json.loads(json.dumps(event['payload'])), payload)
async def run_processing(self, committed):
store, s3 = AsyncMock(), AsyncMock()
stamp = datetime.now(timezone.utc)
store.claim_attachment_job.return_value = {
'claim_time': stamp, 'staging_key': 'staging/test',
'content_type': 'image/png', 'size_bytes': 1, 'sha256': 'unused',
}
store.complete_attachment_job.return_value = committed
s3.settings = SimpleNamespace(max_pixels=40000000)
s3.download_key.return_value = b'fixture'
s3.delete.side_effect = RuntimeError('storage temporarily unavailable')
payload = {'attachment_id': str(uuid4())}
with patch('src.worker.render_isolated', return_value=[('thumbnail', b'jpeg', 'image/jpeg', 1, 1)]):
await process(store, s3, payload, 60)
self.assertEqual(store.complete_attachment_job.call_args.args[-1], stamp)
return store, s3
async def test_cleanup_error_does_not_retry_ready(self):
store, s3 = await self.run_processing(True)
s3.delete.assert_awaited_once()
store.retry_attachment_job.assert_not_awaited()
async def test_stale_completion_keeps_staging(self):
_, s3 = await self.run_processing(False)
s3.delete.assert_not_awaited()
async def test_stale_claim_cannot_publish_metadata(self):
store = PostgresStore('unused')
connection = AsyncMock()
connection.fetchval.return_value = None
@asynccontextmanager
async def context():
yield connection
connection.transaction = context
store._pool = SimpleNamespace(acquire=context)
self.assertFalse(await store.complete_attachment_job(uuid4(), 'original', [], datetime.now(timezone.utc)))
connection.execute.assert_not_awaited()
async def test_retry_of_terminal_or_stale_attempt_is_noop(self):
store = PostgresStore('unused')
connection = AsyncMock()
connection.fetchrow.return_value = None
@asynccontextmanager
async def context():
yield connection
connection.transaction = context
store._pool = SimpleNamespace(acquire=context)
self.assertFalse(await store.retry_attachment_job(uuid4(), 5, 1, datetime.now(timezone.utc)))
connection.execute.assert_not_awaited()
def test_dlq_waits_for_publisher_confirm(self):
connection = MagicMock()
with patch('src.broker._connection', return_value=connection):
_publish_to('dlq', {'failure': 'invalid_job'})
connection.channel.return_value.confirm_delivery.assert_called_once()
self.assertTrue(connection.channel.return_value.basic_publish.call_args.kwargs['mandatory'])
if __name__ == '__main__':
unittest.main()
+127
View File
@@ -0,0 +1,127 @@
"""Contract, isolated-render and benchmark regressions without Docker."""
import asyncio
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
import importlib.util
from io import BytesIO
import json
from pathlib import Path
import sys
import tempfile
import threading
import time
from types import SimpleNamespace
import unittest
from unittest.mock import AsyncMock, patch
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from PIL import Image
from src.worker import variants, render_isolated, PermanentFailure
from src.storage.postgres import PostgresStore
from src.reconcile import scan
from src.errors import ApiError
def png(width, height):
buffer = BytesIO()
Image.new('RGBA', (width, height), (255, 0, 0, 0)).save(buffer, 'PNG')
return buffer.getvalue()
class Regressions(unittest.IsolatedAsyncioTestCase):
async def test_failed_attachment_is_rejected(self):
store, connection = PostgresStore('unused'), AsyncMock()
connection.fetchval.side_effect = [1, 1, 1]
@asynccontextmanager
async def context():
yield connection
connection.transaction = context
store._pool = SimpleNamespace(acquire=context)
with self.assertRaises(ApiError) as error:
await store.create_message_idempotent(uuid4(), uuid4(), '', 'key', 86400, [uuid4()])
self.assertEqual(error.exception.status_code, 409)
connection.fetchrow.assert_not_awaited()
def test_floor_and_small_images(self):
self.assertEqual(variants(png(300, 200))[0][3:], (256, 170))
self.assertEqual(variants(png(200, 300))[0][3:], (170, 256))
self.assertEqual(variants(png(10, 8))[0][3:], (10, 8))
for name, data, mime, width, height in variants(png(300, 200)):
with Image.open(BytesIO(data)) as image:
self.assertEqual(image.size, (width, height))
self.assertTrue(all(value > 240 for value in image.convert('RGB').getpixel((0, 0))))
def test_renderer_success_and_permanent_error(self):
self.assertEqual(render_isolated(png(300, 200), 10)[0][3:], (256, 170))
with self.assertRaises(PermanentFailure):
render_isolated(b'not an image', 10)
def test_renderer_is_killed_on_deadline(self):
started = time.monotonic()
with self.assertRaises(TimeoutError):
render_isolated(png(300, 200), .0001)
self.assertLess(time.monotonic() - started, 2)
async def test_cleanup_retains_active_and_failed_staging(self):
old = datetime.now(timezone.utc) - timedelta(days=2)
db, s3 = AsyncMock(), AsyncMock()
db.attachment_keys.return_value = {'staging/active': uuid4(), 'staging/failed': uuid4(), 'originals/ready': uuid4()}
s3.list_with_pages.side_effect = [({'staging/active': old, 'staging/failed': old, 'staging/orphan': old}, 1),
({'originals/ready': old}, 1), ({'variants/orphan': old}, 1)]
report = await scan(SimpleNamespace(grace_seconds=60, apply=True, object_key=[]), db, s3)
self.assertEqual(report['deleted'], ['staging/orphan', 'variants/orphan'])
async def test_permanent_failure_is_atomic_and_not_retried(self):
store = PostgresStore('unused')
connection = AsyncMock()
connection.fetchrow.return_value = {'attempt': 1}
@asynccontextmanager
async def context():
yield connection
connection.transaction = context
store._pool = SimpleNamespace(acquire=context)
result = await store.retry_attachment_job(uuid4(), 5, 1, datetime.now(timezone.utc), 'invalid_image')
self.assertFalse(result)
self.assertEqual(connection.execute.await_count, 2)
for call in connection.execute.call_args_list:
self.assertIn("status='failed'", call.args[0])
self.assertEqual(call.args[2], 'invalid_image')
def test_benchmark_partial_batch_and_recovery(self):
spec = importlib.util.spec_from_file_location('track1', ROOT / 'scripts/track1.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
jobs, lock = {}, threading.Lock()
class FakeClient:
def __init__(self, *args, **kwargs): pass
def bootstrap(self): return {}, {}, {}, {'id': str(uuid4())}
def call(self, method, path, *args, **kwargs):
if method == 'POST':
key = str(uuid4())
with lock: jobs[key] = {'id': key, 'status': 'ready', 'queue_wait_seconds': .01}
return {'status': 202, 'json': {'id': key}}
return {'json': {'status': 'ready'}}
def attachment(self, *args): return {}, b''
def wait_ready(self, *args, **kwargs): return {}
def metrics(_):
with lock:
return {'jobs': list(jobs.values()), 'pending': 0, 'rss_bytes': 1000, 'concurrency': 2, 'prefetch': 2}
with tempfile.TemporaryDirectory() as directory:
destination = str(Path(directory) / 'result.json')
args = SimpleNamespace(run_name='test', workers=2, prefetch=2, max_pending=20, images=10,
concurrency=8, size=8, max_ready_seconds=2, require_backpressure=False,
output=destination, base_url=None, ca_file=None)
info = {'Config': {'Env': ['MAX_PENDING_JOBS=20']}, 'HostConfig': {'Memory': 4096, 'NanoCpus': 2}}
with patch.object(module, 'arguments', return_value=args), patch.object(module, 'Client', FakeClient), \
patch.object(module, 'metrics', side_effect=metrics), patch.object(module, 'container_info', return_value=info), \
patch.object(module, 'broker_depth', return_value={'messages_ready': 0, 'messages_unacknowledged': 0}):
module.main()
report = json.loads(Path(destination).read_text())
self.assertEqual(report['results']['ready'], 10)
self.assertTrue(report['results']['recovery_upload_ready'])
if __name__ == '__main__':
unittest.main()