#!/usr/bin/env python3
"""Module 25. Private files, SQLite and loopback HTTP; Python 3.12.12 standard library.
All sizes and fault schedules are chosen teaching inputs. No external services.
"""
import argparse, concurrent.futures, contextlib, hashlib, http.client, json, os, re
import sqlite3, subprocess, sys, tempfile, threading
from collections import Counter
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

BLOCK = 4
MAX_FILE = 64
BASE = b'AAAABBBBCCCCAAAA'
EDIT = b'AAAABBBBddddAAAA'
TOKENS = {'fixture-laptop':'laptop', 'fixture-phone':'phone', 'fixture-eve':'eve'}
REQUEST_COUNTS = Counter()
REQUEST_LOCK = threading.Lock()

def wire(value):
    return json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False, ensure_ascii=False).encode('utf-8')

def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError('duplicate JSON field')
        result[key] = value
    return result

def digest(data):
    return hashlib.sha256(data).hexdigest()

class Refusal(Exception):
    def __init__(self, status, reason):
        self.status, self.reason = status, reason
        super().__init__(reason)

def require(okay, reason='invalid_input', status=400):
    if not okay:
        raise Refusal(status, reason)

def integer(value, low, high):
    return type(value) is int and low <= value <= high

def text(value, pattern):
    return type(value) is str and re.fullmatch(pattern, value) is not None

def shape(body, fields):
    require(type(body) is dict and set(body) == set(fields))

def blocks(data):
    require(type(data) is bytes and len(data) <= MAX_FILE)
    return [data[i:i + BLOCK] for i in range(0, len(data), BLOCK)]

def manifest(data):
    return {'blocks':[{'digest':digest(b), 'length':len(b)} for b in blocks(data)],
            'digest':digest(data), 'size':len(data)}

def validate_manifest(body):
    require(type(body['blocks']) is list and len(body['blocks']) <= MAX_FILE // BLOCK)
    require(integer(body['size'], 0, MAX_FILE) and text(body['digest'], '[0-9a-f]{64}'))
    total = 0
    for i, ref in enumerate(body['blocks']):
        shape(ref, ['digest', 'length'])
        require(text(ref['digest'], '[0-9a-f]{64}') and integer(ref['length'], 1, BLOCK))
        require(i == len(body['blocks']) - 1 or ref['length'] == BLOCK)
        total += ref['length']
    require(total == body['size'])

def sync_dir(directory):
    fd = os.open(directory, os.O_RDONLY)
    try:
        os.fsync(fd)
    finally:
        os.close(fd)

def replace_file(path, data):
    temporary = path.with_suffix(path.suffix + '.pending')
    with temporary.open('wb') as target:
        target.write(data)
        target.flush()
        os.fsync(target.fileno())
    os.replace(temporary, path)
    sync_dir(path.parent)

class Store:
    """One authority path; SQLite serializes publication, authorization, upload and GC."""
    def __init__(self, root):
        self.root = Path(root)
        self.root.mkdir(exist_ok=True)
        self.blobs = self.root / 'blobs'
        self.blobs.mkdir(exist_ok=True)
        sync_dir(self.root)
        self.path = self.root / 'source.sqlite'
        self.available = True
        self.stop_before_commit = False
        with self.tx() as db:
            db.executescript('''
              CREATE TABLE IF NOT EXISTS devices(device TEXT PRIMARY KEY NOT NULL,
                namespace TEXT NOT NULL, active INTEGER NOT NULL CHECK(active IN (0,1)));
              INSERT OR IGNORE INTO devices VALUES('laptop','ada',1),('phone','ada',1),('eve','eve',1);
              CREATE TABLE IF NOT EXISTS revisions(revision INTEGER PRIMARY KEY AUTOINCREMENT,
                path TEXT NOT NULL, deleted INTEGER NOT NULL CHECK(deleted IN (0,1)),
                blocks TEXT NOT NULL, digest TEXT NOT NULL, size INTEGER NOT NULL CHECK(size>=0));
              CREATE TABLE IF NOT EXISTS paths(path TEXT PRIMARY KEY NOT NULL,
                revision INTEGER NOT NULL REFERENCES revisions(revision));
              CREATE TABLE IF NOT EXISTS receipts(device TEXT NOT NULL, operation TEXT NOT NULL,
                payload TEXT NOT NULL, result TEXT NOT NULL, PRIMARY KEY(device,operation));
            ''')
        sync_dir(self.root)

    @contextlib.contextmanager
    def tx(self):
        require(self.available, 'source_unavailable', 503)
        db = sqlite3.connect(self.path, timeout=5)
        db.row_factory = sqlite3.Row
        db.execute('PRAGMA foreign_keys=ON')
        db.execute('PRAGMA synchronous=EXTRA')
        try:
            db.execute('BEGIN IMMEDIATE')
            yield db
            db.commit()
        except BaseException:
            db.rollback()
            raise
        finally:
            db.close()

    def authorize(self, db, device):
        row = db.execute('SELECT namespace,active FROM devices WHERE device=?', (device,)).fetchone()
        require(row is not None and row['namespace'] == 'ada' and row['active'] == 1,
                'forbidden', 403)

    def blob_path(self, key):
        require(text(key, '[0-9a-f]{64}'))
        return self.blobs / (key + '.block')

    def verified(self, ref, synchronize=False):
        path = self.blob_path(ref['digest'])
        require(path.is_file(), 'missing_block', 409)
        with path.open('rb') as source:
            data = source.read(BLOCK + 1)
            require(len(data) == ref['length'] and digest(data) == ref['digest'], 'corrupt_block', 503)
            if synchronize:
                # Identical existing bytes do not prove that a previous fsync succeeded.
                os.fsync(source.fileno())
        if synchronize:
            sync_dir(self.blobs)
        return data

    def assemble(self, body, synchronize=False):
        data = b''.join(self.verified(ref, synchronize) for ref in body['blocks'])
        require(len(data) == body['size'] and digest(data) == body['digest'], 'file_integrity', 409)
        return data

    @staticmethod
    def record(row):
        return {'revision':row['revision'], 'path':row['path'], 'deleted':bool(row['deleted']),
                'blocks':json.loads(row['blocks']), 'digest':row['digest'], 'size':row['size']}

    def current(self, db, path):
        return db.execute('SELECT r.* FROM revisions r JOIN paths p USING(revision) WHERE p.path=?',
                          (path,)).fetchone()

    def accepted_head(self, db):
        # This fixture only appends automatic ids and rolls back every failed insert.
        # sqlite_sequence survives deletion of a retained row; MAX(revision) does not.
        row = db.execute("SELECT seq FROM sqlite_sequence WHERE name='revisions'").fetchone()
        head = row[0] if row is not None else 0
        require(integer(head, 0, 64), 'history_gap', 409)
        positions = [r[0] for r in db.execute('SELECT revision FROM revisions ORDER BY revision')]
        require(positions == list(range(1, head + 1)), 'history_gap', 409)
        return head

    def append(self, db, path, body, deleted=False):
        revision = db.execute('INSERT INTO revisions(path,deleted,blocks,digest,size) VALUES(?,?,?,?,?)',
                              (path, int(deleted), wire(body['blocks']).decode(), body['digest'], body['size'])).lastrowid
        db.execute('INSERT INTO paths VALUES(?,?) ON CONFLICT(path) DO UPDATE SET revision=excluded.revision',
                   (path, revision))
        return revision

    def dispatch(self, device, route, body):
        require(type(body) is dict)
        with self.tx() as db:
            self.authorize(db, device)
            head = self.accepted_head(db)
            if route == '/blocks/has':
                shape(body, ['blocks'])
                require(type(body['blocks']) is list and len(body['blocks']) <= 16)
                missing = []
                for ref in body['blocks']:
                    shape(ref, ['digest', 'length'])
                    require(text(ref['digest'], '[0-9a-f]{64}') and integer(ref['length'], 1, BLOCK))
                    if not self.blob_path(ref['digest']).exists():
                        missing.append(ref['digest'])
                    else:
                        self.verified(ref)
                return 200, {'missing':sorted(set(missing))}
            if route == '/blocks/put':
                shape(body, ['digest', 'hex'])
                require(text(body['digest'], '[0-9a-f]{64}') and text(body['hex'], '(?:[0-9a-f]{2}){1,4}'))
                data = bytes.fromhex(body['hex'])
                require(digest(data) == body['digest'], 'digest_mismatch')
                path = self.blob_path(body['digest'])
                existed = path.exists()
                if existed:
                    require(path.read_bytes() == data, 'collision_or_corruption', 409)
                else:
                    require(len(list(self.blobs.glob('*.block'))) < 256, 'blob_capacity', 413)
                    replace_file(path, data)
                self.verified({'digest':body['digest'], 'length':len(data)}, True)
                return 200 if existed else 201, {'bytes':len(data), 'reused':existed}
            if route in ('/commit', '/delete', '/rename'):
                fields = ['operation', 'path', 'base']
                fields += ['blocks','digest','size'] if route == '/commit' else ['destination'] if route == '/rename' else []
                shape(body, fields)
                require(text(body['operation'], '[a-z0-9-]{1,40}') and text(body['path'], '[a-z0-9][a-z0-9.-]{0,31}'))
                require(body['path'] not in ('.','..') and integer(body['base'], 0, 1000000))
                if route == '/rename':
                    require(text(body['destination'], '[a-z0-9][a-z0-9.-]{0,31}') and body['destination'] != body['path'])
                if route == '/commit':
                    validate_manifest(body)
                payload = wire([route, body]).decode()
                receipt = db.execute('SELECT payload,result FROM receipts WHERE device=? AND operation=?',
                                     (device, body['operation'])).fetchone()
                if receipt is not None:
                    require(receipt['payload'] == payload, 'operation_conflict', 409)
                    return 200, json.loads(receipt['result'])
                require(head + (2 if route == '/rename' else 1) <= 64, 'revision_capacity', 503)
                old = self.current(db, body['path'])
                current = old['revision'] if old is not None else 0
                require(current == body['base'], 'base_conflict:' + str(current), 409)
                require(old is None or not old['deleted'], 'path_tombstoned', 409)
                if route == '/commit':
                    self.assemble(body, True)
                    result = {'revision':self.append(db, body['path'], body)}
                else:
                    require(old is not None, 'missing_file', 404)
                    previous = self.record(old)
                    if route == '/rename':
                        require(self.current(db, body['destination']) is None, 'destination_used', 409)
                        self.assemble(previous, True)
                    removed = self.append(db, body['path'], previous, True)
                    result = {'revision':removed}
                    if route == '/rename':
                        result = {'removed':removed, 'revision':self.append(db, body['destination'], previous)}
                db.execute('INSERT INTO receipts VALUES(?,?,?,?)',
                           (device, body['operation'], payload, wire(result).decode()))
                if self.stop_before_commit:
                    os._exit(23)
                return 201, result
            if route == '/list':
                shape(body, [])
                rows = db.execute('SELECT r.* FROM revisions r JOIN paths p USING(revision) ORDER BY path').fetchall()
                return 200, {'head':head,
                             'files':[self.record(r) for r in rows]}
            if route == '/changes':
                shape(body, ['after'])
                require(integer(body['after'], 0, 1000000))
                require(body['after'] <= head, 'future_cursor', 409)
                rows = db.execute('SELECT * FROM revisions WHERE revision>? ORDER BY revision', (body['after'],)).fetchall()
                require([r['revision'] for r in rows] == list(range(body['after'] + 1, head + 1)), 'history_gap', 409)
                return 200, {'head':head, 'changes':[self.record(r) for r in rows]}
            if route == '/download':
                shape(body, ['path','revision'])
                require(text(body['path'], '[a-z0-9][a-z0-9.-]{0,31}') and integer(body['revision'], 1, 1000000))
                current = self.current(db, body['path'])
                require(current is not None and not current['deleted'], 'not_found', 404)
                row = db.execute('SELECT * FROM revisions WHERE path=? AND revision=?', (body['path'],body['revision'])).fetchone()
                require(row is not None and not row['deleted'], 'not_found', 404)
                record = self.record(row)
                data = self.assemble(record)
                return 200, {'hex':data.hex(), 'digest':digest(data), 'revision':row['revision']}
            raise Refusal(404, 'unknown_route')

    def collect_orphans(self):
        # Private administrative operation, serialized against upload/publication.
        with self.tx() as db:
            self.accepted_head(db)
            keep = {ref['digest'] for row in db.execute('SELECT blocks FROM revisions') for ref in json.loads(row[0])}
            removed = [p for p in self.blobs.glob('*.block') if p.stem not in keep]
            size = sum(p.stat().st_size for p in removed)
            for path in removed:
                path.unlink()
            sync_dir(self.blobs)
            return len(removed), size

class Handler(BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'
    def log_message(self, *_):
        pass
    def do_POST(self):
        with REQUEST_LOCK:
            REQUEST_COUNTS[self.path if self.path in ('/blocks/has','/blocks/put','/commit','/rename','/delete','/list','/changes','/download') else 'unknown'] += 1
        self.connection.settimeout(2)
        self.close_connection = True
        try:
            lengths = self.headers.get_all('Content-Length') or []
            require(self.headers.get_all('Transfer-Encoding') is None, 'unsupported_transfer')
            require(len(lengths) == 1 and text(lengths[0], '[0-9]+'), 'length_required')
            normalized = lengths[0].lstrip('0') or '0'
            require(len(normalized) <= 4 and int(normalized) <= 4096, 'request_cap', 413)
            auth = self.headers.get_all('Authorization') or []
            require(len(auth) == 1 and auth[0].startswith('Bearer ') and auth[0][7:] in TOKENS, 'unauthorized', 401)
            length = int(normalized)
            data = self.rfile.read(length)
            require(len(data) == length, 'short_body')
            body = json.loads(data.decode('utf-8'), object_pairs_hook=unique_object,
                              parse_constant=lambda _: (_ for _ in ()).throw(ValueError()))
            # Reject unpaired surrogates even in irrelevant/rejected fields.
            wire(body)
            status, response = self.server.store.dispatch(TOKENS[auth[0][7:]], self.path, body)
            if self.server.drop_reply and self.path == '/commit' and status == 201:
                self.server.drop_reply = False
                self.connection.close()
                return
        except Refusal as error:
            status, response = error.status, {'error':error.reason}
        except (ValueError, UnicodeError, TypeError):
            status, response = 400, {'error':'invalid_json'}
        except (OSError, sqlite3.Error):
            status, response = 503, {'error':'storage_unavailable'}
        payload = wire(response)
        try:
            self.send_response(status)
            self.send_header('Content-Length', str(len(payload)))
            self.send_header('Content-Type','application/json')
            self.send_header('Cache-Control','private, no-store')
            self.send_header('Connection','close')
            self.end_headers()
            self.wfile.write(payload)
            self.wfile.flush()
        except OSError:
            pass

@contextlib.contextmanager
def endpoint(store):
    server = ThreadingHTTPServer(('127.0.0.1',0), Handler)
    server.store, server.drop_reply = store, False
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        yield server
    finally:
        server.shutdown()
        server.server_close()
        thread.join()

def call(server, route, device, body):
    connection = http.client.HTTPConnection('127.0.0.1',server.server_port,timeout=5)
    try:
        connection.request('POST', route, wire(body), {'Authorization':'Bearer fixture-' + device, 'Content-Type':'application/json'})
        response = connection.getresponse()
        lengths = response.headers.get_all('Content-Length') or []
        require(response.headers.get_all('Transfer-Encoding') is None and len(lengths) == 1 and text(lengths[0], '[0-9]+'), 'response_framing', 502)
        normalized = lengths[0].lstrip('0') or '0'
        require(len(normalized) <= 7 and int(normalized) <= 1048576, 'response_cap', 502)
        length = int(normalized)
        data = response.read(length)
        require(len(data) == length, 'short_response', 502)
        body = json.loads(data)
        wire(body)
        return response.status, body
    finally:
        connection.close()

def upload(server, device, data):
    refs = manifest(data)['blocks']
    status, result = call(server, '/blocks/has', device, {'blocks':refs})
    require(status == 200, 'negotiation_failed', status)
    missing = set(result['missing'])
    sent = 0
    for chunk in dict.fromkeys(blocks(data)):
        if digest(chunk) in missing:
            status, _ = call(server, '/blocks/put', device, {'digest':digest(chunk),'hex':chunk.hex()})
            require(status in (200,201), 'upload_failed', status)
            sent += len(chunk)
    return sent

def commit_body(operation, data, base=0, path='notes.txt'):
    return {'operation':operation,'path':path,'base':base,**manifest(data)}

class Replica:
    """Local files plus a durable known-revision record; preserves a divergent local edit."""
    def __init__(self, root, device):
        self.root, self.device = Path(root), device
        self.root.mkdir(exist_ok=True)
        self.state = self.root / 'known.json'
        self.known = json.loads(self.state.read_bytes()) if self.state.exists() else {}
        self.operations_path = self.root / 'operations.json'
        self.operations = json.loads(self.operations_path.read_bytes()) if self.operations_path.exists() else {}
    def edit(self, data):
        replace_file(self.root / 'notes.txt', data)
    def pull(self, server):
        status, listing = call(server, '/list', self.device, {})
        require(status == 200, 'listing_failed', status)
        for row in listing['files']:
            if row['path'] != 'notes.txt':
                continue
            target = self.root / 'notes.txt'
            if target.exists() and (not self.known or digest(target.read_bytes()) != self.known['digest']):
                raise Refusal(409, 'local_edit_preserved')
            require(not row['deleted'], 'remote_deleted', 409)
            status, result = call(server, '/download', self.device, {'path':'notes.txt','revision':row['revision']})
            require(status == 200, 'download_failed', status)
            data = bytes.fromhex(result['hex'])
            require(digest(data) == row['digest'] and len(data) == row['size'], 'download_corrupt', 503)
            replace_file(target, data)
            self.known = {'revision':row['revision'],'digest':row['digest']}
            replace_file(self.state, wire(self.known))
    def push(self, server, operation):
        data = (self.root / 'notes.txt').read_bytes()
        body = self.operations.get(operation)
        if body is None:
            body = commit_body(operation,data,self.known.get('revision',0))
            self.operations[operation] = body
        require(body['digest'] == digest(data) and body['size'] == len(data), 'local_operation_changed', 409)
        # A previous replacement or directory fsync may have failed after memory changed.
        # Repeat durable publication before any send, including retries on this instance.
        replace_file(self.operations_path, wire(self.operations))
        sent = upload(server, self.device, data)
        response = call(server, '/commit', self.device, body)
        if response[0] in (200,201):
            self.known = {'revision':response[1]['revision'],'digest':digest(data)}
            replace_file(self.state, wire(self.known))
        return response, sent

def chunking():
    for name, data in [('empty',b''),('exact',b'AAAABBBB'),('short',b'AAAAB'),('repeated',BASE),('overwrite',EDIT),('front',b'x'+BASE)]:
        chunks = blocks(data)
        old = set(blocks(BASE))
        reused = sum(len(c) for c in chunks if c in old)
        transferred = sum(len(c) for c in set(chunks) - old)
        require(b''.join(chunks) == data, 'reconstruction_mismatch', 500)
        print(name + ': bytes=' + str(len(data)) + '; blocks=' + str(len(chunks))
              + '; reused positions bytes=' + str(reused) + '; unique missing bytes=' + str(transferred))
    print('sha256(AAAA)=' + digest(b'AAAA'))
    print('SHA-256 digest bytes=' + str(len(hashlib.sha256(BASE).digest())) + '; hex characters=' + str(len(digest(BASE))))

def replicas():
    with tempfile.TemporaryDirectory(prefix='m25-replicas-') as directory:
        root = Path(directory)
        store = Store(root / 'authority')
        laptop, phone = Replica(root/'laptop','laptop'), Replica(root/'phone','phone')
        with endpoint(store) as server:
            laptop.edit(BASE)
            response, sent = laptop.push(server,'initial')
            phone.pull(server)
            print('initial commit=' + str(response[0]) + '; revision=1; uploaded unique bytes=' + str(sent))
            print('two local files equal=' + str((root/'laptop/notes.txt').read_bytes() == (root/'phone/notes.txt').read_bytes()))
            phone.edit(EDIT)
            response, sent = phone.push(server,'offline-edit')
            print('offline phone reconnect=' + str(response[0]) + '; revision=2; uploaded bytes=' + str(sent))
            retry = call(server,'/commit','phone',commit_body('offline-edit',EDIT,1))
            print('same operation retry=' + str(retry[0]) + '; same revision=' + str(retry[1]['revision']))
            laptop.edit(b'AAAABBBBzzzzAAAA')
            response, sent = laptop.push(server,'concurrent')
            print('stale laptop=' + str(response[0]) + ' ' + response[1]['error'] + '; local edit retained=' + str((root/'laptop/notes.txt').read_bytes().endswith(b'zzzzAAAA')))
            for name, data in [('unchanged',BASE),('overwrite',EDIT),('front',b'x'+BASE)]:
                old=set(blocks(BASE));parts=blocks(data)
                print(name + ': full=' + str(len(data)) + '; metadata-first whole-file=' + str(0 if digest(data)==digest(BASE) else len(data)) + '; block payload=' + str(sum(len(c) for c in set(parts)-old)) + '; manifest JSON=' + str(len(wire(manifest(data)))))

def publication():
    with tempfile.TemporaryDirectory(prefix='m25-publication-') as directory:
        store = Store(directory)
        with endpoint(store) as server:
            body = commit_body('publish',BASE)
            print('before blocks=' + str(call(server,'/commit','laptop',body)[0]))
            print('uploaded unique bytes=' + str(upload(server,'laptop',BASE)) + '; visible paths before commit=' + str(len(call(server,'/list','laptop',{})[1]['files'])))
            status, result = call(server,'/commit','laptop',body)
            print('published=' + str(status) + '; revision=' + str(result['revision']) + '; ordered references=' + str(len(body['blocks'])))
            received=bytes.fromhex(call(server,'/download','phone',{'path':'notes.txt','revision':1})[1]['hex'])
            print('reconstructed bytes=' + str(len(received)) + '; identical=' + str(received==BASE))
            print('duplicate commit=' + str(call(server,'/commit','laptop',body)[0]))
            bad=store.blob_path(digest(b'BBBB'));bad.write_bytes(b'xxxx')
            print('corrupt referenced block=' + str(call(server,'/commit','phone',commit_body('replace',BASE,1))[0]))
            bad.write_bytes(b'BBBB')
            print('restored-byte retry=' + str(call(server,'/commit','phone',commit_body('replace',BASE,1))[0]))
            print('stale base=' + str(call(server,'/commit','laptop',commit_body('stale',BASE,1))[0]))
        reopened=Store(directory)
        with reopened.tx() as db:
            rows=db.execute('SELECT blocks FROM revisions ORDER BY revision').fetchall()
            print('reopened revisions=' + str(len(rows)) + '; first ordered digests=' + str([r['digest'][:8] for r in json.loads(rows[0][0])]))

def service():
    REQUEST_COUNTS.clear()
    with tempfile.TemporaryDirectory(prefix='m25-service-') as directory:
        root=Path(directory);store=Store(root/'authority')
        laptop,phone=Replica(root/'laptop','laptop'),Replica(root/'phone','phone')
        laptop.edit(BASE)
        with endpoint(store) as server:
            initial, sent = laptop.push(server,'initial')
            print('initial payload=' + str(sent) + '; commit=' + str(initial[0]))
            laptop.pull(server);phone.pull(server)
            phone.edit(EDIT);laptop.edit(b'AAAABBBBzzzzAAAA')
            upload(server,'phone',(root/'phone/notes.txt').read_bytes());upload(server,'laptop',(root/'laptop/notes.txt').read_bytes())
            barrier=threading.Barrier(2)
            def race(device):
                barrier.wait()
                data=(root/device/'notes.txt').read_bytes()
                return device,call(server,'/commit',device,commit_body('race',data,1))
            with concurrent.futures.ThreadPoolExecutor() as pool:
                results=list(pool.map(race,['phone','laptop']))
            winner,result=next(row for row in results if row[1][0]==201)
            print('same-base race statuses=' + str(sorted(r[1][0] for r in results)) + '; committed revision=' + str(result[1]['revision']))
            print('missing block=' + str(call(server,'/commit','phone',commit_body('missing',b'NNNN',2))[0]))
            print('duplicate upload=' + str(call(server,'/blocks/put','phone',{'digest':digest(b'AAAA'),'hex':b'AAAA'.hex()})[0]))
        child=subprocess.run([sys.executable,__file__,'interrupt',str(store.root)],capture_output=True)
        print('publication child exit=' + str(child.returncode))
        require(child.returncode==23,'wrong_child_exit',500)
        store=Store(store.root)
        with endpoint(store) as server:
            print('reopened head=' + str(call(server,'/list','phone',{})[1]['head']))
            upload(server,'phone',BASE)
            body=commit_body('lost-reply',BASE,2)
            server.drop_reply=True
            try:call(server,'/commit','phone',body)
            except http.client.RemoteDisconnected:print('real TCP reply lost after commit')
            print('recovered receipt=' + str(call(server,'/commit','phone',body)[0]) + '; revision=3')
            print('rename=' + str(call(server,'/rename','phone',{'operation':'rename','path':'notes.txt','base':3,'destination':'archive.txt'})[1]))
            print('offline old-path edit=' + str(call(server,'/commit','laptop',commit_body('late',BASE,2))[0]))
            print('delete renamed=' + str(call(server,'/delete','phone',{'operation':'delete','path':'archive.txt','base':5})[1]))
            print('tombstone base retry=' + str(call(server,'/commit','phone',commit_body('resurrect',BASE,6,'archive.txt'))[0]))
            changes=call(server,'/changes','laptop',{'after':2})[1]
            print('offline replay revisions=' + str([r['revision'] for r in changes['changes']]) + '; tombstones=' + str(sum(r['deleted'] for r in changes['changes'])))
            print('deleted path download=' + str(call(server,'/download','phone',{'path':'archive.txt','revision':5})[0]) + '; other namespace=' + str(call(server,'/list','eve',{})[0]))
            upload(server,'phone',b'!!!!')
            removed,size=store.collect_orphans()
            print('orphan GC blocks=' + str(removed) + '; bytes=' + str(size))
            with store.tx() as db:
                records=[store.record(r) for r in db.execute('SELECT * FROM revisions ORDER BY revision')]
                print('retained revisions=' + str(len(records)) + '; references=' + str(sum(len(r['blocks']) for r in records)) + '; blob files=' + str(len(list(store.blobs.glob('*.block')))) + '; revision JSON bytes=' + str(len(wire(records))))
                for record in records:
                    store.assemble(record)
                db.execute("UPDATE devices SET active=0 WHERE device='phone'")
            print('revoked device=' + str(call(server,'/list','phone',{})[0]))
            store.available=False
            print('source unavailable=' + str(call(server,'/list','laptop',{})[0]))
            print('actual HTTP attempts=' + str(sum(REQUEST_COUNTS.values())) + '; by route=' + wire(dict(sorted(REQUEST_COUNTS.items()))).decode())

if __name__ == '__main__':
    require(sys.version_info[:3] == (3,12,12), 'use_python_3.12.12')
    parser=argparse.ArgumentParser();parser.add_argument('mode',choices=['replicas','chunking','publication','service','interrupt']);parser.add_argument('root',nargs='?');args=parser.parse_args()
    if args.mode == 'interrupt':
        store=Store(args.root);store.stop_before_commit=True
        store.dispatch('phone','/commit',commit_body('interrupted',BASE,2))
    else:
        globals()[args.mode]()
