"""Offline supplied-trace reconciliation. Never authorizes or performs a retry.""" import hashlib import json import re import sys TOKEN = re.compile(r'[A-Za-z0-9_.-]{1,64}\Z') HASH = re.compile(r'[0-9a-f]{64}\Z') FIELDS = {'event_id', 'operation_id', 'attempt_id', 'target_id', 'kind', 'idempotency_key', 'payload_sha256', 'effect_id'} def reconcile(document): if not isinstance(document, dict) or set(document) != {'events'}: raise ValueError('Expected only an events array') events = document['events'] if not isinstance(events, list) or not 1 <= len(events) <= 300: raise ValueError('Expected 1..300 events') ids = set() attempts = {} operations = {} keys = {} for index, event in enumerate(events): if not isinstance(event, dict) or set(event) != FIELDS: raise ValueError('Every event must have exactly the documented fields') for field in ('event_id', 'operation_id', 'attempt_id', 'target_id'): if not isinstance(event[field], str) or not TOKEN.fullmatch(event[field]): raise ValueError('Invalid redacted identifier') if event['event_id'] in ids: raise ValueError('Duplicate event identity; ambiguous input') ids.add(event['event_id']) if event['kind'] not in ('attempt', 'timeout', 'effect'): raise ValueError('Unsupported event kind') if not isinstance(event['payload_sha256'], str) or not HASH.fullmatch(event['payload_sha256']): raise ValueError('Invalid payload digest') for field in ('idempotency_key', 'effect_id'): if event[field] is not None and (not isinstance(event[field], str) or not TOKEN.fullmatch(event[field])): raise ValueError('Invalid redacted key/effect identifier') if (event['kind'] == 'effect') != (event['effect_id'] is not None): raise ValueError('Only an effect event has an effect identity') identity = (event['operation_id'], event['attempt_id']) signature = (event['target_id'], event['idempotency_key'], event['payload_sha256']) if identity in attempts and attempts[identity] != signature: raise ValueError('Conflicting records for the same attempt') attempts[identity] = signature operations.setdefault(event['operation_id'], []).append(event) if event['idempotency_key'] is not None: keys.setdefault((event['target_id'], event['idempotency_key']), []).append(event) if len(operations) > 30: raise ValueError('More than 30 logical operations') # Canonical sorting makes conclusions independent of arrival order. findings = [] summaries = [] for operation, rows in sorted(operations.items()): effects = sorted({(r['target_id'], r['effect_id']) for r in rows if r['kind'] == 'effect'}) attempts_seen = sorted({r['attempt_id'] for r in rows}) references = sorted(r['event_id'] for r in rows) state = 'multiple_effects_reported' if len(effects) > 1 else ('one_effect_reported' if effects else 'outcome_unknown') summaries.append({'operation_id': operation, 'state': state, 'attempt_ids': attempts_seen, 'reported_effects': [{'target_id': t, 'effect_id': e} for t, e in effects], 'evidence_event_ids': references}) if len(effects) > 1: findings.append({'kind': 'multiple_effects_reported', 'operation_id': operation, 'evidence_event_ids': references, 'meaning': 'Supplied trace reports distinct effects for one logical operation; verify against authoritative target records.'}) if not effects: findings.append({'kind': 'outcome_unknown', 'operation_id': operation, 'evidence_event_ids': references, 'meaning': 'No effect evidence supplied. A timeout or missing record does not establish failure or permission to retry.'}) if len(attempts_seen) > 1: scoped_keys = {(r['target_id'], r['idempotency_key']) for r in rows} if any(key is None for _, key in scoped_keys) or len(scoped_keys) > 1: findings.append({'kind': 'retry_key_not_stable', 'operation_id': operation, 'evidence_event_ids': references, 'meaning': 'Multiple attempts use missing or different scoped keys; target idempotency semantics are unverified.'}) for (target, key), rows in sorted(keys.items()): if len({r['payload_sha256'] for r in rows}) > 1: findings.append({'kind': 'same_key_different_payload', 'target_id': target, 'idempotency_key': key, 'evidence_event_ids': sorted(r['event_id'] for r in rows), 'meaning': 'A scoped key is associated with different payload digests; do not assume semantically equivalent retries.'}) if len({r['operation_id'] for r in rows}) > 1: findings.append({'kind': 'key_shared_between_operations', 'target_id': target, 'idempotency_key': key, 'evidence_event_ids': sorted(r['event_id'] for r in rows), 'meaning': 'Distinct supplied logical operations share a scoped key; clarify intent before deduplication.'}) canonical = json.dumps(document, sort_keys=True, separators=(',', ':')).encode() return {'schema_version': 1, 'input_sha256': hashlib.sha256(canonical).hexdigest(), 'operations': summaries, 'findings': findings, 'retry_authorized': False, 'target_execution_verified': False, 'limitations': ['Supplied trace evidence only; no network, code execution, credentials or account access.', 'No guarantee of trace authenticity, completeness, idempotency retention, delivery or exactly-once execution.', 'Event order is not a clock or sequence; target identity and logical operation grouping are caller declarations.', 'Multiple observations of the same scoped effect count once; missing effect evidence remains unknown.']} if __name__ == '__main__': if len(sys.argv) != 2: raise SystemExit('Usage: python3 reconcile.py REDACTED_TRACE.json') with open(sys.argv[1], 'rb') as file: raw = file.read(102401) if len(raw) > 102400: raise SystemExit('Input exceeds 100 KiB') print(json.dumps(reconcile(json.loads(raw)), indent=2))