File size: 33,726 Bytes
bbff072
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
#!/usr/bin/env python3
"""NYARION V fixed-pool immutable page-tree research image engine.

Regular POSIX files only. All logical values are held in RAM. Capsule commits
use one fsync; checkpoints copy changed trie paths and publish through two
protected seal banks. The fixed object pool is reclaimed by root reachability.
This is not a mounted filesystem or a hardware durability qualification.
"""
from __future__ import annotations
import argparse,base64,errno,hashlib,heapq,json,os,re,stat,struct,sys,uuid
from pathlib import Path
try:
    import fcntl
except ImportError:
    fcntl=None

FORMAT=5
MAGIC=b'NYPAGES5'
SLOTS=64
SPAN=65536
SECTOR=512
BLOCK_SIZE=4096
SEAL_OFFSETS=(0,4096,8192,12288)
RING_START=16384
POOL_START=RING_START+2*SLOTS*SPAN
APPEND_START=POOL_START
DEFAULT_POOL_BLOCKS=16384
MAX_POOL_BLOCKS=1<<20
MAX_U64=(1<<64)-1
K_SEAL,K_CATALOG,K_TRIE,K_BLOB,K_DATA,K_CAPSULE=1,2,3,4,5,6
PREFIX=struct.Struct('>8sHHIQ16s32s')
HEADER=struct.Struct('>8sHHIQ16s32s32s')
PAGE_PAYLOAD=BLOCK_SIZE-HEADER.size
MAX_CAPSULE=SPAN-HEADER.size
INLINE_LIMIT=256
ZERO='0'*64
HEX32=re.compile(r'^[0-9a-f]{32}$')
HEX64=re.compile(r'^[0-9a-f]{64}$')
TOKEN=re.compile(r'^[A-Za-z0-9_.:-]{1,64}$')
HEX='0123456789abcdef'

class StoreError(Exception):pass
class InvalidImage(StoreError):pass
class RecoveryBlocked(StoreError):pass
class SplitIdentity(RecoveryBlocked):pass
class UnsupportedFormat(RecoveryBlocked):pass
class WriterFenced(StoreError):pass
class TransactionConflict(StoreError):pass

def canonical(obj):return json.dumps(obj,sort_keys=True,separators=(',',':'),ensure_ascii=True,allow_nan=False).encode('ascii')
def digest(raw):return hashlib.sha256(raw).hexdigest()
def uint(x,maximum=MAX_U64):return type(x) is int and 0<=x<=maximum
def hash_key(key):return hashlib.sha256(key.encode('utf8')).hexdigest()
def path_key(path):
    if not isinstance(path,str) or not path.startswith('/') or '\\' in path or '\0' in path or len(path.encode('utf8'))>1024 or len(canonical(path))>PAGE_PAYLOAD-512 or any(p in ('','.','..') for p in path[1:].split('/')):
        raise ValueError('canonical absolute flat path key required')
    return path
def token_key(token):
    if not isinstance(token,str) or not TOKEN.fullmatch(token):raise ValueError('safe ASCII token required')
    return token
def b64(raw):return base64.b64encode(raw).decode('ascii')
def unb64(value):
    if not isinstance(value,str):raise InvalidImage('base64 type')
    try:raw=base64.b64decode(value,validate=True)
    except (ValueError,UnicodeError) as exc:raise InvalidImage('base64 encoding') from exc
    if b64(raw)!=value:raise InvalidImage('noncanonical base64')
    return raw
def unpack_json(raw):
    def pairs(items):
        d={}
        for k,v in items:
            if k in d:raise InvalidImage('duplicate JSON field')
            d[k]=v
        return d
    try:obj=json.loads(raw.decode('ascii'),object_pairs_hook=pairs,parse_constant=lambda _:(_ for _ in ()).throw(ValueError()))
    except (ValueError,UnicodeError,RecursionError) as exc:raise InvalidImage('invalid JSON') from exc
    if not isinstance(obj,dict) or canonical(obj)!=raw:raise InvalidImage('noncanonical JSON object')
    return obj
def pack(kind,payload,epoch,volume,fixed=None):
    if not uint(epoch) or not isinstance(volume,str) or not HEX32.fullmatch(volume):raise ValueError('record identity')
    prefix=PREFIX.pack(MAGIC,FORMAT,kind,len(payload),epoch,bytes.fromhex(volume),hashlib.sha256(payload).digest())
    raw=prefix+hashlib.sha256(prefix).digest()+payload
    if fixed is not None:
        if len(raw)>fixed:raise ValueError('record exceeds reserved unit')
        raw+=bytes(fixed-len(raw))
    return raw
def read_header(raw,kind,maximum):
    if len(raw)<HEADER.size:raise InvalidImage('short header')
    magic,version,k,n,e,vol,h,check=HEADER.unpack_from(raw)
    if magic!=MAGIC or k!=kind or hashlib.sha256(raw[:PREFIX.size]).digest()!=check:raise InvalidImage('header identity/checksum')
    if version!=FORMAT:raise UnsupportedFormat('checksum-valid unsupported format')
    if n>maximum:raise RecoveryBlocked('checksum-valid length exceeds bound')
    return {'epoch':e,'volume':vol.hex(),'length':n,'digest':h.hex()}
def read_payload(raw,head):
    body=raw[HEADER.size:HEADER.size+head['length']]
    if len(body)!=head['length'] or digest(body)!=head['digest']:raise InvalidImage('payload length/digest')
    return body
def capsule_offset(epoch,replica):return RING_START+(replica*SLOTS+epoch%SLOTS)*SPAN
def block_offset(index):return POOL_START+index*BLOCK_SIZE

class PageStore:
    """Single serialized publisher; fixed-capacity mirrored object arena."""
    def __init__(self,path,*,writable=True,minimum_epoch=None):
        if fcntl is None:raise StoreError('POSIX flock required')
        self.path=os.fspath(path);self.fd=None;self.writable=writable;self.fenced=False;self.reset_stats()
        fd=os.open(self.path,(os.O_RDWR if writable else os.O_RDONLY)|getattr(os,'O_NOFOLLOW',0))
        try:
            if not stat.S_ISREG(os.fstat(fd).st_mode):raise InvalidImage('regular image file required')
            fcntl.flock(fd,(fcntl.LOCK_EX if writable else fcntl.LOCK_SH)|fcntl.LOCK_NB);self.fd=fd
            self._recover()
            if minimum_epoch is not None and (not uint(minimum_epoch) or self.epoch<minimum_epoch):raise RecoveryBlocked('below caller minimum epoch')
            if writable:self._reprotect()
        except BaseException:os.close(fd);self.fd=None;raise
    @classmethod
    def create(cls,path,*,initial_files=None,pool_blocks=DEFAULT_POOL_BLOCKS):
        if fcntl is None:raise StoreError('POSIX flock required')
        if not uint(pool_blocks,MAX_POOL_BLOCKS) or pool_blocks<16:raise ValueError('pool_blocks must be 16..1048576')
        if initial_files is not None and not isinstance(initial_files,dict):raise TypeError('initial_files dictionary required')
        files={}
        for key,value in (initial_files or {}).items():
            path_key(key)
            if not isinstance(value,bytes):raise TypeError('bytes values required')
            if len(value)>MAX_CAPSULE:raise ValueError('initial value exceeds supported size')
            files[key]=value
        fd=os.open(os.fspath(path),os.O_RDWR|os.O_CREAT|os.O_EXCL|getattr(os,'O_NOFOLLOW',0),0o600)
        self=cls.__new__(cls);self.path=os.fspath(path);self.fd=fd;self.writable=True;self.fenced=False;self.reset_stats()
        try:
            if not stat.S_ISREG(os.fstat(fd).st_mode):raise InvalidImage('regular image file required')
            fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB);os.ftruncate(fd,POOL_START+pool_blocks*BLOCK_SIZE)
            self.volume=uuid.uuid4().hex;self.pool_blocks=pool_blocks;self.generation=-1;self.epoch=0;self.checkpoint_epoch=0;self.history=ZERO
            self.files_root=None;self.tokens_root=None;self.catalog_desc=None;self._files=files;self._tokens={};self.active={}
            self._dirty_files=dict(files);self._dirty_tokens={};self._cache={};self._graph_cache={};self._repair_records=[];self._selected_valid_slots=set();self._live_blocks=set()
            self._free=list(range(pool_blocks));heapq.heapify(self._free)
            self._refs={};self._block_owner={};self._pending=set()
            self.checkpoint(initial=True)
            parent=os.open(str(Path(path).resolve().parent),os.O_RDONLY|getattr(os,'O_DIRECTORY',0))
            try:os.fsync(parent)
            finally:os.close(parent)
            return self
        except BaseException:self.close();raise
    def __enter__(self):return self
    def __exit__(self,*exc):self.close()
    def close(self):
        if self.fd is not None:os.close(self.fd);self.fd=None
    def _live(self):
        if self.fd is None:raise StoreError('closed')
        if self.fenced:raise WriterFenced('uncertain state: close and recover')
    def _writable(self):
        self._live()
        if not self.writable:raise WriterFenced('read-only image')
    def reset_stats(self):
        self.stats={'bytes_written':0,'write_calls':0,'fsync_calls':0,'capsule_batches':0,'checkpoints':0,
                    'page_allocations':0,'reclaimed_blocks':0,'arena_live_blocks':0,'full_graph_scans':0,
                    'incremental_validations':0,'graph_nodes_validated':0,'refcount_steps':0,'pool_rebuilds':0}
    def _pwrite(self,raw,offset):
        view=memoryview(raw)
        while view:
            n=os.pwrite(self.fd,view,offset)
            if n<=0:raise OSError('zero-length write')
            self.stats['bytes_written']+=n;self.stats['write_calls']+=1;view=view[n:];offset+=n
    def _sync(self):self.stats['fsync_calls']+=1;os.fsync(self.fd)
    def _valid_desc(self,desc,kind=None):
        if not isinstance(desc,list) or len(desc)!=6:return False
        a,b,g,k,n,h=desc
        return (uint(a,self.pool_blocks-1) and uint(b,self.pool_blocks-1) and a!=b and uint(g) and
                type(k) is int and k in (K_CATALOG,K_TRIE,K_BLOB,K_DATA) and (kind is None or k==kind)
                and uint(n,PAGE_PAYLOAD) and isinstance(h,str) and bool(HEX64.fullmatch(h)))
    def _alloc_object(self,kind,body):
        if len(body)>PAGE_PAYLOAD:raise StoreError('object exceeds page payload')
        if len(self._free)<2:raise OSError(errno.ENOSPC,'fixed object arena lacks COW checkpoint headroom')
        a,b=heapq.heappop(self._free),heapq.heappop(self._free)
        desc=[a,b,self._writing_generation,kind,len(body),digest(body)]
        key=tuple(desc);self._pending.add(key)
        for index in (a,b):
            if index in self._block_owner:raise InvalidImage('allocator selected an owned block')
            self._block_owner[index]=key
        raw=pack(kind,body,self._writing_generation,self.volume,fixed=BLOCK_SIZE)
        for index in (a,b):self._pwrite(raw,block_offset(index))
        self._cache[tuple(desc)]=body;self.stats['page_allocations']+=2
        return desc
    def _read_object(self,desc,kind=None):
        if not self._valid_desc(desc,kind):raise InvalidImage('object descriptor bounds/identity')
        key=tuple(desc)
        if key in self._cache:return self._cache[key]
        good=None;bad=[]
        for index in desc[:2]:
            try:
                raw=os.pread(self.fd,BLOCK_SIZE,block_offset(index));head=read_header(raw,desc[3],PAGE_PAYLOAD);body=read_payload(raw,head)
                if head['epoch']!=desc[2] or head['volume']!=self.volume or len(body)!=desc[4] or digest(body)!=desc[5]:raise InvalidImage('object generation/digest mismatch')
                good=body
            except (InvalidImage,OSError):bad.append(index)
        if good is None:raise RecoveryBlocked('required object has no valid mirror; fallback refused')
        expected=pack(desc[3],good,desc[2],self.volume,fixed=BLOCK_SIZE)
        for index in bad:self._repair_records.append((block_offset(index),expected))
        self._cache[key]=good;return good
    def _put_json(self,kind,obj):return self._alloc_object(kind,canonical(obj))
    def _file_value(self,data):
        if len(data)>MAX_CAPSULE:raise ValueError('value exceeds supported size')
        if len(data)<=INLINE_LIMIT:return {'inline':b64(data)}
        chunks=[self._alloc_object(K_DATA,data[i:i+PAGE_PAYLOAD]) for i in range(0,len(data),PAGE_PAYLOAD)]
        return {'blob':self._put_json(K_BLOB,{'length':len(data),'digest':digest(data),'chunks':chunks})}
    def _build_tree(self,family,entries,depth=0):
        if not entries:return None
        leaf={'family':family,'type':'leaf','depth':depth,'entries':entries};raw=canonical(leaf)
        if len(raw)<=PAGE_PAYLOAD:return self._alloc_object(K_TRIE,raw)
        if depth>=64:raise StoreError('hash collision leaf exceeds page capacity')
        groups={}
        for key,value in entries.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
        children={nib:self._build_tree(family,group,depth+1) for nib,group in groups.items()}
        return self._put_json(K_TRIE,{'family':family,'type':'branch','depth':depth,'children':children})
    def _update_tree(self,desc,family,changes,depth=0):
        if not changes:return desc
        if desc is None:return self._build_tree(family,{k:v for k,v in changes.items() if v is not None},depth)
        node=unpack_json(self._read_object(desc,K_TRIE))
        if node.get('family')!=family or node.get('depth')!=depth:raise InvalidImage('trie update identity/depth')
        if node.get('type')=='leaf':
            entries=dict(node['entries'])
            for key,value in changes.items():
                if value is None:entries.pop(key,None)
                else:entries[key]=value
            if entries==node['entries']:return desc
            return self._build_tree(family,entries,depth)
        if node.get('type')!='branch' or depth>=64:raise InvalidImage('trie branch update')
        children=dict(node['children']);groups={}
        for key,value in changes.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
        for nib,group in groups.items():
            child=self._update_tree(children.get(nib),family,group,depth+1)
            if child is None:children.pop(nib,None)
            else:children[nib]=child
        if children==node['children']:return desc
        if not children:return None
        return self._put_json(K_TRIE,{'family':family,'type':'branch','depth':depth,'children':children})
    def _scan_graph(self,catalog_desc,*,decode=False,generation=None,incremental=False):
        """Full recovery validation, or validation of newly reserved objects only.

        An unchanged pointer is accepted only when its complete identity is live
        and its validated family/routing/owner context matches the new edge.
        """
        self.stats['incremental_validations' if incremental else 'full_graph_scans']+=1
        seen=set();identities=set();files={};tokens={}
        selected_generation=self.generation if generation is None else generation
        if not self._valid_desc(catalog_desc,K_CATALOG) or catalog_desc[2]!=selected_generation:raise InvalidImage('catalogue birth differs from selected generation')
        def known(desc,kind,context):
            if not self._valid_desc(desc,kind) or desc[2]>selected_generation:raise InvalidImage('invalid reachable descriptor/birth')
            if not incremental:return False
            key=tuple(desc)
            if any(self._block_owner.get(index)!=key for index in desc[:2]):raise InvalidImage('descriptor does not own its reserved/live blocks')
            if self._refs.get(key,0):
                info=self._graph_cache.get(key)
                if info is None or info['context']!=context or info['max_epoch']>cat['epoch']:raise InvalidImage('unchanged object context/epoch mismatch')
                return True
            if key not in self._pending:raise InvalidImage('pointer is neither live nor reserved')
            return False
        def claim(desc,kind):
            if not self._valid_desc(desc,kind) or desc[2]>selected_generation:raise InvalidImage('invalid reachable descriptor/birth')
            if seen.intersection(desc[:2]):raise InvalidImage('object block alias/cycle')
            seen.update(desc[:2]);identities.add(tuple(desc));self.stats['graph_nodes_validated']+=1
            return self._read_object(desc,kind)
        if incremental:
            key=tuple(catalog_desc)
            if key not in self._pending or any(self._block_owner.get(index)!=key for index in catalog_desc[:2]):raise InvalidImage('candidate catalogue not reserved')
        cat=unpack_json(claim(catalog_desc,K_CATALOG))
        if (set(cat)!={'format','volume','epoch','history','files_root','tokens_root'} or type(cat['format']) is not int or cat['format']!=FORMAT or
            cat['volume']!=self.volume or not uint(cat['epoch']) or not isinstance(cat['history'],str) or not HEX64.fullmatch(cat['history'])):raise InvalidImage('catalogue schema')
        if incremental and (cat['epoch']!=self.epoch or cat['history']!=self.history):raise InvalidImage('candidate logical head mismatch')
        def remember(desc,links,context,max_epoch=0):
            self._graph_cache[tuple(desc)]={'links':links,'context':context,'max_epoch':max_epoch}
        def file_value(path,obj):
            if not isinstance(obj,dict):raise InvalidImage('file value schema')
            if set(obj)=={'inline'}:
                data=unb64(obj['inline'])
                if len(data)>INLINE_LIMIT:raise InvalidImage('oversized inline value')
                return data,[]
            if set(obj)!={'blob'}:raise InvalidImage('file encoding')
            desc=obj['blob'];links=[(desc,K_BLOB)]
            if known(desc,K_BLOB,('blob',path)):return None,links
            manifest=unpack_json(claim(desc,K_BLOB))
            if (set(manifest)!={'length','digest','chunks'} or not uint(manifest['length'],MAX_CAPSULE) or manifest['length']<=INLINE_LIMIT or
                not isinstance(manifest['digest'],str) or not HEX64.fullmatch(manifest['digest']) or
                not isinstance(manifest['chunks'],list) or len(manifest['chunks'])!=(manifest['length']+PAGE_PAYLOAD-1)//PAGE_PAYLOAD):raise InvalidImage('blob manifest')
            parts=[]
            for i,chunk in enumerate(manifest['chunks']):
                context=('data',path,i)
                if known(chunk,K_DATA,context):part=self._read_object(chunk,K_DATA)
                else:
                    part=claim(chunk,K_DATA);remember(chunk,[],context)
                if len(part)!=min(PAGE_PAYLOAD,manifest['length']-i*PAGE_PAYLOAD):raise InvalidImage('blob chunk length')
                parts.append(part)
            data=b''.join(parts)
            if len(data)!=manifest['length'] or digest(data)!=manifest['digest']:raise InvalidImage('blob data mismatch')
            remember(desc,[(chunk,K_DATA) for chunk in manifest['chunks']],('blob',path))
            return data,links
        def walk(desc,family,depth=0,prefix=''):
            if desc is None:return
            context=('trie',family,depth,prefix)
            if known(desc,K_TRIE,context):return
            node=unpack_json(claim(desc,K_TRIE))
            if node.get('family')!=family or type(node.get('depth')) is not int or node['depth']!=depth or depth>64:raise InvalidImage('trie identity/depth')
            links=[];max_epoch=0
            if node.get('type')=='leaf':
                if set(node)!={'family','type','depth','entries'} or not isinstance(node['entries'],dict) or not node['entries']:raise InvalidImage('leaf schema')
                for key,value in node['entries'].items():
                    try:path_key(key) if family=='files' else token_key(key)
                    except ValueError as exc:raise InvalidImage('trie key') from exc
                    if not hash_key(key).startswith(prefix):raise InvalidImage('trie key routing')
                    if family=='files':
                        data,dependencies=file_value(key,value);links.extend(dependencies)
                        if decode:files[key]=data
                    else:
                        if not isinstance(value,list) or len(value)!=2 or not uint(value[0],cat['epoch']) or not value[0] or not isinstance(value[1],str) or not HEX64.fullmatch(value[1]):raise InvalidImage('token receipt')
                        max_epoch=max(max_epoch,value[0])
                        if decode:tokens[key]=value
                remember(desc,links,context,max_epoch);return
            if (node.get('type')!='branch' or set(node)!={'family','type','depth','children'} or depth>=64 or
                not isinstance(node['children'],dict) or not node['children'] or any(nib not in HEX or len(nib)!=1 for nib in node['children'])):raise InvalidImage('branch schema')
            for nib,child in node['children'].items():
                walk(child,family,depth+1,prefix+nib);links.append((child,K_TRIE))
                max_epoch=max(max_epoch,self._graph_cache[tuple(child)]['max_epoch'])
            remember(desc,links,context,max_epoch)
        walk(cat['files_root'],'files');walk(cat['tokens_root'],'tokens')
        remember(catalog_desc,[(desc,K_TRIE) for desc in (cat['files_root'],cat['tokens_root']) if desc is not None],('catalog',))
        return cat,seen,files,tokens
    def _acquire(self,desc):
        """Activate outgoing edges only on the object's zero-to-one transition."""
        key=tuple(desc);previous=self._refs.get(key,0);self._refs[key]=previous+1;self.stats['refcount_steps']+=1
        if previous:return
        info=self._graph_cache.get(key)
        if info is None:raise InvalidImage('acquiring unvalidated object')
        self._pending.discard(key);self._live_blocks.update(desc[:2])
        for child,kind in info['links']:self._acquire(child)
    def _release(self,desc):
        """Retire outgoing edges and recycle blocks only at the last reference."""
        key=tuple(desc);count=self._refs.get(key,0);self.stats['refcount_steps']+=1
        if count<=0:raise InvalidImage('reference count underflow')
        if count>1:self._refs[key]=count-1;return
        del self._refs[key];info=self._graph_cache.pop(key)
        for child,kind in info['links']:self._release(child)
        self._cache.pop(key,None)
        for index in desc[:2]:
            if self._block_owner.pop(index,None)!=key:raise InvalidImage('releasing object ownership mismatch')
            self._live_blocks.remove(index);heapq.heappush(self._free,index)
        self.stats['reclaimed_blocks']+=2
    def _discard_unreachable_reservations(self):
        # Normally empty: retain this guard for allocations omitted by a builder.
        for key in self._pending:
            if self._refs.get(key,0):raise InvalidImage('live allocation remained reserved')
            self._cache.pop(key,None);self._graph_cache.pop(key,None)
            for index in key[:2]:
                if self._block_owner.pop(index,None)!=key:raise InvalidImage('reservation ownership mismatch')
                heapq.heappush(self._free,index)
            self.stats['reclaimed_blocks']+=2
        self._pending.clear()
    def _validate_capsule(self,obj,head):
        if (set(obj)!={'format','volume','epoch','parent','token','intent','changes'} or type(obj['format']) is not int or obj['format']!=FORMAT or
            obj['volume']!=self.volume or obj['epoch']!=head['epoch'] or not uint(obj['epoch']) or not obj['epoch'] or
            not isinstance(obj['parent'],str) or not HEX64.fullmatch(obj['parent']) or not isinstance(obj['changes'],list) or not obj['changes']):raise InvalidImage('capsule schema')
        try:token_key(obj['token'])
        except ValueError as exc:raise InvalidImage('capsule token') from exc
        previous=None;items=[]
        for change in obj['changes']:
            if not isinstance(change,list) or len(change)!=2:raise InvalidImage('change schema')
            path,value=change
            try:path_key(path)
            except ValueError as exc:raise InvalidImage('capsule path') from exc
            if previous is not None and path<=previous:raise InvalidImage('unsorted/duplicate changes')
            previous=path;raw=None if value is None else unb64(value)
            items.append([path,None if raw is None else [len(raw),digest(raw)]])
        if digest(canonical(items))!=obj['intent']:raise InvalidImage('intent mismatch')
        return obj
    def _apply(self,obj):
        if obj['token'] in self._tokens:raise RecoveryBlocked('duplicate committed token')
        for path,value in obj['changes']:
            data=None if value is None else unb64(value)
            if data is None:self._files.pop(path,None)
            else:self._files[path]=data
            self._dirty_files[path]=data
        entry=[obj['epoch'],obj['intent']];self._tokens[obj['token']]=entry;self._dirty_tokens[obj['token']]=entry
    def _recover(self):
        self._cache={};self._graph_cache={};self._repair_records=[];seals=[];places=[]
        for slot,off in enumerate(SEAL_OFFSETS):
            try:
                raw=os.pread(self.fd,SECTOR,off);head=read_header(raw,K_SEAL,SECTOR-HEADER.size);obj=unpack_json(read_payload(raw,head))
                if (set(obj)!={'generation','volume','pool_blocks','root'} or not uint(obj['generation']) or obj['generation']!=head['epoch'] or
                    obj['volume']!=head['volume'] or not uint(obj['pool_blocks'],MAX_POOL_BLOCKS) or obj['pool_blocks']<16):raise InvalidImage('seal schema')
                seals.append(obj);places.append((slot,obj))
            except (InvalidImage,OSError):continue
        if not seals:raise RecoveryBlocked('no valid catalogue seal')
        if len({s['volume'] for s in seals})!=1:raise SplitIdentity('volume disagreement')
        g=max(s['generation'] for s in seals);newest=[s for s in seals if s['generation']==g]
        if len({canonical(s) for s in newest})!=1:raise SplitIdentity('same-generation disagreement')
        self.seal=newest[0];self.generation=g;self.volume=self.seal['volume'];self.pool_blocks=self.seal['pool_blocks']
        if os.fstat(self.fd).st_size!=POOL_START+self.pool_blocks*BLOCK_SIZE:raise InvalidImage('fixed image capacity mismatch')
        self._selected_valid_slots={i for i,s in places if canonical(s)==canonical(self.seal)}
        self.catalog_desc=self.seal['root']
        cat,live,files,tokens=self._scan_graph(self.catalog_desc,decode=True)
        self.files_root=cat['files_root'];self.tokens_root=cat['tokens_root'];self.epoch=self.checkpoint_epoch=cat['epoch'];self.history=cat['history']
        self._files=files;self._tokens=tokens;self._dirty_files={};self._dirty_tokens={};self._live_blocks=live
        self._free=[i for i in range(self.pool_blocks) if i not in live];heapq.heapify(self._free);self.stats['pool_rebuilds']+=1
        self._refs={key:1 for key in self._graph_cache}
        self._block_owner={index:key for key in self._refs for index in key[:2]};self._pending=set()
        headers={};complete={};valid={}
        for slot in range(SLOTS):
            for replica in range(2):
                off=RING_START+(replica*SLOTS+slot)*SPAN
                try:rawhead=os.pread(self.fd,HEADER.size,off);head=read_header(rawhead,K_CAPSULE,MAX_CAPSULE)
                except (InvalidImage,OSError):continue
                if head['volume']!=self.volume:raise SplitIdentity('capsule volume disagreement')
                e=head['epoch']
                if e<=self.checkpoint_epoch:continue
                if e%SLOTS!=slot or e-self.checkpoint_epoch>SLOTS:raise RecoveryBlocked('capsule outside bounded window')
                identity=(head['length'],head['digest']);headers.setdefault(e,set()).add(identity)
                if len(headers[e])!=1:raise SplitIdentity('same-epoch capsule disagreement')
                try:
                    body=read_payload(rawhead+os.pread(self.fd,head['length'],off+HEADER.size),head)
                    obj=self._validate_capsule(unpack_json(body),head)
                except (InvalidImage,OSError):continue
                complete[e]={'body':body,'obj':obj,'digest':digest(body)};valid.setdefault(e,set()).add(replica)
        if any(e not in complete for e in headers):raise RecoveryBlocked('newer valid header lacks complete capsule')
        for e,item in sorted(complete.items()):
            if e!=self.epoch+1 or item['obj']['parent']!=self.history:raise RecoveryBlocked('capsule history gap/parent mismatch')
            self._apply(item['obj']);self.epoch=e;self.history=item['digest']
            raw=pack(K_CAPSULE,item['body'],e,self.volume)
            for replica in range(2):
                if replica not in valid[e]:self._repair_records.append((capsule_offset(e,replica),raw))
        self.active=complete;self.stats['arena_live_blocks']=len(live)
    def _reprotect(self):
        try:
            for off,raw in self._repair_records:self._pwrite(raw,off)
            if self._repair_records:self._sync()
            targets=[i for i in range((self.generation%2)*2,(self.generation%2)*2+2) if i not in self._selected_valid_slots]
            if targets:
                raw=pack(K_SEAL,canonical(self.seal),self.generation,self.volume,fixed=SECTOR)
                for i in targets:self._pwrite(raw,SEAL_OFFSETS[i])
                self._sync();self._selected_valid_slots.update(targets)
        except BaseException:self.fenced=True;raise
        self._repair_records=[]
    def checkpoint(self,initial=False):
        self._writable()
        if initial and self.generation!=-1:raise ValueError('initial checkpoint restricted to creation')
        if self.generation==MAX_U64:raise StoreError('catalogue generation exhausted')
        generation=self.generation+1;self._writing_generation=generation
        old_root=self.catalog_desc
        try:
            changes={path:None if value is None else self._file_value(value) for path,value in self._dirty_files.items()}
            files_root=self._update_tree(self.files_root,'files',changes)
            tokens_root=self._update_tree(self.tokens_root,'tokens',self._dirty_tokens)
            cat={'format':FORMAT,'volume':self.volume,'epoch':self.epoch,'history':self.history,'files_root':files_root,'tokens_root':tokens_root}
            root=self._put_json(K_CATALOG,cat)
            seal={'generation':generation,'volume':self.volume,'pool_blocks':self.pool_blocks,'root':root}
            raw=pack(K_SEAL,canonical(seal),generation,self.volume,fixed=SECTOR)
            self._scan_graph(root,generation=generation,incremental=True)
            self._acquire(root)
            self._sync()
            targets=range(4) if initial else range((generation%2)*2,(generation%2)*2+2)
            for i in targets:self._pwrite(raw,SEAL_OFFSETS[i])
            self._sync()
            # Publication is durable before the allocator changes ownership.
            self.generation=generation;self.seal=seal;self.catalog_desc=root;self.files_root=files_root;self.tokens_root=tokens_root
            self.checkpoint_epoch=self.epoch;self._selected_valid_slots=set(targets)
            if old_root is not None:self._release(old_root)
            self._discard_unreachable_reservations()
            self._repair_records=[];self.active={};self._dirty_files={};self._dirty_tokens={}
            self.stats['checkpoints']+=1;self.stats['arena_live_blocks']=len(self._live_blocks)
        except BaseException:self.fenced=True;raise
        return self.checkpoint_epoch
    def transact(self,changes,token):
        self._writable();token_key(token)
        if not isinstance(changes,dict) or not changes:raise ValueError('nonempty changes dictionary required')
        encoded=[];items=[]
        for path,value in sorted(changes.items()):
            path_key(path)
            if value is not None and not isinstance(value,bytes):raise TypeError('bytes or None values required')
            encoded.append([path,None if value is None else b64(value)]);items.append([path,None if value is None else [len(value),digest(value)]])
        intent=digest(canonical(items));old=self._tokens.get(token)
        if old:
            if old[1]!=intent:raise TransactionConflict('token reused with different intent')
            return old[0]
        if self.epoch==MAX_U64:raise StoreError('epoch exhausted')
        e=self.epoch+1;obj={'format':FORMAT,'volume':self.volume,'epoch':e,'parent':self.history,'token':token,'intent':intent,'changes':encoded}
        body=canonical(obj)
        if len(body)>MAX_CAPSULE:raise ValueError('capsule payload exceeds bound')
        if len(self.active)>=SLOTS:self.checkpoint()
        raw=pack(K_CAPSULE,body,e,self.volume)
        try:
            for replica in range(2):self._pwrite(raw,capsule_offset(e,replica))
            self._sync();self._apply(obj);self.epoch=e;self.history=digest(body)
            self.active[e]={'body':body,'obj':obj,'digest':self.history};self.stats['capsule_batches']+=1
        except BaseException:self.fenced=True;raise
        return e
    def get(self,path):
        self._live();path_key(path)
        try:return self._files[path]
        except KeyError:raise FileNotFoundError(path) from None
    def files(self):self._live();return sorted(self._files)
    def query(self,token):
        self._live();token_key(token);entry=self._tokens.get(token)
        return None if entry is None else {'epoch':entry[0],'intent_sha256':entry[1]}
    def inspect(self):
        self._live();return {'format':FORMAT,'volume':self.volume,'epoch':self.epoch,'checkpoint_epoch':self.checkpoint_epoch,
            'generation':self.generation,'pool_blocks':self.pool_blocks,'live_blocks':len(self._live_blocks),'free_blocks':len(self._free),
            'files':self.files(),'tokens':len(self._tokens),'fixed_image_bytes':POOL_START+self.pool_blocks*BLOCK_SIZE,'io':dict(self.stats)}

CutStore=ImageStore=PageStore
def main(argv=None):
    parser=argparse.ArgumentParser(description=__doc__);sub=parser.add_subparsers(dest='command',required=True)
    for name in ('init','demo','inspect','ls'):
        p=sub.add_parser(name);p.add_argument('image')
    args=parser.parse_args(argv)
    try:
        if args.command in ('init','demo'):
            with PageStore.create(args.image) as store:
                if args.command=='demo':store.transact({'/measurement':b'12.345','/index':b'revision=1'},'demo')
                print(json.dumps(store.inspect(),indent=2))
        else:
            with PageStore(args.image,writable=False) as store:
                print('\n'.join(store.files()) if args.command=='ls' else json.dumps(store.inspect(),indent=2))
        return 0
    except (StoreError,OSError,ValueError,TypeError) as exc:print('error: '+str(exc),file=sys.stderr);return 2
if __name__=='__main__':raise SystemExit(main())