Files
mtusi2026lab4/src/reconcile.py
T

130 lines
6.9 KiB
Python

"""Conservative two-store reconciler; dry-run by default, no API endpoint."""
import argparse
import datetime as dt
import hashlib
import json
import re
import time
import psycopg
from psycopg.rows import dict_row
from botocore.exceptions import BotoCoreError, ClientError
from objects import Objects
from postgres import setting
def reconcile(apply=False, grace=3600):
started = time.monotonic()
# Fixed cutoff for the entire pass: objects born during scanning stay protected.
cutoff = dt.datetime.now(dt.timezone.utc) - dt.timedelta(seconds=grace)
objects = Objects(setting)
counts = dict(metadata=0, objects=0, head_calls=0, get_calls=0, deleted_objects=0, deleted_intents=0, marked_missing=0, restored=0, skipped_locked=0, protected_fresh=0, protected_ready=0, protected_foreign_prefix=0)
findings = []
def note(kind, attachment_id):
if len(findings) < 200:
findings.append({'kind': kind, 'id': str(attachment_id)})
with psycopg.connect(setting('DATABASE_URL'), autocommit=True, row_factory=dict_row, connect_timeout=2, options='-c statement_timeout=2000 -c lock_timeout=500') as conn:
if not conn.execute('SELECT pg_try_advisory_lock(2301004) AS locked').fetchone()['locked']:
raise RuntimeError('Another reconciler is running')
last = '00000000-0000-0000-0000-000000000000'
while True:
batch = conn.execute('SELECT id FROM attachments WHERE 1=1 AND id > %s ORDER BY id LIMIT 100', (last,)).fetchall()
if not batch:
break
for item in batch:
last = item['id']
counts['metadata'] += 1
with conn.transaction():
row = conn.execute('SELECT * FROM attachments WHERE 1=1 AND id = %s FOR UPDATE SKIP LOCKED', (last,)).fetchone()
if row is None:
counts['skipped_locked'] += 1
continue
if row['updated_at'] > cutoff:
counts['protected_fresh'] += 1
continue
head = objects.head(row['object_key'])
counts['head_calls'] += 1
if row['state'] == 'uploading':
# FK and state locking also prevent deleting anything referenced.
used = conn.execute('SELECT 1 FROM message_attachments WHERE 1=1 AND attachment_id = %s LIMIT 1', (last,)).fetchone()
if used:
note('unexpected_used_intent_retained', last)
continue
note('stale_intent', last)
if apply:
objects.delete(row['object_key'])
counts['deleted_objects'] += int(head is not None)
conn.execute("DELETE FROM attachments WHERE 1=1 AND id = %s AND state = 'uploading'", (last,))
counts['deleted_intents'] += 1
elif head is None or head['ContentLength'] != row['size_bytes'] or head.get('Metadata', {}).get('sha256') != row['sha256']:
note('missing_or_mismatched', last)
if apply and row['state'] != 'storage_missing':
conn.execute("UPDATE attachments SET state = 'storage_missing', updated_at = clock_timestamp() WHERE 1=1 AND id = %s", (last,))
counts['marked_missing'] += 1
elif row['state'] == 'storage_missing':
# Recovery needs actual bytes, not merely a claimed metadata hash.
response = objects.get(row['object_key'])
counts['get_calls'] += 1
digest = hashlib.sha256()
size = 0
with response['Body'] as stream:
for chunk in iter(lambda: stream.read(64 * 1024), b''):
digest.update(chunk)
size += len(chunk)
if size == row['size_bytes'] and digest.hexdigest() == row['sha256']:
note('recoverable', last)
if apply:
conn.execute("UPDATE attachments SET state = 'ready', updated_at = clock_timestamp() WHERE 1=1 AND id = %s", (last,))
counts['restored'] += 1
else:
note('corrupt_recovery_retained', last)
else:
counts['protected_ready'] += 1
# Paginated listing; never collect all keys in memory.
paginator = objects.client.get_paginator('list_objects_v2')
for result in paginator.paginate(Bucket=objects.bucket, Prefix='originals/', PaginationConfig={'PageSize': 100}):
for item in result.get('Contents', []):
counts['objects'] += 1
key = item['Key']
if not re.fullmatch(r'originals/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}', key):
counts['protected_foreign_prefix'] += 1
continue
if item['LastModified'] > cutoff:
counts['protected_fresh'] += 1
continue
# A valid upload commits intent BEFORE PUT, and never reuses object keys.
with conn.transaction():
if conn.execute('SELECT 1 FROM attachments WHERE 1=1 AND object_key = %s', (key,)).fetchone():
continue
head = objects.head(key)
counts['head_calls'] += 1
if head is None or head['LastModified'] > cutoff:
continue
note('orphan', key.split('/')[1])
if apply:
objects.delete(key)
counts['deleted_objects'] += 1
objects.client.close()
return dict(apply=apply, grace_seconds=grace, elapsed_seconds=round(time.monotonic() - started, 6), counts=counts, findings=findings)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply', action='store_true')
parser.add_argument('--grace-seconds', type=int, default=3600)
parser.add_argument('--allow-short-test-grace', action='store_true', help='Only on an isolated synthetic test stand')
args = parser.parse_args()
if args.grace_seconds < (1 if args.allow_short_test_grace else 3600):
parser.error('Production grace must be at least 3600 seconds')
try:
print(json.dumps(reconcile(args.apply, args.grace_seconds), indent=2))
except Exception:
# Do not serialize library exception details, DSNs, signatures or keys.
print(json.dumps({'error': 'Reconciliation aborted; no fail-open cleanup. Retry after restoring dependencies.'}))
raise SystemExit(1)
if __name__ == '__main__':
main()