#!/usr/bin/env python3 """Original bounded fixtures for load, handover and recovery articles. Only local synthetic files are used. No service or production system is tested. """ from pathlib import Path from datetime import datetime, timezone from concurrent.futures import ThreadPoolExecutor import csv import hashlib import json import math import os import platform import shutil import sqlite3 import tempfile import time import zipfile import pypdf ROOT = Path(__file__).resolve().parents[1] ASSETS = ROOT / 'assets' def digest(file): return hashlib.sha256(file.read_bytes()).hexdigest() def save(file, value): file.parent.mkdir(parents=True, exist_ok=True) file.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n') sources = [('tables', 'APDF-0883', 'synthetic-tables.pdf', 3), ('invoices', 'APDF-0904', 'synthetic-invoice-corpus.pdf', 3), ('strokes', 'APDF-0925', 'synthetic-stroke-sample.pdf', 1)] def load_fixture(): target = ASSETS / 'APDF-1597' target.mkdir(exist_ok=True) inputs = [] for name, aid, filename, pages in sources: dst = target / 'inputs' / (name + '.pdf') dst.parent.mkdir(exist_ok=True) shutil.copy2(ASSETS / aid / filename, dst) shutil.copy2(ASSETS / aid / 'embedded-font-license.txt', target / ('font-licence-' + name + '.txt')) reader = pypdf.PdfReader(dst) extracted = '\n'.join(page.extract_text() or '' for page in reader.pages) assert len(reader.pages) == pages inputs.append({'class': name, 'path': 'inputs/' + dst.name, 'pages': pages, 'bytes': dst.stat().st_size, 'sha256': digest(dst), 'reference_text_sha256': hashlib.sha256(extracted.encode()).hexdigest(), 'source_article': aid, 'source_file': filename}) profile = {'kind': 'LOCAL_COMPONENT_EXPERIMENT', 'workers': 4, 'phases': [{'name': 'low', 'seconds': 10, 'jobs_per_second': 5}, {'name': 'higher', 'seconds': 10, 'jobs_per_second': 10}], 'mix': 'Round-robin of three original synthetic fixtures; one warm-up read each before recording', 'limits': ['No HTTP, authentication, database, remote storage or OCR', 'ThreadPoolExecutor queue is not a bounded admission controller', 'No saturation, cold-start, restart, memory-limit or tenant-isolation experiment', 'Host is shared; results are not an ArkePDF capacity statement'], 'inputs': inputs} save(target / 'load-profile.json', profile) start = time.perf_counter() futures = [] def job(number, phase, item, scheduled, submitted): began = time.perf_counter() error = None try: reader = pypdf.PdfReader(target / item['path']) text = '\n'.join(page.extract_text() or '' for page in reader.pages) valid = len(reader.pages) == item['pages'] and hashlib.sha256(text.encode()).hexdigest() == item['reference_text_sha256'] if not valid: error = 'REFERENCE_OUTPUT_MISMATCH' except Exception as exc: valid = False error = type(exc).__name__ ended = time.perf_counter() return {'job_id': f'JOB-{number:03d}', 'phase': phase, 'class': item['class'], 'scheduled_ms': round((scheduled-start)*1000, 6), 'submitted_ms': round((submitted-start)*1000, 6), 'worker_started_ms': round((began-start)*1000, 6), 'completed_ms': round((ended-start)*1000, 6), 'scheduler_lag_ms': round((submitted-scheduled)*1000, 6), 'queue_ms': round((began-submitted)*1000, 6), 'processing_ms': round((ended-began)*1000, 6), 'completion_from_schedule_ms': round((ended-scheduled)*1000, 6), 'output_matches_warm_reference': valid, 'error': error} with ThreadPoolExecutor(max_workers=4) as pool: number = 0 offset = 0 for phase in profile['phases']: for index in range(phase['seconds'] * phase['jobs_per_second']): number += 1 scheduled = start + offset + index / phase['jobs_per_second'] delay = scheduled - time.perf_counter() if delay > 0: time.sleep(delay) submitted = time.perf_counter() futures.append(pool.submit(job, number, phase['name'], inputs[(number-1) % 3], scheduled, submitted)) offset += phase['seconds'] rows = [future.result() for future in futures] delay = start + offset - time.perf_counter() if delay > 0: time.sleep(delay) def percentile(values, pct): return sorted(values)[math.ceil(pct*len(values))-1] phases = [] for phase in profile['phases']: cohort = [row for row in rows if row['phase'] == phase['name']] phases.append({'phase': phase['name'], 'scheduled_jobs': len(cohort), 'completed_jobs': len(cohort), 'matching_outputs': sum(r['output_matches_warm_reference'] for r in cohort), 'p50_completion_from_schedule_ms': percentile([r['completion_from_schedule_ms'] for r in cohort], .50), 'p95_completion_from_schedule_ms': percentile([r['completion_from_schedule_ms'] for r in cohort], .95), 'p95_queue_ms': percentile([r['queue_ms'] for r in cohort], .95), 'max_scheduler_lag_ms': max(r['scheduler_lag_ms'] for r in cohort)}) with (target / 'raw-results.csv').open('w', newline='') as handle: writer = csv.DictWriter(handle, fieldnames=list(rows[0])); writer.writeheader(); writer.writerows(rows) save(target / 'results.json', {'observed_at_utc': datetime.now(timezone.utc).isoformat(), 'environment': {'python': platform.python_version(), 'pypdf': pypdf.__version__, 'logical_cpus_visible': os.cpu_count(), 'host_scope': 'Shared task container; no reserved hardware'}, 'scheduled': 150, 'submitted': len(rows), 'terminal': len(rows), 'completed_by_20_second_cutoff': sum(r['completed_ms'] <= 20000 for r in rows), 'errors': sum(r['error'] is not None for r in rows), 'phases': phases, 'percentile_definition': 'Nearest rank: ordered value at ceil(p*N), one-based', 'latency_definition': 'Planned arrival to local component completion; includes scheduler lag and executor queue', 'reference_limit': 'Warm-up output consistency, not independent semantic correctness', 'capacity_claim': None, 'raw_results_sha256': digest(target/'raw-results.csv')}) def handover_fixture(): target = ASSETS / 'APDF-1639' source = target / 'source' source.mkdir(parents=True, exist_ok=True) records = [] items = sources + [('redacted', 'APDF-0568', 'release-cleaned.pdf', 3)] for index, (name, aid, filename, pages) in enumerate(items, 1): dst = source / (name + '.pdf') shutil.copy2(ASSETS / aid / filename, dst) records.append({'document_id': f'DOC-{index:03d}', 'version': 'synthetic-v1', 'path': 'source/' + dst.name, 'bytes': dst.stat().st_size, 'sha256': digest(dst), 'expected_pages': pages, 'source_article': aid, 'source_filename': filename, 'destination_path': 'documents/' + dst.name, 'retention_rule': None, 'access_rule': 'PROPOSED_REVIEW_TEAM_ONLY'}) manifest = {'scope': 'Four original synthetic PDF fixtures; demonstration transfer manifest, not BagIt certification', 'records': records, 'source_owner_signature': None, 'receiving_owner_signature': None, 'handover_approved': False, 'note': 'Identity, permission and retention decisions require actual archive owners.'} save(target / 'transfer-manifest.json', manifest) def inspect(folder): expected = {Path(r['destination_path']).name: r for r in records} actual = {f.name: f for f in folder.glob('*') if f.is_file()} return {'missing': sorted(expected.keys()-actual.keys()), 'unexpected': sorted(actual.keys()-expected.keys()), 'hash_mismatches': sorted(name for name in expected.keys() & actual.keys() if digest(actual[name]) != expected[name]['sha256']), 'matching': sum(digest(actual[name]) == expected[name]['sha256'] for name in expected.keys() & actual.keys())} cases = {} with tempfile.TemporaryDirectory(prefix='arkepdf-transfer-') as tmp: dst = Path(tmp)/'destination' for case in ['baseline', 'missing', 'altered', 'unexpected']: if dst.exists(): shutil.rmtree(dst) shutil.copytree(source, dst) if case == 'missing': (dst/'invoices.pdf').unlink() if case == 'altered': with (dst/'tables.pdf').open('ab') as handle: handle.write(b'\n% Synthetic altered-byte control\n') if case == 'unexpected': shutil.copy2(dst/'strokes.pdf', dst/'extra.pdf') cases[case] = inspect(dst) assert cases['baseline'] == {'missing': [], 'unexpected': [], 'hash_mismatches': [], 'matching': 4} assert cases['missing']['missing'] == ['invoices.pdf'] assert cases['altered']['hash_mismatches'] == ['tables.pdf'] assert cases['unexpected']['unexpected'] == ['extra.pdf'] save(target/'results.json', {'observed_at_utc': datetime.now(timezone.utc).isoformat(), 'cases': cases, 'business_retrieval_test': 'NOT_RUN', 'real_permissions_test': 'NOT_RUN', 'independent_owner_signoff': 'PENDING', 'source_files_unchanged': True}) def recovery_fixture(): target = ASSETS/'APDF-1660'; target.mkdir(exist_ok=True) archive = json.loads((ASSETS/'APDF-1639/transfer-manifest.json').read_text()) with tempfile.TemporaryDirectory(prefix='arkepdf-recovery-') as tmp: root = Path(tmp); source = root/'snapshot'; source.mkdir() documents = source/'documents'; documents.mkdir() for record in archive['records']: shutil.copy2(ASSETS/'APDF-1639'/record['path'], documents/Path(record['path']).name) connection = sqlite3.connect(source/'catalogue.sqlite') connection.execute('CREATE TABLE documents (id TEXT PRIMARY KEY, path TEXT, sha256 TEXT, pages INTEGER)') connection.executemany('INSERT INTO documents VALUES (?,?,?,?)', [(r['document_id'],r['destination_path'],r['sha256'],r['expected_pages']) for r in archive['records']]) connection.commit(); connection.close() save(source/'config.json', {'storage_root': 'documents', 'schema_version': 1, 'synthetic_last_committed_event': '2026-10-31T09:40:00Z', 'scope': 'Local file catalogue demonstration only; no production credentials or access-control system'}) files = [{'path': f.relative_to(source).as_posix(), 'bytes': f.stat().st_size, 'sha256': digest(f)} for f in sorted(source.rglob('*')) if f.is_file()] save(target/'backup-manifest.json', {'files': files, 'snapshot_type': 'Closed local SQLite catalogue and original synthetic PDFs', 'simulated_incident_at': '2026-10-31T10:00:00Z', 'modelled_recovery_point_gap_minutes': 20, 'RPO_target_minutes': 15, 'RPO_target_status': 'MODEL_FAIL', 'RTO_target': None, 'qualification': 'Scenario timestamps are fictional and unrelated to the actual experiment clock; no live business RPO measured.'}) bundle = target/'synthetic-backup.zip' with zipfile.ZipFile(bundle,'w',zipfile.ZIP_DEFLATED) as z: for record in files: z.write(source/record['path'],record['path']) results = [] for case in ['baseline', 'missing_catalogue', 'altered_document']: dst = root/case began = time.perf_counter() with zipfile.ZipFile(bundle) as z: z.extractall(dst) restored = time.perf_counter() if case == 'missing_catalogue': (dst/'catalogue.sqlite').unlink() if case == 'altered_document': with (dst/'documents/tables.pdf').open('ab') as handle: handle.write(b'\n% Synthetic recovery fault\n') missing = [r['path'] for r in files if not (dst/r['path']).is_file()] mismatched = [r['path'] for r in files if (dst/r['path']).is_file() and digest(dst/r['path']) != r['sha256']] retrieved = False if not missing and not mismatched: con = sqlite3.connect(f'file:{dst / "catalogue.sqlite"}?mode=ro', uri=True) doc_path, pages = con.execute('SELECT path,pages FROM documents WHERE id=?',('DOC-002',)).fetchone(); con.close() pdf = pypdf.PdfReader(dst/doc_path) retrieved = len(pdf.pages) == pages and 'Document ID' in (pdf.pages[0].extract_text() or '') ended = time.perf_counter() results.append({'case': case, 'restore_seconds': restored-began, 'verification_seconds': ended-restored, 'total_seconds': ended-began, 'missing': missing, 'hash_mismatches': mismatched, 'local_catalogue_lookup_and_pdf_parse': retrieved, 'result': 'PASS_BOUNDED_LOCAL_CHECK' if not missing and not mismatched and retrieved else 'BLOCKED'}) assert results[0]['result'] == 'PASS_BOUNDED_LOCAL_CHECK' assert results[1]['missing'] == ['catalogue.sqlite'] assert results[2]['hash_mismatches'] == ['documents/tables.pdf'] save(target/'results.json', {'observed_at_utc':datetime.now(timezone.utc).isoformat(), 'python':platform.python_version(),'sqlite':sqlite3.sqlite_version,'pypdf':pypdf.__version__, 'backup_sha256':digest(bundle),'cases':results, 'platform_RTO_measured':False,'platform_RPO_measured':False, 'excluded':['Detection and declaration','Infrastructure provisioning','Keys and identity providers','Permissions and network controls','Queue reconciliation','Business-owner acceptance and failback']}) if __name__ == '__main__': load_fixture() handover_fixture() recovery_fixture() print(json.dumps({'created_for':['APDF-1597','APDF-1639','APDF-1660'], 'actual_scope':'Bounded local synthetic component experiments only'}))