600 lines
35 KiB
Python
600 lines
35 KiB
Python
#!/usr/bin/env python3
|
|
"""Disposable Compose integration tests. Never operates on an existing project."""
|
|
import argparse
|
|
import concurrent.futures
|
|
import contextlib
|
|
import datetime as dt
|
|
import hashlib
|
|
import http.client
|
|
import io
|
|
import json
|
|
import os
|
|
import re
|
|
from pathlib import Path
|
|
import secrets
|
|
import shlex
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
from PIL import Image, __version__ as pillow_version
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from client import Client, Failure, check
|
|
|
|
|
|
def wait_for(predicate, label, timeout=60):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
value = predicate()
|
|
if value:
|
|
return value
|
|
time.sleep(0.2)
|
|
raise Failure('timeout: ' + label)
|
|
|
|
|
|
class Stack:
|
|
def __init__(self):
|
|
self.project = 'lab5test' + uuid.uuid4().hex[:12]
|
|
self.directory = ROOT / 'build' / 'student-tests' / self.project
|
|
self.directory.mkdir(parents=True, mode=0o700)
|
|
self.events = []
|
|
self.client = None
|
|
self.probe_name = None
|
|
self.store_ids = {}
|
|
self.base_files = ['-f', str(ROOT / 'compose.yaml'), '-f', str(self.directory / 'compose.json')]
|
|
values = {
|
|
'POSTGRES_USER': 'messenger', 'POSTGRES_DB': 'messenger',
|
|
'POSTGRES_PASSWORD': secrets.token_hex(24),
|
|
'MINIO_ROOT_USER': 'lab5-test-root', 'MINIO_ROOT_PASSWORD': secrets.token_hex(24),
|
|
'MINIO_USER_ACCESS_KEY': 'lab5-test-access', 'MINIO_USER_SECRET_KEY': secrets.token_hex(24),
|
|
'S3_BUCKET': 'lab5-tests', 'SESSION_STORE': 'postgres', 'API_REPLICAS': '1',
|
|
'DB_POOL_SIZE': '2', 'HTTP_WORKERS': '2', 'DRAIN_SECONDS': '0',
|
|
'API_CPU_LIMIT': '1.0', 'API_MEM_LIMIT': '512m', 'MINIO_CPU_LIMIT': '1.0',
|
|
}
|
|
self.command_env = os.environ.copy()
|
|
# An exported S3_ENDPOINT must never redirect a disposable test to another store.
|
|
for name in re.findall(r'\$\{([A-Za-z_]\w*)', (ROOT / 'compose.yaml').read_text()):
|
|
self.command_env.pop(name, None)
|
|
self.env_file = self.directory / 'test.env'
|
|
self.env_file.write_text(''.join(k + '=' + v + '\n' for k, v in values.items()))
|
|
self.env_file.chmod(0o600)
|
|
credentials = {
|
|
'database_url': 'postgresql://messenger:' + values['POSTGRES_PASSWORD'] + '@db:5432/messenger',
|
|
'cache_url': 'redis://cache:6379/0', 's3_access_key_id': values['MINIO_USER_ACCESS_KEY'],
|
|
's3_secret_access_key': values['MINIO_USER_SECRET_KEY'],
|
|
}
|
|
self.secret_files = []
|
|
for name, value in credentials.items():
|
|
path = self.directory / name
|
|
path.write_text(value + '\n')
|
|
path.chmod(0o644) # Bind-mounted files must be readable by container uid 10001.
|
|
self.secret_files.append(path)
|
|
override = {
|
|
'services': {
|
|
'api': {'ports': ['127.0.0.1::8080'], 'deploy': {'replicas': 1},
|
|
'healthcheck': {'interval': '1s', 'start_period': '1s', 'retries': 60}},
|
|
'worker': {'environment': {
|
|
'JOB_RECLAIM_IDLE_MS': '1000', 'JOB_RETRY_BASE_MS': '200',
|
|
'JOB_RETRY_MAX_MS': '800', 'JOB_TIMEOUT_SECONDS': '3',
|
|
'STAGING_RETENTION_SECONDS': '30', 'STAGING_CLEANUP_INTERVAL_SECONDS': '1',
|
|
}},
|
|
},
|
|
'secrets': {name: {'file': str(self.directory / name)} for name in credentials},
|
|
}
|
|
(self.directory / 'compose.json').write_text(json.dumps(override))
|
|
self.prefix = ['docker', 'compose', '--project-directory', str(ROOT), '-p', self.project,
|
|
'--env-file', str(self.env_file)]
|
|
|
|
def command(self, args, label, data=None, allow_failure=False, timeout=180):
|
|
result = subprocess.run(args, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
cwd=ROOT, timeout=timeout, env=self.command_env)
|
|
if result.returncode and not allow_failure:
|
|
with (self.directory / 'control.log').open('ab') as log:
|
|
log.write(result.stdout + result.stderr)
|
|
raise Failure(label + ' failed; diagnostic: ' + str(self.directory / 'control.log'))
|
|
return result
|
|
|
|
def dc(self, *args, fault=None, data=None, allow_failure=False, timeout=180):
|
|
files = self.base_files.copy()
|
|
if fault:
|
|
path = self.directory / ('fault-' + fault + '.json')
|
|
path.write_text(json.dumps({'services': {'api': {'environment': {
|
|
'LAB_ENABLE_FAULT_INJECTION': '1', 'LAB_FAULT_POINT': fault}}}}))
|
|
files += ['-f', str(path)]
|
|
result = self.command(self.prefix + files + list(args), 'Compose ' + args[0],
|
|
data=data, allow_failure=allow_failure, timeout=timeout)
|
|
return result.stdout.decode().strip()
|
|
|
|
def record(self, name, **fields):
|
|
self.events.append({'check': name, **fields})
|
|
print('PASS:', name, flush=True)
|
|
|
|
def start(self, build):
|
|
self.dc('config', '--quiet')
|
|
if build:
|
|
self.dc('build', 'api', 'minio', 'minio-init', timeout=1800)
|
|
self.dc('up', '-d', '--wait', '--wait-timeout', '120', 'api', 'worker', timeout=180)
|
|
self.refresh()
|
|
self.store_ids = {name: self.dc('ps', '-q', name) for name in ('db', 'cache')}
|
|
self.record('isolated stack started', project=self.project,
|
|
containers={name: self.inspect(name) for name in ('api', 'worker', 'db', 'cache', 'minio')})
|
|
|
|
def refresh(self):
|
|
address = self.dc('port', '--index', '1', 'api', '8080')
|
|
if self.client is None:
|
|
self.client = Client('http://' + address, timeout=10)
|
|
else:
|
|
self.client.base = 'http://' + address
|
|
def healthy():
|
|
try:
|
|
self.client.call('GET', '/health/ready', schema='Health')
|
|
return True
|
|
except (Failure, http.client.HTTPException):
|
|
return False
|
|
wait_for(healthy, 'API readiness')
|
|
|
|
def sql(self, query):
|
|
# These containers are restarted, never recreated, during a run.
|
|
args = ['docker', 'exec', '-i', self.store_ids['db'], 'psql', '-X', '-v',
|
|
'ON_ERROR_STOP=1', '-U', 'messenger', '-d', 'messenger', '-Atqc', query]
|
|
return self.command(args, 'test SQL').stdout.decode().strip()
|
|
|
|
def redis(self, *args):
|
|
command = ['docker', 'exec', '-i', self.store_ids['cache'], 'valkey-cli', '--json', *args]
|
|
return json.loads(self.command(command, 'test Redis').stdout)
|
|
|
|
def inspect(self, service):
|
|
ids = self.dc('ps', '-a', '-q', service).splitlines()
|
|
if not ids:
|
|
return []
|
|
raw = self.command(['docker', 'inspect', *ids], 'inspect containers').stdout
|
|
return [{'id': x['Id'], 'image': x['Image'], 'started_at': x['State']['StartedAt'],
|
|
'exit_code': x['State']['ExitCode'], 'restart_count': x['RestartCount'],
|
|
'memory_limit_bytes': x['HostConfig']['Memory'],
|
|
'volumes': sorted(m['Name'] for m in x['Mounts'] if m['Type'] == 'volume')}
|
|
for x in json.loads(raw)]
|
|
|
|
def wait_store(self, service):
|
|
def healthy():
|
|
cid = self.dc('ps', '-q', service)
|
|
result = self.command(['docker', 'inspect', '--format',
|
|
'{{.State.Health.Status}}', cid], 'store health')
|
|
return result.stdout.decode().strip() == 'healthy'
|
|
wait_for(healthy, service + ' health', timeout=90)
|
|
|
|
def recreate_api(self, fault=None):
|
|
self.dc('up', '-d', '--no-deps', '--force-recreate', 'api', fault=fault)
|
|
self.refresh()
|
|
|
|
def mc(self, command, data=None, allow_failure=False):
|
|
if self.probe_name is None:
|
|
self.probe_name = self.project + '-mc-probe'
|
|
script = ('mc alias set local "$S3_ENDPOINT" "$MINIO_ROOT_USER" '
|
|
'"$MINIO_ROOT_PASSWORD" >/dev/null; touch /tmp/probe-ready; exec sleep infinity')
|
|
self.dc('run', '--rm', '-d', '--no-deps', '--name', self.probe_name,
|
|
'--entrypoint', '/bin/sh', 'minio-user-init', '-ec', script)
|
|
wait_for(lambda: self.command(['docker', 'exec', self.probe_name, 'test', '-f',
|
|
'/tmp/probe-ready'], 'MinIO probe readiness',
|
|
allow_failure=True).returncode == 0,
|
|
'MinIO probe readiness', timeout=30)
|
|
return self.command(['docker', 'exec', '-i', self.probe_name, '/bin/sh', '-ec', command],
|
|
'MinIO test action', data=data, allow_failure=allow_failure)
|
|
|
|
def exists(self, key):
|
|
result = self.mc('mc stat "local/$S3_BUCKET/"' + shlex.quote(key), allow_failure=True)
|
|
return result.returncode == 0
|
|
|
|
def replay(self, job_id, success):
|
|
args = self.prefix + self.base_files + ['exec', '-T', 'api', '/docker-entrypoint.sh',
|
|
'/app/job_admin', 'replay', job_id, '--actor', 'integration-test',
|
|
'--reason', 'temporary failure fixed']
|
|
result = self.command(args, 'operator replay', allow_failure=True)
|
|
check((result.returncode == 0) == success, 'unexpected replay outcome')
|
|
|
|
def close(self):
|
|
try:
|
|
if self.probe_name:
|
|
self.command(['docker', 'rm', '-f', self.probe_name], 'remove own MinIO probe',
|
|
allow_failure=True)
|
|
self.dc('down', '--volumes', '--remove-orphans', timeout=120)
|
|
finally:
|
|
for path in [self.env_file, *self.secret_files]:
|
|
path.unlink(missing_ok=True)
|
|
|
|
|
|
class Suite:
|
|
def __init__(self, stack):
|
|
self.stack = stack
|
|
self.c = stack.client
|
|
self.alice, self.bob, self.eve, self.chat = self.c.bootstrap()
|
|
self.content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
|
|
|
def upload(self, expected=202):
|
|
result = self.c.call('POST', '/api/v1/chats/' + self.chat['id'] + '/attachments?filename=sample.png',
|
|
expected, actor=self.alice, raw=self.content,
|
|
headers={'Content-Type': 'image/png'}, schema='Attachment' if expected == 202 else None)
|
|
if expected != 202:
|
|
return result
|
|
att = result['json']
|
|
check(att['status'] == 'queued' and att['variants'] == [] and att['error_code'] is None,
|
|
'202 snapshot must be queued without variants')
|
|
check(att['sha256'] == hashlib.sha256(self.content).hexdigest() and
|
|
att['size_bytes'] == len(self.content), 'upload original metadata mismatch')
|
|
return att
|
|
|
|
def metadata(self, att):
|
|
return self.c.call('GET', '/api/v1/attachments/' + att['id'], actor=self.alice,
|
|
schema='Attachment')['json']
|
|
|
|
def job(self, att):
|
|
return self.stack.sql("SELECT id FROM jobs WHERE attachment_id='" + att['id'] + "'")
|
|
|
|
def key(self, att):
|
|
return 'staging/' + self.chat['id'] + '/' + att['id']
|
|
|
|
def ready(self, att):
|
|
ready = self.c.wait_ready(self.alice, att, wait_seconds=60)
|
|
check(ready['error_code'] is None, 'ready has error_code')
|
|
variants = {v['name']: v for v in ready['variants']}
|
|
check(len(ready['variants']) == 3 and set(variants) == {'thumbnail', 'crop', 'optimized'},
|
|
'ready must publish exactly three variants')
|
|
path = '/api/v1/attachments/' + att['id'] + '/content'
|
|
original = self.c.call('GET', path, actor=self.bob)
|
|
check(original['bytes'] == self.content and original['headers'].get_content_type() == 'image/png',
|
|
'original differs')
|
|
for name, size, mime, fmt in [('thumbnail', (256, 160), 'image/jpeg', 'JPEG'),
|
|
('crop', (128, 128), 'image/jpeg', 'JPEG'),
|
|
('optimized', (320, 200), 'image/webp', 'WEBP')]:
|
|
result = self.c.call('GET', path + '?variant=' + name, actor=self.bob)
|
|
v = variants[name]
|
|
with Image.open(io.BytesIO(result['bytes'])) as image:
|
|
image.load()
|
|
check(image.format == fmt and image.size == size and not image.getexif(),
|
|
'actual variant image mismatch: ' + name)
|
|
check(result['headers'].get_content_type() == mime and
|
|
len(result['bytes']) == v['size_bytes'] and
|
|
hashlib.sha256(result['bytes']).hexdigest() == v['sha256'] and
|
|
(v['width'], v['height']) == size, 'variant metadata mismatch: ' + name)
|
|
for suffix in ('', '/content?variant=optimized'):
|
|
self.c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=self.eve)
|
|
return ready
|
|
|
|
def events(self, att):
|
|
events = []
|
|
for _, fields in self.stack.redis('XRANGE', 'jobs:attachments', '-', '+'):
|
|
values = dict(zip(fields[::2], fields[1::2]))
|
|
with contextlib.suppress(ValueError, KeyError, AttributeError):
|
|
payload = json.loads(values['payload'])
|
|
if payload.get('attachment_id') == att['id']:
|
|
events.append(payload)
|
|
return events
|
|
|
|
def pending_empty(self):
|
|
return self.stack.redis('XPENDING', 'jobs:attachments', 'attachment-workers')[0] == 0
|
|
|
|
def upload_async(self):
|
|
s = self.stack
|
|
s.dc('stop', 'worker')
|
|
att = self.upload()
|
|
check(self.metadata(att)['status'] == 'queued', 'GET must be queued with stopped worker')
|
|
self.c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 409, actor=self.alice)
|
|
s.dc('start', 'worker')
|
|
self.ready(att)
|
|
s.record('upload 202 -> GET queued -> ready, original and 3 variants verified', attachment_id=att['id'])
|
|
|
|
def worker_down(self):
|
|
s = self.stack
|
|
s.dc('stop', 'worker')
|
|
att = self.upload()
|
|
check(self.metadata(att)['status'] == 'queued', 'worker-down upload was processed')
|
|
self.c.message(self.alice, self.chat, '', attachments=[att['id']])
|
|
before = {name: s.inspect(name) for name in ('api', 'db', 'cache', 'minio')}
|
|
s.dc('restart', 'db', 'cache', 'minio')
|
|
for name in ('db', 'cache', 'minio'):
|
|
s.wait_store(name)
|
|
s.dc('restart', 'api')
|
|
s.refresh()
|
|
check(self.metadata(att)['status'] == 'queued', 'accepted job lost after store/API restart')
|
|
after = {name: s.inspect(name) for name in before}
|
|
for name in before:
|
|
check(before[name][0]['started_at'] != after[name][0]['started_at'], name + ' did not restart')
|
|
check(before[name][0]['volumes'] == after[name][0]['volumes'], name + ' changed volumes')
|
|
s.dc('start', 'worker')
|
|
self.ready(att)
|
|
s.record('worker down: accepted job/session survive API, PostgreSQL, Valkey and S3 restart',
|
|
attachment_id=att['id'], before=before, after=after)
|
|
|
|
def outbox_crash(self):
|
|
s = self.stack
|
|
s.dc('stop', 'worker', 'cache')
|
|
att = self.upload()
|
|
check(self.metadata(att)['status'] == 'queued', 'broker-down upload not queued')
|
|
s.dc('restart', 'api'); s.refresh()
|
|
check(self.metadata(att)['status'] == 'queued', 'outbox lost on offline restart')
|
|
s.dc('start', 'cache', 'worker'); self.ready(att)
|
|
s.record('broker down: upload 202 and offline API restart preserve outbox')
|
|
s.dc('stop', 'worker', 'cache')
|
|
s.recreate_api('upload_after_commit')
|
|
before = int(s.sql('SELECT count(*) FROM attachments'))
|
|
try:
|
|
self.upload()
|
|
except (Failure, http.client.HTTPException):
|
|
pass
|
|
else:
|
|
raise Failure('upload fault did not terminate API')
|
|
wait_for(lambda: s.inspect('api')[0]['exit_code'] == 86, 'upload crash exit 86')
|
|
check(int(s.sql('SELECT count(*) FROM attachments')) == before + 1, 'crash transaction absent')
|
|
att = {'id': s.sql('SELECT id FROM attachments ORDER BY created_at DESC LIMIT 1')}
|
|
check(s.sql("SELECT count(*) FROM outbox WHERE NOT published AND payload->>'attachment_id'='" +
|
|
att['id'] + "'") == '1', 'committed outbox intent absent')
|
|
s.recreate_api()
|
|
check(self.metadata(att)['status'] == 'queued', 'crash attachment missing')
|
|
s.dc('start', 'cache', 'worker'); self.ready(att)
|
|
s.record('crash after COMMIT before XADD: same attachment/job recovers without new POST',
|
|
attachment_id=att['id'], exit_code=86)
|
|
s.dc('stop', 'worker', 'cache')
|
|
att = self.upload()
|
|
s.recreate_api('outbox_after_publish'); s.dc('start', 'cache')
|
|
wait_for(lambda: s.inspect('api')[0]['exit_code'] == 86, 'publisher crash exit 86')
|
|
check(len(self.events(att)) == 1, 'XADD did not precede injected crash')
|
|
check(s.sql("SELECT count(*) FROM outbox WHERE NOT published AND payload->>'attachment_id'='" +
|
|
att['id'] + "'") == '1', 'publisher committed marker before crash')
|
|
s.recreate_api()
|
|
wait_for(lambda: len(self.events(att)) == 2, 'outbox redelivery')
|
|
s.dc('start', 'worker'); self.ready(att)
|
|
check(s.sql("SELECT retries FROM jobs WHERE id='" + self.job(att) + "'") == '0',
|
|
'publisher duplicate caused an extra processing attempt')
|
|
s.record('crash after XADD before published marker: duplicate delivery, one ready effect',
|
|
attachment_id=att['id'], stream_deliveries=2, exit_code=86)
|
|
|
|
def retry_replay(self):
|
|
s = self.stack
|
|
counts = s.sql('SELECT (SELECT count(*) FROM attachments), (SELECT count(*) FROM jobs), (SELECT count(*) FROM outbox)')
|
|
s.sql("CREATE FUNCTION test_reject_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test failure'; END $$; CREATE TRIGGER test_reject_outbox BEFORE INSERT ON outbox FOR EACH ROW EXECUTE FUNCTION test_reject_outbox()")
|
|
self.upload(expected=500)
|
|
check(s.sql('SELECT (SELECT count(*) FROM attachments), (SELECT count(*) FROM jobs), (SELECT count(*) FROM outbox)') == counts,
|
|
'outbox failure did not roll back all metadata')
|
|
s.sql('DROP TRIGGER test_reject_outbox ON outbox; DROP FUNCTION test_reject_outbox()')
|
|
s.record('attachment/job/outbox transaction rolls back on outbox INSERT failure')
|
|
s.sql("CREATE TABLE test_attempts(job_id uuid, attempt int, observed_at timestamptz, due_at timestamptz); CREATE FUNCTION test_audit_attempt() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.status='processing' AND OLD.status<>'processing' THEN INSERT INTO test_attempts VALUES(NEW.id,NEW.retries+1,now(),NEW.next_attempt_at); END IF; RETURN NEW; END $$; CREATE TRIGGER test_audit_attempt AFTER UPDATE ON jobs FOR EACH ROW EXECUTE FUNCTION test_audit_attempt()")
|
|
s.sql("CREATE FUNCTION test_reject_ready() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.status='ready' THEN RAISE EXCEPTION 'test failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER test_reject_ready BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION test_reject_ready()")
|
|
att = self.upload()
|
|
wait_for(lambda: self.metadata(att)['status'] == 'failed', 'retry exhaustion')
|
|
s.dc('stop', 'worker')
|
|
s.sql('DROP TRIGGER test_reject_ready ON attachments; DROP FUNCTION test_reject_ready()')
|
|
job = self.job(att)
|
|
check(s.sql("SELECT retries FROM jobs WHERE id='" + job + "'") == '6', 'retry limit not enforced')
|
|
check(self.metadata(att)['error_code'] == 'processing_failed', 'failed error_code absent')
|
|
check([p['attempt'] for p in self.events(att)] == list(range(1, 7)), 'managed attempts differ')
|
|
check(s.sql("SELECT count(*) FROM test_attempts WHERE job_id='" + job + "' AND observed_at<due_at") == '0',
|
|
'worker started before durable due time')
|
|
delays = []
|
|
rows = s.sql("SELECT payload->>'attempt', EXTRACT(EPOCH FROM (available_at-created_at))*1000 "
|
|
"FROM outbox WHERE payload->>'job_id'='" + job + "' ORDER BY id")
|
|
for row in rows.splitlines()[1:]:
|
|
attempt, delay = row.split('|'); attempt, delay = int(attempt), float(delay)
|
|
ceiling = min(800, 200 * 2 ** (attempt - 2))
|
|
check(ceiling / 2 <= delay <= ceiling, 'backoff/jitter outside configured range')
|
|
delays.append({'attempt': attempt, 'delay_ms': delay})
|
|
self.c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 409, actor=self.alice)
|
|
s.record('backoff+jitter persisted, attempts 1..6, no early processing, finite failed', delays=delays)
|
|
# Corrupt bytes of the same size: replay must check SHA, not only HEAD/length.
|
|
key = shlex.quote(self.key(att))
|
|
s.mc('mc pipe "local/$S3_BUCKET/"' + key, data=bytes(len(self.content)))
|
|
s.replay(job, False)
|
|
check(s.sql("SELECT count(*) FROM job_replays WHERE job_id='" + job + "'") == '0',
|
|
'rejected replay changed audit')
|
|
s.mc('mc pipe "local/$S3_BUCKET/"' + key, data=self.content)
|
|
s.replay(job, True)
|
|
s.replay(job, False)
|
|
s.redis('XADD', 'jobs:attachments', '*', 'payload', json.dumps(self.events(att)[0]))
|
|
s.dc('start', 'worker'); self.ready(att)
|
|
s.replay(job, False)
|
|
check(s.sql("SELECT retry_base,retries FROM jobs WHERE id='" + job + "'") == '6|6',
|
|
'replay reset monotonic retry count')
|
|
check(max(p['attempt'] for p in self.events(att)) == 7, 'replay did not enqueue next managed attempt')
|
|
check(s.sql("SELECT actor,retries_before FROM job_replays WHERE job_id='" + job + "'") == 'integration-test|6',
|
|
'replay audit mismatch')
|
|
s.record('audited replay verifies SHA, keeps job_id, fences stale events, refuses queued/ready', job_id=job)
|
|
|
|
def worker_crashes(self):
|
|
s = self.stack
|
|
s.sql("CREATE FUNCTION test_pause_ready() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.status='ready' THEN PERFORM pg_sleep(10); END IF; RETURN NEW; END $$; CREATE TRIGGER test_pause_ready BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION test_pause_ready()")
|
|
att = self.upload()
|
|
wait_for(lambda: s.sql("SELECT count(*) FROM pg_stat_activity WHERE wait_event='PgSleep' AND query LIKE 'UPDATE attachments a SET status=%'") == '1',
|
|
'worker after S3 before result COMMIT')
|
|
s.dc('kill', '-s', 'SIGKILL', 'worker')
|
|
s.sql('DROP TRIGGER test_pause_ready ON attachments; DROP FUNCTION test_pause_ready()')
|
|
check(s.exists('attachments/' + self.chat['id'] + '/' + att['id'] + '/v1/optimized.webp'),
|
|
'worker had not saved the final variant before crash')
|
|
s.dc('start', 'worker'); self.ready(att)
|
|
check(int(s.sql("SELECT retries FROM jobs WHERE id='" + self.job(att) + "'")) >= 1,
|
|
'crashed processing not counted')
|
|
s.record('SIGKILL after S3 before COMMIT/ACK: pending recovers the same effect', attachment_id=att['id'])
|
|
before = s.inspect('worker')[0]['restart_count']
|
|
s.sql("CREATE FUNCTION test_pause_ready() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.status='ready' THEN PERFORM pg_sleep(10); END IF; RETURN NEW; END $$; CREATE TRIGGER test_pause_ready BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION test_pause_ready()")
|
|
att = self.upload()
|
|
wait_for(lambda: s.inspect('worker')[0]['restart_count'] > before, 'watchdog restart')
|
|
s.sql('DROP TRIGGER test_pause_ready ON attachments; DROP FUNCTION test_pause_ready()')
|
|
self.ready(att)
|
|
check('timed out' in s.dc('logs', '--no-color', 'worker'), 'watchdog timeout not observed')
|
|
s.record('watchdog bounds hung processing and Compose restarts worker',
|
|
restart_count_before=before, restart_count_after=s.inspect('worker')[0]['restart_count'])
|
|
|
|
def duplicates_publishers(self):
|
|
s = self.stack
|
|
s.dc('up', '-d', '--no-deps', '--scale', 'worker=2', 'worker')
|
|
s.sql("CREATE FUNCTION test_pause_ready() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.status='ready' THEN PERFORM pg_sleep(1); END IF; RETURN NEW; END $$; CREATE TRIGGER test_pause_ready BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION test_pause_ready()")
|
|
att = self.upload()
|
|
wait_for(lambda: self.events(att), 'initial stream event')
|
|
for _ in range(4):
|
|
s.redis('XADD', 'jobs:attachments', '*', 'payload', json.dumps(self.events(att)[0]))
|
|
ready = self.ready(att)
|
|
s.sql('DROP TRIGGER test_pause_ready ON attachments; DROP FUNCTION test_pause_ready()')
|
|
wait_for(self.pending_empty, 'duplicate ACKs')
|
|
check(self.metadata(att) == ready, 'duplicate changed ready metadata')
|
|
check(s.sql("SELECT retries FROM jobs WHERE id='" + self.job(att) + "'") == '0', 'duplicate became a retry')
|
|
s.record('two workers serialize duplicate processing; variants and ready metadata stay unique',
|
|
workers=s.inspect('worker'), stream_deliveries=len(self.events(att)))
|
|
s.dc('up', '-d', '--no-deps', '--scale', 'worker=1', 'worker')
|
|
s.dc('stop', 'worker', 'cache')
|
|
items = [self.upload() for _ in range(8)]
|
|
s.dc('up', '-d', '--no-deps', '--scale', 'api=2', 'api'); s.refresh()
|
|
s.dc('start', 'cache')
|
|
wait_for(lambda: s.sql('SELECT count(*) FROM outbox WHERE NOT published') == '0', 'concurrent publishers')
|
|
check(all(len(self.events(att)) == 1 for att in items), 'healthy publishers duplicated outbox rows')
|
|
s.dc('start', 'worker')
|
|
for att in items:
|
|
self.ready(att)
|
|
s.record('two API publishers drain outbox with SKIP LOCKED', apis=s.inspect('api'), jobs=len(items))
|
|
s.dc('up', '-d', '--no-deps', '--scale', 'api=1', 'api'); s.refresh()
|
|
|
|
def cleanup_races(self):
|
|
s = self.stack
|
|
# Short retention only inside this disposable project.
|
|
path = s.directory / 'cleanup.json'
|
|
path.write_text(json.dumps({'services': {'worker': {'environment': {'STAGING_RETENTION_SECONDS': '1'}}}}))
|
|
s.command(s.prefix + s.base_files + ['-f', str(path), 'up', '-d', '--no-deps', '--force-recreate', 'worker'],
|
|
'enable test retention')
|
|
s.dc('stop', 'cache')
|
|
att = self.upload()
|
|
direct = self.c.call('POST', '/api/v1/chats/' + self.chat['id'] + '/direct-uploads', 201,
|
|
actor=self.alice, body={'filename': 'sample.png', 'content_type': 'image/png',
|
|
'size_bytes': len(self.content), 'sha256': hashlib.sha256(self.content).hexdigest()})
|
|
direct = json.loads(direct['bytes'])
|
|
s.command(s.prefix + s.base_files + ['exec', '-T', 'api', 'curl', '-fsS', '-X', 'PUT',
|
|
'-H', 'Content-Type: image/png', '--data-binary', '@-', direct['upload_url']],
|
|
'presigned upload', data=self.content)
|
|
direct_key = 'staging/' + self.chat['id'] + '/' + direct['id']
|
|
orphan = 'staging/' + self.chat['id'] + '/' + str(uuid.uuid4())
|
|
s.mc('mc pipe "local/$S3_BUCKET/"' + shlex.quote(orphan), data=self.content)
|
|
wait_for(lambda: not s.exists(orphan), 'orphan retention', timeout=30)
|
|
check(s.exists(self.key(att)) and s.exists(direct_key), 'GC deleted an active upload')
|
|
s.dc('start', 'cache'); ready = self.ready(att)
|
|
wait_for(lambda: s.sql("SELECT staging_cleaned_at IS NOT NULL FROM attachments WHERE id='" + att['id'] + "'") == 't',
|
|
'ready staging cleanup')
|
|
check(not s.exists(self.key(att)) and self.metadata(att) == ready, 'ready cleanup changed content/metadata')
|
|
complete_path = '/api/v1/direct-uploads/' + direct['id'] + '/complete'
|
|
direct_att = self.c.call('POST', complete_path, 202, actor=self.alice, schema='Attachment')['json']
|
|
self.ready(direct_att)
|
|
check(s.exists(direct_key), 'GC deleted a key while its presigned URL is valid')
|
|
self.c.call('POST', complete_path, 200, actor=self.alice, schema='Attachment')
|
|
check(s.sql("SELECT count(*) FROM outbox WHERE payload->>'attachment_id'='" + direct['id'] + "'") == '1',
|
|
'presigned completion replay duplicated outbox')
|
|
s.record('retention deletes orphan/ready staging, protects queued and live presigned source')
|
|
# Hold an API upload in INSERT after its PUT. GC must respect its advisory lock.
|
|
listing = 'mc ls --json "local/$S3_BUCKET/staging/"' + shlex.quote(self.chat['id'] + '/')
|
|
old_keys = {json.loads(line)['key'] for line in s.mc(listing).stdout.splitlines()}
|
|
s.sql("CREATE FUNCTION test_pause_upload() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(4); RETURN NEW; END $$; CREATE TRIGGER test_pause_upload BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION test_pause_upload()")
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
|
|
future = executor.submit(self.upload)
|
|
wait_for(lambda: s.sql("SELECT count(*) FROM pg_stat_activity WHERE wait_event='PgSleep' AND query LIKE 'INSERT INTO attachments%'") == '1',
|
|
'API paused after PUT')
|
|
current = {json.loads(line)['key'] for line in s.mc(listing).stdout.splitlines()}
|
|
new_key = next(iter(current - old_keys))
|
|
time.sleep(2.2)
|
|
phase_query = "SELECT count(*) FROM pg_stat_activity WHERE wait_event='PgSleep' AND query LIKE 'INSERT INTO attachments%'"
|
|
check(s.sql(phase_query) == '1', 'GC race probe missed the pre-COMMIT window')
|
|
present = s.exists('staging/' + self.chat['id'] + '/' + new_key)
|
|
check(s.sql(phase_query) == '1', 'GC race probe crossed the COMMIT boundary')
|
|
check(present, 'GC deleted uncommitted upload')
|
|
raced = future.result()
|
|
s.sql('DROP TRIGGER test_pause_upload ON attachments; DROP FUNCTION test_pause_upload()')
|
|
self.ready(raced)
|
|
s.record('GC/upload race: PUT-before-COMMIT source is protected')
|
|
s.dc('stop', 'cache'); expired = self.upload()
|
|
s.sql("UPDATE jobs SET status='failed', retries=1, error_code='processing_failed' WHERE attachment_id='" + expired['id'] + "'; "
|
|
"UPDATE attachments SET status='failed', error_code='processing_failed', updated_at=now()-interval '1 day' WHERE id='" + expired['id'] + "'")
|
|
wait_for(lambda: s.sql("SELECT staging_cleaned_at IS NOT NULL FROM attachments WHERE id='" + expired['id'] + "'") == 't',
|
|
'failed retention')
|
|
check(not s.exists(self.key(expired)), 'expired failed source retained')
|
|
s.replay(self.job(expired), False)
|
|
s.dc('start', 'cache')
|
|
s.record('expired failed staging is collected; replay refuses cleaned source')
|
|
|
|
def memory(self):
|
|
s = self.stack
|
|
image = s.directory / '40m.png'
|
|
with Image.new('RGB', (8000, 5000), (30, 140, 200)) as fixture:
|
|
fixture.save(image)
|
|
image_id = s.inspect('api')[0]['image']
|
|
args = ['docker', 'run', '--rm', '--network', 'none', '--memory', '512m', '--memory-swap', '512m',
|
|
'--user', str(os.getuid()) + ':' + str(os.getgid()),
|
|
'-v', str(s.directory) + ':/work', '--entrypoint', '/app/variants_smoke', image_id,
|
|
'/work/40m.png', '/work/40m-output']
|
|
s.command(args, '40M pixel memory boundary', timeout=120)
|
|
for name, size in [('thumbnail.jpg', (256, 160)), ('crop.jpg', (128, 128)), ('optimized.webp', (1280, 800))]:
|
|
with Image.open(s.directory / '40m-output' / name) as result:
|
|
result.load()
|
|
check(result.size == size, 'large fixture output mismatch')
|
|
s.record('40M pixel RGB PNG produces three variants with 512 MiB and no swap', pixels=40000000,
|
|
memory_limit_bytes=512 * 1024 * 1024, swap_bytes=0)
|
|
|
|
def reliability(self):
|
|
self.retry_replay()
|
|
self.worker_crashes()
|
|
self.duplicates_publishers()
|
|
self.cleanup_races()
|
|
self.memory()
|
|
|
|
def public_smoke(self):
|
|
self.stack.command([sys.executable, str(ROOT / 'tests/smoke.py'), '--base-url', self.c.base],
|
|
'public smoke', timeout=180)
|
|
self.stack.record('unchanged lab5 public smoke passed')
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('scenario', choices=['upload', 'worker_down', 'outbox', 'reliability', 'all'])
|
|
parser.add_argument('--no-build', action='store_true', help='reuse images built from this repository')
|
|
parser.add_argument('--output', type=Path, help='sanitized JSON evidence (no credentials/tokens)')
|
|
args = parser.parse_args()
|
|
stack = Stack()
|
|
started = time.monotonic()
|
|
digest = hashlib.sha256()
|
|
source_files = [ROOT / name for name in ('CMakeLists.txt', 'Dockerfile', 'compose.yaml', '.dockerignore')]
|
|
for folder in ('src', 'migrations', 'third_party'):
|
|
source_files += [p for p in (ROOT / folder).rglob('*') if p.is_file()]
|
|
for path in sorted(source_files):
|
|
digest.update(str(path.relative_to(ROOT)).encode() + b'\0' + path.read_bytes())
|
|
result = {'scenario': args.scenario, 'project': stack.project,
|
|
'source_sha256': digest.hexdigest(), 'python': sys.version.split()[0], 'pillow': pillow_version,
|
|
'started_at': dt.datetime.now(dt.timezone.utc).isoformat(), 'passed': False}
|
|
failed = False
|
|
try:
|
|
stack.start(build=not args.no_build)
|
|
suite = Suite(stack)
|
|
scenarios = ['upload_async', 'worker_down', 'outbox_crash', 'reliability'] if args.scenario == 'all' else [
|
|
{'upload': 'upload_async', 'worker_down': 'worker_down', 'outbox': 'outbox_crash', 'reliability': 'reliability'}[args.scenario]]
|
|
for scenario in scenarios:
|
|
getattr(suite, scenario)()
|
|
suite.public_smoke()
|
|
result['passed'] = True
|
|
except (Failure, OSError, ValueError, http.client.HTTPException, subprocess.TimeoutExpired) as error:
|
|
failed = True
|
|
# Do not print command argv, HTTP bodies or environment on failure.
|
|
result['error'] = str(error) if isinstance(error, Failure) else type(error).__name__
|
|
print('FAIL:', result['error'], file=sys.stderr)
|
|
finally:
|
|
try:
|
|
stack.close()
|
|
result['cleanup'] = 'removed own project and volumes; disposable secrets deleted'
|
|
except (Failure, OSError, subprocess.TimeoutExpired):
|
|
failed = True
|
|
result['passed'] = False
|
|
result['cleanup'] = 'FAILED; remove only project ' + stack.project
|
|
print('FAIL: cleanup of own project ' + stack.project, file=sys.stderr)
|
|
result['events'] = stack.events
|
|
result['elapsed_seconds'] = round(time.monotonic() - started, 3)
|
|
if args.output:
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
|
|
return 1 if failed else 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|