178 lines
8.6 KiB
Python
178 lines
8.6 KiB
Python
import hashlib
|
|
import json
|
|
import os
|
|
import struct
|
|
import sys
|
|
import time
|
|
import zlib
|
|
from io import BytesIO
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path[:0] = [str(ROOT / 'scripts'), str(ROOT / 'student-tests')]
|
|
import pipeline_suite as ps
|
|
from PIL import Image
|
|
from messenger.attachments.infrastructure.images import RenderLimits, render_variants
|
|
from pictures import SIGNATURE, chunk
|
|
from png_trns_fixtures import png_with_trns
|
|
|
|
MODE = sys.argv.pop(1)
|
|
OUT = Path(__file__).parent / (MODE + '.json')
|
|
if OUT.exists():
|
|
raise SystemExit('Result exists; do not repeat completed evidence')
|
|
SUITE = ps.Suite(ps.arguments())
|
|
STACK = SUITE.stack
|
|
REPORT = {'mode': MODE, 'source_sha': ps.run(['git', 'rev-parse', 'HEAD']).strip(), 'started_at': ps.now(), 'cases': []}
|
|
LIMITS = RenderLimits(10485760, 40000000)
|
|
|
|
|
|
def save():
|
|
OUT.write_text(json.dumps(REPORT, ensure_ascii=False, indent=2) + '\n')
|
|
|
|
|
|
def case(name, function):
|
|
row = {'name': name, 'started_at': ps.now()}
|
|
REPORT['cases'].append(row)
|
|
save()
|
|
began = time.monotonic()
|
|
try:
|
|
row['observed'] = function()
|
|
row['result'] = 'PASS'
|
|
except Exception as error:
|
|
row.update(result='FAIL', error=str(error))
|
|
row['elapsed_seconds'] = round(time.monotonic() - began, 3)
|
|
save()
|
|
print(name, row['result'], row.get('error', ''), flush=True)
|
|
|
|
|
|
def containers():
|
|
return STACK.dc('ps', '-a', '--format', '{{.Name}} {{.ID}} {{.State}} {{.Status}}').splitlines()
|
|
|
|
|
|
def outage():
|
|
SUITE.drained()
|
|
before_dlq = STACK.queues()[ps.DLQ]
|
|
STACK.stop('worker')
|
|
att = SUITE.api.fixture()
|
|
ident = att['id']
|
|
ps.poll(lambda: all(r['published'] for r in STACK.sql('outbox', id=ident)), 30, 'published outbox')
|
|
jobs = STACK.sql('jobs', id=ident)
|
|
REPORT['outage_checkpoint'] = {'attachment_id': ident, 'jobs_before': jobs, 'dlq_before': before_dlq}
|
|
save()
|
|
STACK.stop('postgres')
|
|
REPORT['outage_checkpoint']['stopped_containers'] = containers()
|
|
save()
|
|
since = ps.now()
|
|
STACK.dc('start', 'worker')
|
|
def requeues():
|
|
logs = STACK.dc('logs', '--no-color', '--since', since, 'worker')
|
|
rows = [line for line in logs.splitlines() if 'job.requeued' in line and jobs[0]['job_id'] in line]
|
|
return rows if len(rows) >= 12 else None
|
|
try:
|
|
lines = ps.poll(requeues, 90, '12 real database failures', 1)
|
|
Path(__file__).with_name('postgres-outage-worker.log').write_text('\n'.join(lines) + '\n')
|
|
during = STACK.queues()
|
|
finally:
|
|
STACK.up('postgres')
|
|
ps.poll(lambda: ps.http_ready(SUITE.args.base_url), 30, 'API after PostgreSQL')
|
|
ready = SUITE.api.wait(ident)
|
|
SUITE.verify(ready)
|
|
SUITE.drained()
|
|
after = STACK.sql('jobs', id=ident)
|
|
assert after[0]['job_id'] == jobs[0]['job_id'] and after[0]['attempt'] == jobs[0]['attempt'] == 1
|
|
assert after[0]['status'] == 'done'
|
|
assert STACK.queues()[ps.DLQ] == before_dlq
|
|
assert len(STACK.sql('variants', id=ident)) == 3
|
|
return {'attachment_id': ident, 'jobs_before': jobs, 'jobs_after': after, 'requeues': len(lines), 'queues_during': during, 'queues_after': STACK.queues(), 'replay': False, 'stopped_containers': REPORT['outage_checkpoint']['stopped_containers']}
|
|
|
|
|
|
def png(name, data, reference):
|
|
att = SUITE.api.upload(data, name=name + '.png')
|
|
ident = att['id']
|
|
results = []
|
|
for version in (1, 2):
|
|
if version == 2:
|
|
STACK.admin('reprocess', '--attachment-id', ident, '--pipeline-version', '2')
|
|
ps.poll(lambda: SUITE.record(ident)['published_version'] == 2, 90, 'published v2')
|
|
ready = SUITE.api.wait(ident)
|
|
SUITE.verify(ready)
|
|
assert SUITE.api.content(ident)['bytes'] == data
|
|
expected = {r.name: r for r in render_variants(reference, LIMITS, version)}
|
|
variants = []
|
|
for variant in ready['variants']:
|
|
content = SUITE.api.content(ident, variant['name'])['bytes']
|
|
assert content == expected[variant['name']].data, variant['name'] + ' differs from independent white reference'
|
|
with Image.open(BytesIO(content)) as image:
|
|
assert not image.getexif()
|
|
assert not any(key in image.info for key in ('icc_profile', 'xmp', 'transparency'))
|
|
variants.append({'name': variant['name'], 'sha256': hashlib.sha256(content).hexdigest(), 'bytes': len(content), 'dimensions': [variant['width'], variant['height']]})
|
|
results.append({'version': version, 'variants': variants})
|
|
before = SUITE.snapshot(ident)
|
|
STACK.publish(SUITE.payload(ident, 1))
|
|
STACK.publish(SUITE.payload(ident, 2))
|
|
SUITE.drained()
|
|
assert SUITE.snapshot(ident) == before
|
|
assert len(STACK.sql('variants', id=ident)) == 6
|
|
return {'attachment_id': ident, 'input_sha256': hashlib.sha256(data).hexdigest(), 'input_bytes': len(data), 'versions': results, 'stale_and_duplicate_noop': True}
|
|
|
|
|
|
def large_png(depth, rgb):
|
|
transparent = (12345, 23456, 34567) if rgb else (1 if depth < 16 else 12345,)
|
|
neighbor = (transparent[0] + 1, *transparent[1:])
|
|
def block(pixel):
|
|
if depth < 8:
|
|
value = sum(pixel[0] << shift for shift in range(0, 8, depth))
|
|
return bytes([value]) * (4000 * depth // 8)
|
|
return b''.join(v.to_bytes(depth // 8, 'big') for v in pixel) * 4000
|
|
row = b'\0' + block(transparent) + block(neighbor)
|
|
compressor = zlib.compressobj()
|
|
compressed = b''.join(compressor.compress(row) for _ in range(5000)) + compressor.flush()
|
|
return SIGNATURE + chunk(b'IHDR', struct.pack('>IIBBBBB', 8000, 5000, depth, 2 if rgb else 0, 0, 0, 0)) + chunk(b'tRNS', b''.join(v.to_bytes(2, 'big') for v in transparent)) + chunk(b'IDAT', compressed) + chunk(b'IEND', b'')
|
|
|
|
|
|
def large(name, data):
|
|
assert len(data) < LIMITS.max_bytes
|
|
att = SUITE.api.upload(data, name=name + '.png', final=('ready', 'failed'))
|
|
ready = SUITE.api.wait(att['id'], ('ready', 'failed'))
|
|
row = {'attachment_id': att['id'], 'input_bytes': len(data), 'input_sha256': hashlib.sha256(data).hexdigest(), 'pixels': 40000000, 'status': ready['status'], 'error_code': ready['error_code'], 'jobs': STACK.sql('jobs', id=att['id']), 'memory_peak': STACK.cgroup('worker', 'memory.peak'), 'memory_max': STACK.cgroup('worker', 'memory.max')}
|
|
REPORT['large_observations'] = REPORT.get('large_observations', []) + [row]
|
|
save()
|
|
assert ready['status'] == 'ready', json.dumps(row)
|
|
SUITE.verify(ready)
|
|
assert int(row['memory_peak']) < int(row['memory_max'])
|
|
return row
|
|
|
|
|
|
try:
|
|
SUITE.detect_api()
|
|
SUITE.api = ps.Api(SUITE.args)
|
|
dead_before = STACK.queues()[ps.DLQ][0]
|
|
REPORT['conditions'] = {'host_load': os.getloadavg(), 'containers': containers(), 'running': ps.run(['docker', 'ps', '--format', '{{.Names}} {{.Status}}']), 'worker_limits': STACK.dc('exec', '-T', 'worker', 'printenv', 'RENDER_MEMORY_MB', 'RENDER_TIMEOUT_SECONDS', 'WORKER_CONCURRENCY')}
|
|
save()
|
|
if MODE == 'postgres-outage':
|
|
case('published_outbox_database_outage', outage)
|
|
elif MODE == 'png-http':
|
|
folder = ROOT / 'evidence/review-trns-depth-2026-11-06/fixtures'
|
|
for name in ('gray2', 'gray4', 'rgb16'):
|
|
case(name, lambda name=name: png(name, (folder / (name + '.png')).read_bytes(), (folder / (name + '-white.png')).read_bytes()))
|
|
for name, depth, color in [('gray1', 1, (0,)), ('gray8', 8, (85,)), ('gray16', 16, (12345,)), ('rgb8', 8, (255, 0, 0))]:
|
|
case(name, lambda name=name, depth=depth, color=color: png(name, *png_with_trns(depth, color)))
|
|
case('rgb16-adam7-filter4-exif6', lambda: png('adam7', *png_with_trns(16, (12345, 23456, 34567), size=(65, 63), interlace=1, filtering=4, orientation=6)))
|
|
elif MODE == 'png-limits':
|
|
for name, depth, rgb in [('gray2-40mp', 2, False), ('gray4-40mp', 4, False), ('gray16-40mp', 16, False), ('rgb16-40mp', 16, True)]:
|
|
case(name, lambda name=name, depth=depth, rgb=rgb: large(name, large_png(depth, rgb)))
|
|
data = large_png(16, True)
|
|
case('forced-timeout', lambda: SUITE.limited(data, FAULT_RENDER_TIMEOUT_SECONDS='0.01'))
|
|
case('forced-memory', lambda: SUITE.limited(data, FAULT_RENDER_MEMORY_MB='200'))
|
|
STACK.restore()
|
|
case('normal-after-limits', SUITE.smoke_pipeline)
|
|
REPORT['invariants'] = SUITE.invariants(dead_before)
|
|
finally:
|
|
STACK.up('postgres')
|
|
STACK.restore()
|
|
REPORT['accepted_ids'] = SUITE.api.accepted if SUITE.api else []
|
|
REPORT['finished_at'] = ps.now()
|
|
REPORT['result'] = 'PASS' if REPORT['cases'] and all(x.get('result') == 'PASS' for x in REPORT['cases'] + REPORT.get('invariants', [])) else 'FAIL'
|
|
save()
|
|
raise SystemExit(0 if REPORT['result'] == 'PASS' else 1)
|