#!/usr/bin/env python3 """Track 2: repeatable reconciler experiment for the two lab4 stores. Hypothesis: a single-pass reconciler that compares PostgreSQL attachment rows with the private bucket, protects everything younger than a configurable grace period, and re-reads each row immediately before a mutation can remove only provably unreferenced stale objects and stale upload intents. It must never delete a ready attachment that a message uses, a fresh upload in flight, or a file whose metadata and bytes still agree, and it must not invent missing bytes or report a missing object as ready. Protocol: 1. create a reproducible base set of attachments (half linked to messages); 2. measure clean dry-run scans (cost of the traversal); 3. inject real faults on both sides: - stale orphan object (S3 has no metadata row), - stale pending intent with object (crash between PUT and COMMIT), - stale pending intent without object, - ready metadata whose object is gone (missing, used and unused), - fresh orphan object and fresh pending intent (must be protected); 4. dry-run (no mutations), verify findings and unchanged counts; 5. apply, verify only the provable stale items changed; 6. rerun apply immediately (no new deletions while fresh items are young); 7. wait past the grace period and apply again: the fresh orphan is then old enough to remove, while a completed real attachment stays intact; 8. verify the API still serves used attachments and new uploads. Python 3.9+, standard library only. Requires the running stand and Docker. Raw reports and a compact summary are written under evidence/track2/. """ import concurrent.futures import hashlib import json import statistics import subprocess import sys import time import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) sys.path.insert(0, str(ROOT / 'scripts')) from client import Client, Failure, arguments, check # noqa: E402 import lab4_metrics as M # noqa: E402 EVIDENCE = ROOT / 'evidence' / 'track2' BASE_SIZE = 300 USED_SIZE = 150 GRACE = 20 RESULTS = [] def ok(condition, message): RESULTS.append({'check': message, 'passed': bool(condition)}) check(condition, message) def reconcile(apply, grace, output_path): command = [ str(ROOT / 'scripts/compose.sh'), '--env-file', '.env', 'run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconciler', 'api', '-prefix', 'attachments/', '-grace', '%ds' % grace, ] if apply: command.append('-apply') started = M.now_iso() process = M.run(command) finished = M.now_iso() report = json.loads(process.stdout.strip()) report['_invocation'] = {'command': ' '.join(command), 'started_at': started, 'finished_at': finished} M.write_json(output_path, report) return report def object_keys(report, section): return {item['object_key'] for item in (report['findings'].get(section) or [])} def item_ids(report, section): return {item['id'] for item in (report['findings'].get(section) or []) if item.get('id')} def attachment_count(status=None): where = '' if status is None else " WHERE status = '%s'" % status return int(M.psql('SELECT count(*) FROM attachments' + where)) def link_count(): return int(M.psql('SELECT count(*) FROM message_attachments')) def object_exists(key): return M.s3ctl('-op', 'stat', '-key', key, check=False).returncode == 0 def put_object(key, data, container=None): container = container or M.compose_ids('api')[0] name = '/tmp/lab4-track2-object.bin' process = subprocess.run( ['docker', 'exec', '-i', container, 'sh', '-c', 'cat > ' + name], input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) if process.returncode != 0: raise RuntimeError('could not stage object in API container') M.s3ctl('-op', 'put', '-key', key, '-file', name, '-content-type', 'image/png') M.run(['docker', 'exec', container, 'rm', '-f', name]) def delete_object(key): M.s3ctl('-op', 'delete', '-key', key) def insert_pending(attachment_id, chat_id, owner_id, object_key, data, age_seconds): M.psql( "INSERT INTO attachments " "(id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, error_code, " " object_key, created_at, updated_at) VALUES " "('%s'::uuid, '%s'::uuid, '%s'::uuid, 'crash.png', 'image/png', %d, '%s', 'pending', NULL, " " '%s', now() - interval '%d seconds', now() - interval '%d seconds')" % ( attachment_id, chat_id, owner_id, len(data), hashlib.sha256(data).hexdigest(), object_key, age_seconds, age_seconds)) def promote_ready(attachment_id): M.psql("UPDATE attachments SET status = 'ready', updated_at = now() " "WHERE id = '%s'::uuid AND status = 'pending'" % attachment_id) def all_messages(c, actor, chat): from urllib.parse import quote path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100' items, seen = [], set() for _ in range(1000): page = c.call('GET', path, actor=actor, schema='MessagePage')['json'] items.extend(page['items']) cursor = page['next_cursor'] if cursor is None: return items if cursor in seen: raise Failure('message cursor cycle') seen.add(cursor) path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100&cursor=' + quote(cursor, safe='') raise Failure('message history exceeded safety bound') def sleep_until_age(started_monotonic, grace, margin=1.5): while time.monotonic() - started_monotonic < grace + margin: time.sleep(0.25) def main(): args = arguments('Track 2 reconciler experiment; injects faults into SQL and S3') EVIDENCE.mkdir(parents=True, exist_ok=True) c = Client(args.base_url, args.ca_file) alice, bob, eve, chat = c.bootstrap() sample = M.fixture_bytes('sample.png') sha = hashlib.sha256(sample).hexdigest() revision = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip() api_image = M.containers('api')[0]['image_id'] print('== reproducible base set ==') rows_pre = attachment_count() objects_pre = M.s3_count() attachments = [] for index in range(BASE_SIZE): response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=track2-%03d.png' % index, 201, actor=alice, raw=sample, headers={'Content-Type': 'image/png'}, schema='Attachment') attachments.append({'id': response['json']['id'], 'used': False, 'size_bytes': response['json']['size_bytes']}) used_messages = [] for index in range(USED_SIZE // 10): chosen = attachments[index * 10:(index + 1) * 10] message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice, body={'text': 'track2 link %02d' % index, 'attachment_ids': [item['id'] for item in chosen]}, headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')['json'] used_messages.append(message) for item in chosen: item['used'] = True used = [item for item in attachments if item['used']] unused = [item for item in attachments if not item['used']] ok(len(attachments) == BASE_SIZE and len(used) == USED_SIZE and len(unused) == BASE_SIZE - USED_SIZE, 'base attachment set is incomplete') ok(all(message['attachment_ids'] == [item['id'] for item in attachments[index * 10:(index + 1) * 10]] for index, message in enumerate(used_messages)), 'message attachments were reordered') baseline_rows = attachment_count() - rows_pre baseline_objects = M.s3_count() - objects_pre baseline_links = link_count() ok(baseline_rows == BASE_SIZE and baseline_objects == BASE_SIZE, 'base rows/objects were not exactly the %d uploads' % BASE_SIZE) # A previous interrupted run may have left stale pending rows/orphans. # One preliminary apply makes the cost baseline honest on a reused stand; # on a clean stand it deletes nothing. cleanup = reconcile(True, GRACE, EVIDENCE / 'raw-cleanup.json') cleanup_deleted = list(cleanup['actions'].get('deleted_objects') or []) + list( cleanup['actions'].get('deleted_pending_rows') or []) if cleanup_deleted: print('pre-run cleanup removed %d leftovers from an earlier interrupted run' % len(cleanup_deleted)) print('== cost of a clean traversal ==') cost_runs = [] for index in range(3): report = reconcile(False, 3600, EVIDENCE / ('raw-cost-%d.json' % index)) cost_runs.append({ 'run': index + 1, 'generated_at': report['generated_at'], 'db_scan_ms': report['timing']['db_scan_ms'], 's3_list_ms': report['timing']['s3_list_ms'], 'total_ms': report['timing']['total_ms'], 'db_rows': report['timing']['db_rows'], 's3_objects': report['timing']['s3_objects'], }) ok(all(run['db_rows'] >= BASE_SIZE and run['s3_objects'] >= BASE_SIZE for run in cost_runs), 'cost run did not scan the full base set') print('== inject faults on both sides ==') stale_started = time.monotonic() stale_orphan = 'attachments/orphan-stale-' + uuid.uuid4().hex put_object(stale_orphan, sample) crash_one = str(uuid.uuid4()) crash_one_key = 'attachments/' + crash_one insert_pending(crash_one, chat['id'], alice['id'], crash_one_key, sample, 60) put_object(crash_one_key, sample) crash_two = str(uuid.uuid4()) crash_two_key = 'attachments/' + crash_two insert_pending(crash_two, chat['id'], alice['id'], crash_two_key, sample, 60) missing_used = used[0] missing_unused = unused[0] missing_used_key = M.psql("SELECT object_key FROM attachments WHERE id = '%s'::uuid" % missing_used['id']) missing_unused_key = M.psql("SELECT object_key FROM attachments WHERE id = '%s'::uuid" % missing_unused['id']) delete_object(missing_used_key) delete_object(missing_unused_key) ok(not object_exists(missing_used_key) and not object_exists(missing_unused_key), 'missing objects were not removed from S3') # The stale orphan must be older than the grace period. The injected rows # are already older by construction; the S3 object uses its real mtime. sleep_until_age(stale_started, GRACE) active_id = str(uuid.uuid4()) active_key = 'attachments/' + active_id insert_pending(active_id, chat['id'], alice['id'], active_key, sample, 0) put_object(active_key, sample) fresh_orphan = 'attachments/orphan-fresh-' + uuid.uuid4().hex put_object(fresh_orphan, sample) fresh_started = time.monotonic() rows_before = attachment_count() objects_before = M.s3_count() links_before = link_count() print('== dry run: detection without mutation ==') dry = reconcile(False, GRACE, EVIDENCE / 'raw-dry-run.json') ok(stale_orphan in object_keys(dry, 'orphan_objects'), 'stale orphan object not detected') ok(fresh_orphan in object_keys(dry, 'protected_recent_objects'), 'fresh orphan object not protected') ok({crash_one, crash_two} <= item_ids(dry, 'stale_pending'), 'stale upload intents not detected') ok(active_id in item_ids(dry, 'protected_pending'), 'fresh upload intent not protected') ok({missing_used['id'], missing_unused['id']} <= item_ids(dry, 'missing_objects'), 'missing objects not detected') ok(not (dry['actions'].get('deleted_objects') or []), 'dry run deleted objects') ok(not (dry['actions'].get('deleted_pending_rows') or []), 'dry run deleted rows') ok(attachment_count() == rows_before and M.s3_count() == objects_before and link_count() == links_before, 'dry run mutated either store') ok(object_exists(stale_orphan) and object_exists(fresh_orphan), 'dry run removed an object') ok(object_exists(active_key), 'dry run removed an active upload object') print('== apply: only provable stale items ==') def upload_worker(index): local = Client(c.base) response = local.call( 'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=concurrent-%d.png' % index, 201, actor=alice, raw=sample, headers={'Content-Type': 'image/png'}, schema='Attachment') return response['json'] upload_pool = concurrent.futures.ThreadPoolExecutor(max_workers=6) upload_futures = [upload_pool.submit(upload_worker, index) for index in range(6)] # Run the reconciler while those uploads are in flight. Their rows/objects # are younger than the grace period and must not be touched. apply = reconcile(True, GRACE, EVIDENCE / 'raw-apply.json') uploaded_concurrently = [future.result() for future in upload_futures] upload_pool.shutdown() ok(all(item['status'] == 'ready' for item in uploaded_concurrently), 'concurrent upload during reconcile did not finish ready') deleted_objects = set(apply['actions'].get('deleted_objects') or []) deleted_rows = set(apply['actions'].get('deleted_pending_rows') or []) ok(stale_orphan in deleted_objects, 'stale orphan object was not removed') ok(crash_one in deleted_rows and crash_two in deleted_rows, 'stale pending rows were not removed') ok(crash_one_key in deleted_objects, 'stale pending object was not removed') ok(not object_exists(stale_orphan) and not object_exists(crash_one_key) and not object_exists(crash_two_key), 'stale S3 objects survived apply') ok(M.psql("SELECT count(*) FROM attachments WHERE id IN ('%s'::uuid, '%s'::uuid)" % (crash_one, crash_two)).strip() == '0', 'stale pending rows survived apply') ok(object_exists(fresh_orphan), 'fresh orphan object was deleted inside grace') rows_after_apply = rows_before + len(uploaded_concurrently) - 2 ok(object_exists(active_key) and attachment_count() == rows_after_apply, 'active upload, concurrent upload or active row was deleted') ok({missing_used['id'], missing_unused['id']} <= set(apply['actions'].get('unresolved_missing') or []), 'missing objects were not left for manual recovery') ok(link_count() == links_before, 'apply changed message attachment links') ok(M.psql("SELECT status FROM attachments WHERE id = '%s'::uuid" % active_id).strip() == 'pending', 'active upload intent changed state unexpectedly') # The simulated in-flight upload completes: the same row is promoted ready # and becomes usable, proving the reconciler protected a real file. promote_ready(active_id) active_message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice, body={'text': '', 'attachment_ids': [active_id]}, headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')['json'] ok(active_message['attachment_ids'] == [active_id], 'protected upload cannot be attached after completion') active_download = c.call('GET', '/api/v1/attachments/' + active_id + '/content', actor=bob) ok(active_download['bytes'] == sample, 'protected upload bytes changed') print('== rerun before grace expiry: no new deletions ==') rerun = reconcile(True, GRACE, EVIDENCE / 'raw-rerun.json') ok(not (rerun['actions'].get('deleted_objects') or []), 'rerun deleted objects') ok(not (rerun['actions'].get('deleted_pending_rows') or []), 'rerun deleted rows') ok(fresh_orphan in object_keys(rerun, 'protected_recent_objects'), 'fresh orphan lost protection on rerun') ok(object_exists(fresh_orphan), 'fresh orphan removed on rerun') print('== grace expiry: the fresh orphan is now old enough ==') sleep_until_age(fresh_started, GRACE) expired = reconcile(True, GRACE, EVIDENCE / 'raw-after-grace.json') ok(fresh_orphan in set(expired['actions'].get('deleted_objects') or []), 'aged orphan was not removed after grace') ok(not object_exists(fresh_orphan), 'aged orphan object still exists') ok(attachment_count() == rows_after_apply, 'grace expiry deleted a metadata row') ok(c.call('GET', '/api/v1/attachments/' + active_id + '/content', actor=bob)['bytes'] == sample, 'completed protected attachment lost after grace expiry') print('== API and used attachments after reconciliation ==') history = all_messages(c, bob, chat) indexed = {item['id']: item for item in history} for message in used_messages: ok(message['id'] in indexed, 'used message disappeared from history') ok(indexed[message['id']]['attachment_ids'] == message['attachment_ids'], 'used message lost or reordered its attachment links') sample_used = used[10] download = c.call('GET', '/api/v1/attachments/' + sample_used['id'] + '/content', actor=bob) ok(download['bytes'] == sample, 'used attachment bytes changed or disappeared') c.call('GET', '/api/v1/attachments/' + sample_used['id'], 404, actor=eve) c.call('GET', '/api/v1/attachments/' + missing_used['id'], 404, actor=bob) c.call('GET', '/api/v1/attachments/' + missing_unused['id'] + '/content', 404, actor=bob) new_attachment = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after.png', 201, actor=alice, raw=sample, headers={'Content-Type': 'image/png'}, schema='Attachment')['json'] ok(new_attachment['sha256'] == sha, 'new upload after reconciliation failed') failures = [item for item in RESULTS if not item['passed']] summary = { 'track': 'Track 2: consistency of two stores', 'hypothesis': ('A grace-protected, re-checked reconciler removes only stale orphan objects and ' 'stale upload intents, and never deletes ready/used/fresh attachments or invents ' 'missing bytes.'), 'generated_at': M.now_iso(), 'git_revision': revision, 'api_image_id': api_image, 'database_rows_base': baseline_rows, 'object_store_objects_base': baseline_objects, 'message_attachment_links_base': baseline_links, 'base_profile': { 'attachments': BASE_SIZE, 'linked_attachments': USED_SIZE, 'unlinked_ready_attachments': BASE_SIZE - USED_SIZE, 'bytes_per_attachment': len(sample), 'total_attachment_bytes': BASE_SIZE * len(sample), 'image_profile': 'tests/fixtures/sample.png 320x200, identical synthetic bytes', }, 'grace_seconds': GRACE, 'cost_runs': cost_runs, 'cost_summary': { 'runs': len(cost_runs), 'db_scan_ms_median': statistics.median(run['db_scan_ms'] for run in cost_runs), 's3_list_ms_median': statistics.median(run['s3_list_ms'] for run in cost_runs), 'total_ms_median': statistics.median(run['total_ms'] for run in cost_runs), 'note': 'traversal cost is O(rows + objects); timings are wall-clock milliseconds ' 'reported by the reconciler process on this local stand', }, 'injected': { 'stale_orphan_object': stale_orphan, 'stale_pending_with_object': {'id': crash_one, 'object_key': crash_one_key}, 'stale_pending_without_object': {'id': crash_two, 'object_key': crash_two_key}, 'missing_used_attachment': {'id': missing_used['id'], 'object_key': missing_used_key}, 'missing_unused_attachment': {'id': missing_unused['id'], 'object_key': missing_unused_key}, 'fresh_orphan_object': fresh_orphan, 'active_upload_intent': {'id': active_id, 'object_key': active_key}, }, 'dry_run': { 'orphan_objects': sorted(object_keys(dry, 'orphan_objects')), 'protected_recent_objects': sorted(object_keys(dry, 'protected_recent_objects')), 'stale_pending': sorted(item_ids(dry, 'stale_pending')), 'protected_pending': sorted(item_ids(dry, 'protected_pending')), 'missing_objects': sorted(item_ids(dry, 'missing_objects')), 'deleted_objects': dry['actions'].get('deleted_objects') or [], 'deleted_pending_rows': dry['actions'].get('deleted_pending_rows') or [], }, 'apply': { 'deleted_objects': sorted(deleted_objects), 'deleted_pending_rows': sorted(deleted_rows), 'unresolved_missing': apply['actions'].get('unresolved_missing') or [], }, 'rerun': { 'deleted_objects': rerun['actions'].get('deleted_objects') or [], 'deleted_pending_rows': rerun['actions'].get('deleted_pending_rows') or [], }, 'after_grace': { 'deleted_objects': expired['actions'].get('deleted_objects') or [], 'deleted_pending_rows': expired['actions'].get('deleted_pending_rows') or [], }, 'assertions': RESULTS, 'assertions_failed': len(failures), 'result': 'PASS' if not failures else 'FAIL', 'limitations': [ 'The reconciler never deletes or fabricates a missing original: bytes cannot be restored ' 'automatically, so those rows are reported as unresolved for operator recovery.', 'A simulated in-flight upload row is used as the deterministic active state; real concurrent ' 'uploads are additionally exercised and must finish ready.', 'Cost is measured on this 2 vCPU / ~2 GiB Colima stand and does not extrapolate to production.', 'The S3 ListObjects scan is not a snapshot: concurrent uploads are protected by the grace ' 'period and by the immediate database re-check before each delete.', ], } M.write_json(EVIDENCE / 'dataset.json', { 'generated_at': summary['generated_at'], 'base_profile': summary['base_profile'], 'attachments': attachments, 'used_messages': [{'id': item['id'], 'attachment_ids': item['attachment_ids']} for item in used_messages], 'concurrent_uploads': [item['id'] for item in uploaded_concurrently], }) M.write_json(EVIDENCE / 'summary.json', summary) print(json.dumps({'result': summary['result'], 'assertions': len(RESULTS), 'failed': len(failures), 'cost_ms_median': summary['cost_summary']['total_ms_median']}, ensure_ascii=False)) if failures: raise SystemExit('FAILED checks: ' + ', '.join(item['check'] for item in failures)) print('PASS: track 2 reconciler experiment') if __name__ == '__main__': try: main() except (Failure, ValueError, OSError) as exc: print('FAIL:', str(exc)) raise SystemExit(1)