This commit is contained in:
2026-11-06 18:45:08 +03:00
parent 545d083049
commit 482e7ff477
17 changed files with 958 additions and 42 deletions
+97
View File
@@ -0,0 +1,97 @@
"""Additional real-container checks: validation, permanent failure, timeout, retention."""
import os
from pipeline import Client, check, compose, remote, state, until
def main():
c = Client(os.getenv('BASE_URL', 'http://127.0.0.1:8080'))
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/attachments'
c.call('POST', path + '?filename=bad.png', 415, actor=alice, raw=b'not a PNG',
headers={'Content-Type': 'image/png'})
c.call('POST', path + '?filename=../bad.png', 400, actor=alice, raw=b'bad',
headers={'Content-Type': 'image/png'})
try:
compose('stop', 'worker', 'cleanup')
att, data = c.attachment(alice, chat)
aid = att['id']
before = state(aid)
# A queued record cannot be collected even when its staging is old.
remote(f'''
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from src.cleanup import cleanup
client = s3_client()
class SingleObject:
def __getattr__(self, name):
return getattr(client, name)
def get_paginator(self, name):
obj = dict(client.head_object(Bucket=BUCKET, Key={before['staging']!r}), Key={before['staging']!r})
return SimpleNamespace(paginate=lambda **kw: [{{'Contents': [obj]}}])
cleanup(sessions, SingleObject(), now=datetime.now(timezone.utc) + timedelta(days=2))
s3_client().head_object(Bucket=BUCKET, Key={before['staging']!r})
''')
# Force a real checksum failure after upload, without changing the public contract.
remote(f"s3_client().put_object(Bucket=BUCKET, Key={before['staging']!r}, Body=b'corrupted')\n")
key = 'queued-before-failure-' + aid
message = c.message(alice, chat, '', key=key, attachments=[aid])['json']
compose('start', 'worker')
until(lambda: state(aid)['status'] == 'failed')
check(state(aid)['attempt'] == 1 and state(aid)['error'] == 'invalid_image', 'permanent error retried')
c.call('GET', '/api/v1/attachments/' + aid + '/content', 409, actor=bob)
check(c.message(alice, chat, '', key=key, attachments=[aid])['json'] == message,
'failed processing broke message idempotency')
# Expire this test job's failed retention; cleanup must remove its staging.
remote(f'''
from datetime import timedelta
from src.jobs import now, replay
from src.cleanup import cleanup
with sessions.begin() as session:
a = session.get(Attachment, {aid!r})
a.updated_at = now() - timedelta(days=2)
cleanup(sessions, s3_client())
try:
replay(sessions, {before['job_id']!r}, 'expired staging must reject')
except ValueError:
pass
else:
raise AssertionError('Replay accepted missing staging')
''')
check(state(aid)['staging'] is None, 'failed staging retention did not expire')
print('PASS: upload validation, active staging retention, permanent failure, message replay, expired staging', flush=True)
compose('stop', 'worker')
att, _ = c.attachment(alice, chat)
aid = att['id']
until(lambda: state(aid)['published'])
# Substitute a real sleeping child for the decoder, keeping the real timeout/kill path.
remote(f'''
import subprocess, sys
import src.worker as worker
from unittest.mock import patch
real_run = subprocess.run
def stalled(*args, **kwargs):
return real_run([sys.executable, '-c', 'import time; time.sleep(30)'], timeout=1)
with sessions() as session:
j = session.scalar(select(AttachmentJob).where(AttachmentJob.attachment_id == {aid!r}))
fields = {{'job': json.dumps(envelope(j))}}
with patch.object(worker.subprocess, 'run', stalled):
worker.handle(sessions, broker(), '0-0', fields)
''')
check(state(aid)['status'] == 'queued' and state(aid)['failures'] == 1, 'timeout did not schedule retry')
remote(f'''
with sessions() as session:
j = session.scalar(select(AttachmentJob).where(AttachmentJob.attachment_id == {aid!r}))
assert j.last_error == 'processing_timeout'
''')
compose('start', 'worker')
c.wait_ready(bob, att)
check(state(aid)['attempt'] == 2, 'timeout recovery did not complete')
print('PASS: real subprocess timeout, termination and successful retry', flush=True)
finally:
compose('start', 'worker', 'cleanup')
if __name__ == '__main__':
main()
+197
View File
@@ -0,0 +1,197 @@
"""Integration/fault checks for the local lab5 Compose project; restores stopped services."""
import base64
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
def compose(*args, input=None):
result = subprocess.run(['docker', 'compose', *args], cwd=ROOT, input=input,
text=True, encoding='utf-8', capture_output=True)
if result.returncode:
raise AssertionError('Compose failed: ' + ' '.join(args[:3]) + '\n' + result.stderr)
return result.stdout
PRELUDE = '''
import json
from sqlalchemy import select
from sqlalchemy.orm import sessionmaker
from src.database import create_db_engine
from src.models import Attachment, AttachmentJob
from src.jobs import broker, envelope, GROUP, STREAM
from src.object_storage import BUCKET, s3_client
engine = create_db_engine()
sessions = sessionmaker(engine, expire_on_commit=False)
'''
def remote(code, fault=None):
options = ['exec', '-T']
if fault:
options += ['-e', 'JOB_FAULT=' + fault]
return compose(*options, 'api', 'python', '-', input=PRELUDE + code).strip()
def state(attachment_id):
return json.loads(remote(f'''
with sessions() as session:
a = session.get(Attachment, {attachment_id!r})
j = session.scalar(select(AttachmentJob).where(AttachmentJob.attachment_id == a.id))
print(json.dumps(dict(status=a.status, error=a.error_code, job_id=j.id,
attempt=j.attempt, failures=j.failures, published=bool(j.published_at),
staging=a.staging_key, variants=a.variants, audit=j.replay_audit)))
'''))
def until(fn, timeout=130):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = fn()
if result:
return result
time.sleep(1)
raise AssertionError('Timed out waiting for durable state')
def ready(client):
def probe():
try:
return client.call('GET', '/health/ready')['status'] == 200
except Exception:
return False
until(probe, 40)
def inject(attachment_id, fault):
# Use a real consumer-group delivery, leaving the message pending at the crash point.
return remote(f'''
from src.worker import handle
client = broker()
with sessions() as session:
j = session.scalar(select(AttachmentJob).where(AttachmentJob.attachment_id == {attachment_id!r}))
target = j.id
for _ in range(100):
batches = client.xreadgroup(GROUP, 'fault-test', {{STREAM: '>'}}, count=1, block=1000)
if batches:
mid, fields = batches[0][1][0]
handle(sessions, client, mid, fields)
if json.loads(fields['job'])['job_id'] == target:
print(mid)
break
else:
raise AssertionError('No delivery for target job')
''', fault=fault)
def main():
client = Client(os.getenv('BASE_URL', 'http://127.0.0.1:8080'))
alice, bob, eve, chat = client.bootstrap()
try:
compose('stop', 'worker', 'dispatcher', 'cleanup')
attachment, content = client.attachment(alice, chat)
aid = attachment['id']
check(attachment['status'] == 'queued', 'upload must return queued')
check(not state(aid)['published'], 'outbox was already published')
client.message(alice, chat, '', attachments=[aid])
client.call('GET', f'/api/v1/attachments/{aid}/content', 409, actor=bob)
compose('restart', 'api')
ready(client)
check(state(aid)['status'] == 'queued', 'API restart lost upload')
compose('start', 'dispatcher')
until(lambda: state(aid)['published'])
compose('restart', 'broker')
compose('start', 'worker')
result = client.wait_ready(bob, attachment)
check({v['name'] for v in result['variants']} == {'thumbnail', 'crop', 'optimized'}, 'missing variants')
for variant in result['variants']:
download = client.call('GET', f'/api/v1/attachments/{aid}/content?variant=' + variant['name'], actor=bob)
check(hashlib.sha256(download['bytes']).hexdigest() == variant['sha256'], 'variant checksum mismatch')
check(len(download['bytes']) == variant['size_bytes'], 'variant size mismatch')
check(download['headers'].get_content_type() == variant['content_type'], 'variant MIME mismatch')
check(client.call('GET', f'/api/v1/attachments/{aid}/content', actor=bob)['bytes'] == content, 'original changed')
print('PASS: outbox COMMIT/publish gap, stopped worker, API and broker restart', flush=True)
for fault in ('after_objects', 'after_commit'):
compose('stop', 'worker')
att, _ = client.attachment(alice, chat)
aid = att['id']
until(lambda: state(aid)['published'])
pending_id = inject(aid, fault)
snapshot = state(aid)
check(snapshot['status'] == ('processing' if fault == 'after_objects' else 'ready'), 'wrong crash state')
compose('start', 'worker')
until(lambda: state(aid)['status'] == 'ready')
until(lambda: remote(f"print(int(not broker().xpending_range(STREAM, GROUP, {pending_id!r}, {pending_id!r}, 1)))\n") == '1')
if fault == 'after_objects':
check(state(aid)['attempt'] == 2, 'expired lease was not retried')
else:
time.sleep(2)
check(state(aid)['attempt'] == 1, 'ready job was reprocessed')
# Force duplicate delivery; stable object keys and metadata must remain identical.
before = state(aid)
remote(f'''
with sessions() as session:
j = session.get(AttachmentJob, {before['job_id']!r})
broker().xadd(STREAM, {{'job': json.dumps(envelope(j))}})
''')
time.sleep(2)
after = state(aid)
check(before['variants'] == after['variants'] and before['attempt'] == after['attempt'], 'duplicate changed result')
count = remote(f"print(s3_client().list_objects_v2(Bucket=BUCKET, Prefix='variants/{aid}/')['KeyCount'])\n")
check(count == '3', 'redelivery produced extra S3 objects')
print('PASS: crash ' + fault + ', redelivery and stable variants', flush=True)
compose('stop', 'worker')
att, content = client.attachment(alice, chat)
aid = att['id']
until(lambda: state(aid)['published'])
# Remove only this test's staging object to cause a real temporary S3 error.
staging = state(aid)['staging']
remote(f"s3_client().delete_object(Bucket=BUCKET, Key={staging!r})\n")
compose('start', 'worker')
until(lambda: state(aid)['status'] == 'failed', 150)
failed = state(aid)
check(failed['error'] == 'retry_exhausted' and failed['attempt'] == 5, 'retry budget incorrect')
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': '', 'attachment_ids': [aid]}, headers={'Idempotency-Key': aid})
registry = compose('exec', '-T', 'api', 'python', '-m', 'src.jobs', 'failed')
check(failed['job_id'] in registry, 'failed job not visible')
remote(f'''
import base64
s3_client().put_object(Bucket=BUCKET, Key={staging!r},
Body=base64.b64decode({base64.b64encode(content).decode()!r}), ContentType='image/png')
''')
compose('exec', '-T', 'api', 'python', '-m', 'src.jobs', 'replay', failed['job_id'],
'--reason', 'synthetic test: restored staging')
client.wait_ready(bob, att)
check(len(state(aid)['audit']) == 1 and state(aid)['attempt'] == 6, 'replay lost audit or attempt')
remote(f'''
from src.jobs import replay
try:
replay(sessions, {failed['job_id']!r}, 'must reject ready')
except ValueError:
pass
else:
raise AssertionError('Replayed a ready job')
''')
print('PASS: bounded retries, failed registry, explicit audited replay, ready replay rejected', flush=True)
compose('exec', '-T', 'api', 'python', '-m', 'src.cleanup', '--once')
check(state(aid)['staging'] is None, 'completed staging was not cleaned')
check(client.call('GET', f'/api/v1/attachments/{aid}/content', actor=bob)['bytes'] == content, 'cleanup deleted original')
print('PASS: staging cleanup preserves ready objects', flush=True)
finally:
compose('start', 'broker', 'dispatcher', 'worker', 'cleanup')
if __name__ == '__main__':
main()
+61
View File
@@ -0,0 +1,61 @@
"""Run inside the application image: python -m unittest discover -s /checks."""
import hashlib
import io
import unittest
from unittest.mock import patch
from PIL import Image
from src.image_processor import variants
class ImageTests(unittest.TestCase):
def render(self, image, fmt='PNG', **kwargs):
source = io.BytesIO()
image.save(source, format=fmt, **kwargs)
results = list(variants(source.getvalue()))
self.assertEqual([meta['name'] for meta, _ in results], ['thumbnail', 'crop', 'optimized'])
decoded = {}
for meta, data in results:
self.assertEqual(meta['sha256'], hashlib.sha256(data).hexdigest())
self.assertEqual(meta['size_bytes'], len(data))
with Image.open(io.BytesIO(data)) as item:
item.load()
self.assertEqual(item.size, (meta['width'], meta['height']))
self.assertFalse(item.getexif())
self.assertNotIn('icc_profile', item.info)
decoded[meta['name']] = item.copy()
return decoded
def test_dimensions_and_floor_rounding(self):
images = self.render(Image.new('RGB', (321, 200), 'red'))
self.assertEqual(images['thumbnail'].size, (256, 159))
self.assertEqual(images['crop'].size, (128, 128))
self.assertEqual(images['optimized'].size, (321, 200))
def test_no_upscale_and_white_alpha(self):
images = self.render(Image.new('RGBA', (20, 10), (255, 0, 0, 0)))
self.assertEqual(images['thumbnail'].size, (20, 10))
self.assertEqual(images['optimized'].size, (20, 10))
self.assertEqual(images['thumbnail'].getpixel((5, 5)), (255, 255, 255))
def test_exif_orientation_and_metadata_removal(self):
exif = Image.Exif()
exif[274] = 6
exif[270] = 'private description'
images = self.render(Image.new('RGB', (320, 200), 'blue'), 'JPEG', exif=exif)
self.assertEqual(images['thumbnail'].size, (160, 256))
self.assertEqual(images['optimized'].size, (200, 320))
def test_optimized_bound(self):
images = self.render(Image.new('RGB', (2000, 1000), 'green'))
self.assertEqual(images['optimized'].size, (1280, 640))
def test_worker_pixel_limit(self):
with patch('src.image_processor.MAX_PIXELS', 100):
with self.assertRaises(ValueError):
self.render(Image.new('RGB', (11, 10)))
if __name__ == '__main__':
unittest.main()