forked from mtusi2026/mtusi2026lab6
139 lines
8.7 KiB
Python
139 lines
8.7 KiB
Python
"""Grade 4: durable acceptance, outbox, crashes, lease, retries, explicit replay."""
|
|
import hashlib
|
|
import json
|
|
import time
|
|
import uuid
|
|
from pipeline_helpers import *
|
|
|
|
|
|
def main():
|
|
client = Client(timeout=30)
|
|
ready(client)
|
|
actor, _, _, chat = client.bootstrap()
|
|
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
|
results = {}
|
|
try:
|
|
# Worker absent: no resize in API, accepted job survives real restarts.
|
|
compose('stop', 'worker')
|
|
attachment = upload(client, actor, chat)
|
|
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=actor)
|
|
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
|
|
body={'text': '', 'attachment_ids': [attachment['id']]},
|
|
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')
|
|
services = ('api1', 'api2', 'broker')
|
|
def starts():
|
|
values = {}
|
|
for service in services:
|
|
container = compose('ps', '-q', service)
|
|
data = subprocess.run(['docker', 'inspect', container], capture_output=True, text=True, check=True)
|
|
values[service] = json.loads(data.stdout)[0]['State']['StartedAt']
|
|
return values
|
|
before = starts()
|
|
compose('restart', *services)
|
|
ready(client)
|
|
after = starts()
|
|
check(all(before[s] != after[s] for s in services), 'actual restart not observed')
|
|
check(state(client, actor, attachment)['status'] == 'queued', 'worker stopped but state changed')
|
|
start_only('worker')
|
|
result = wait_state(client, actor, attachment)
|
|
check({v['name'] for v in result['variants']} == {'thumbnail', 'crop', 'optimized'}, 'missing grade4 variants')
|
|
check(client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=actor)['bytes'] == raw, 'original changed')
|
|
wait_for(lambda: psql("SELECT staging_deleted_at IS NOT NULL FROM attachment_jobs WHERE id='" + attachment['id'] + "';") == 't', 'staging not cleaned')
|
|
results['stopped_worker_and_restart'] = dict(status='PASS', before=before, after=after)
|
|
|
|
# Committed outbox remains when dispatcher dies before XADD.
|
|
compose('stop', 'dispatcher')
|
|
fault('dispatcher_before_publish')
|
|
item = upload(client, actor, chat)
|
|
check(psql("SELECT count(*) FROM attachment_outbox WHERE job_id='" + item['id'] + "';") == '1', 'outbox absent')
|
|
compose('start', 'dispatcher')
|
|
hit('dispatcher_before_publish')
|
|
wait_state(client, actor, item)
|
|
results['commit_publish_gap'] = 'PASS: actual dispatcher exit 86 and automatic restart'
|
|
|
|
# Crash after S3 objects, before final PG COMMIT; reclaim expired processing.
|
|
fault('worker_after_objects')
|
|
item = upload(client, actor, chat)
|
|
hit('worker_after_objects')
|
|
check(psql("SELECT state FROM attachment_jobs WHERE id='" + item['id'] + "';") == 'processing', 'crash did not leave processing')
|
|
started = time.monotonic()
|
|
result = wait_state(client, actor, item, timeout=110)
|
|
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == '2', 'expired lease not recovered')
|
|
check(len(result['variants']) == 3, 'duplicate variant metadata')
|
|
results['crash_after_objects'] = dict(status='PASS', recovery_seconds=round(time.monotonic()-started, 3), attempts=2)
|
|
|
|
# COMMIT ready then death before ack: ready must never regress/reprocess.
|
|
fault('worker_before_ack')
|
|
item = upload(client, actor, chat)
|
|
hit('worker_before_ack')
|
|
result = wait_state(client, actor, item)
|
|
attempts = psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';")
|
|
duplicate = dict(schema_version=1, job_id=item['id'], type='attachment.process.v1', attachment_id=item['id'],
|
|
pipeline_version=1, attempt=1, created_at=item['created_at'])
|
|
# Use broker password only inside the container, never in evidence.
|
|
duplicate_id = compose('exec', '-T', 'broker', 'sh', '-ec',
|
|
'redis-cli --no-auth-warning -a "$(cat /run/secrets/broker_password)" XADD attachment.jobs.v1 "*" job "$1"',
|
|
'sh', json.dumps(duplicate))
|
|
wait_for(lambda: compose('exec', '-T', 'broker', 'sh', '-ec',
|
|
'redis-cli --raw --no-auth-warning -a "$(cat /run/secrets/broker_password)" XRANGE attachment.jobs.v1 "$1" "$1"',
|
|
'sh', duplicate_id) == '', 'ready duplicate was not acknowledged')
|
|
check(state(client, actor, item) == result, 'ready duplicate changed result')
|
|
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == attempts, 'ready duplicate processed again')
|
|
results['commit_before_ack_and_duplicate'] = 'PASS'
|
|
|
|
# Temporary S3 failure: attempt budget/backoff, failed registry, audited replay.
|
|
compose('stop', 'worker')
|
|
item = upload(client, actor, chat)
|
|
psql("UPDATE attachment_jobs SET max_attempts=2 WHERE id='" + item['id'] + "';")
|
|
compose('stop', 's3')
|
|
start_only('worker')
|
|
check(compose('ps', '--status', 'running', '-q', 's3') == '', 'fault test unexpectedly restarted S3')
|
|
wait_for(lambda: psql("SELECT state FROM attachment_jobs WHERE id='" + item['id'] + "';") == 'failed', 'temporary errors did not exhaust retries', 100)
|
|
compose('start', 's3')
|
|
ready(client)
|
|
failed = state(client, actor, item)
|
|
check(failed['error_code'] == 'retry_exhausted', 'unsafe or missing final error')
|
|
client.call('GET', '/api/v1/attachments/' + item['id'] + '/content', 409, actor=actor)
|
|
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=actor,
|
|
body={'text':'failed', 'attachment_ids':[item['id']]}, headers={'Idempotency-Key':uuid.uuid4().hex})
|
|
registry = compose('exec', '-T', 'dispatcher', '/messenger', 'failed-jobs')
|
|
check(item['id'] in registry, 'failed registry missing job')
|
|
compose('exec', '-T', 'dispatcher', '/messenger', 'replay', item['id'])
|
|
wait_state(client, actor, item)
|
|
check(psql("SELECT count(*) FROM attachment_replays WHERE job_id='" + item['id'] + "';") == '1', 'replay audit missing')
|
|
proc = subprocess.run(['docker','compose','--env-file','.env','exec','-T','dispatcher','/messenger','replay',item['id']], cwd=ROOT, capture_output=True)
|
|
check(proc.returncode != 0, 'ready replay must be refused')
|
|
results['retry_failed_registry_replay'] = dict(status='PASS', exhausted_attempts=2, error_code='retry_exhausted', replay_audit_rows=1, ready_replay_rejected=True)
|
|
|
|
# Permanent invalid staging: no endless retries, safe machine error.
|
|
compose('stop', 'worker')
|
|
item = upload(client, actor, chat)
|
|
original_key = uuid.uuid4().hex
|
|
original_body = {'text':'accepted while queued', 'attachment_ids':[item['id']]}
|
|
original_message = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
|
|
actor=actor, body=original_body, headers={'Idempotency-Key':original_key}, schema='Message')['json']
|
|
# Integrity metadata mismatch represents invalid durable source.
|
|
psql("UPDATE attachments SET sha256=repeat('0',64) WHERE id='" + item['id'] + "';")
|
|
start_only('worker')
|
|
failed = wait_state(client, actor, item, 'failed')
|
|
check(failed['error_code'] == 'invalid_image', 'permanent invalid source must fail safely')
|
|
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == '1', 'permanent error retried')
|
|
repeated = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
|
|
actor=actor, body=original_body, headers={'Idempotency-Key':original_key}, schema='Message')['json']
|
|
check(repeated == original_message, 'committed message replay changed after attachment failed')
|
|
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409,
|
|
actor=actor, body=original_body, headers={'Idempotency-Key':uuid.uuid4().hex})
|
|
results['permanent_error'] = 'PASS'
|
|
results['message_replay_after_attachment_failure'] = 'PASS'
|
|
results['crash_points'] = json.loads(psql("SELECT json_agg(json_build_object('point',point,'armed',armed,'hit_at',hit_at) ORDER BY point) FROM pipeline_faults WHERE hit_at IS NOT NULL;"))
|
|
dump_evidence('pipeline-grade4.json', results)
|
|
print('PASS:', json.dumps(results))
|
|
finally:
|
|
compose('start', 's3', 'broker', 'dispatcher', 'worker', 'api1', 'api2')
|
|
psql('DELETE FROM pipeline_faults;')
|
|
ready(client)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|