Files
mtusi2026lab6-fork/student-tests/job_lifecycle.py
T

90 lines
3.8 KiB
Python

"""Exercise job fencing, failed replay and cleanup on the stage-5 stand."""
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
code = """
import sys
from messenger.attachments import AttachmentStorage
from messenger.config import Config
from messenger.db import Database
from messenger.errors import Conflict
import messenger.job_lifecycle as lifecycle
from messenger.worker import materialize, process
db = Database(Config.from_env())
db.open()
s3 = AttachmentStorage()
aid = sys.argv[1]
def delivery():
with db.cursor() as cur:
cur.execute('SELECT id AS job_id,attachment_id,pipeline_version,attempt FROM attachment_jobs WHERE attachment_id=%s', (aid,))
return cur.fetchone()
try:
first = delivery()
row = lifecycle.claim(db, first)
assert row['status'] == 'processing' and lifecycle.claim(db, first) is None
stale_result = materialize(row, s3, first['pipeline_version'], first['attempt'])
with db.cursor() as cur:
cur.execute("UPDATE attachment_jobs SET lease_until=now()-interval '1 second' WHERE id=%s", (first['job_id'],))
lifecycle.recover_expired(db)
second = delivery()
assert second['attempt'] == first['attempt'] + 1
assert not lifecycle.complete(db, first, result=stale_result)
assert lifecycle.claim(db, second)
lifecycle.MAX_ATTEMPTS = 2
assert lifecycle.complete(db, second)
with db.cursor() as cur:
cur.execute('SELECT status,error_code FROM attachments WHERE id=%s', (aid,))
assert cur.fetchone() == {'status':'failed','error_code':'retry_exhausted'}
assert lifecycle.replay(db, first['job_id'], 'stage5-test') == 3
third = delivery()
process(db, s3, third)
process(db, s3, third)
try:
lifecycle.replay(db, first['job_id'], 'stage5-test')
except Conflict:
pass
else:
raise AssertionError('ready job was replayed')
with db.cursor() as cur:
cur.execute('SELECT count(*) AS n FROM attachment_variants WHERE attachment_id=%s', (aid,))
assert cur.fetchone()['n'] == 3
cur.execute('SELECT count(*) AS n FROM attachment_replays WHERE job_id=%s', (first['job_id'],))
assert cur.fetchone()['n'] == 1
cur.execute("UPDATE attachment_outbox SET available_at=now()-interval '16 minutes' WHERE job_id=%s AND attempt=1",
(first['job_id'],))
# Check that the cleaner can remove an obsolete attempt even after replay succeeded.
removed = []
while lifecycle.clean_abandoned_outputs(db, lambda key: (s3.delete(key), removed.append(key))):
pass
assert stale_result[0] in removed, removed
while lifecycle.clean_staging(db, s3.delete):
pass
with db.cursor() as cur:
cur.execute('SELECT staging_cleaned_at,lease_until FROM attachment_jobs WHERE id=%s', (first['job_id'],))
row = cur.fetchone()
assert row['staging_cleaned_at'] is not None and row['lease_until'] is None
print('PASS: expired claim fenced, retry exhausted, audited replay, stale objects and staging cleaned')
finally:
db.close()
"""
subprocess.run(['docker', 'compose', 'exec', '-T', 'api-a', 'python', '-c',
code, attachment['id']], cwd=ROOT, check=True, timeout=45)
path = f"/api/v1/attachments/{attachment['id']}/content"
check(client.call('GET', path, actor=bob)['bytes'] == original, 'cleanup damaged original')
print('PASS: ready original survives cleanup and replay requests')
if __name__ == '__main__':
run(main)