File size: 48,432 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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
#!/usr/bin/env python3
"""NYARION VII incremental-reservation immutable page-tree research 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
from collections import ChainMap
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'
# Descriptor fields use their largest allowed encoded widths. A symbolic leaf
# built with this descriptor is never smaller than its physical counterpart.
BOUND_DESC=(MAX_POOL_BLOCKS-1,MAX_POOL_BLOCKS-1,MAX_U64,K_BLOB,PAGE_PAYLOAD,'f'*64)

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
class AdmissionRejected(OSError):
    """No offered capsule was written: its exact checkpoint cannot fit."""
    pass

def canonical(obj):return json.dumps(obj,sort_keys=True,separators=(',',':'),ensure_ascii=True,allow_nan=False).encode('ascii')
# All branch/manifest/catalogue records fit even at the declared format bounds.
assert len(canonical({'family':'tokens','type':'branch','depth':63,'children':{n:BOUND_DESC for n in HEX}}))<=PAGE_PAYLOAD
assert len(canonical({'length':MAX_CAPSULE,'digest':'f'*64,'chunks':[BOUND_DESC]*((MAX_CAPSULE+PAGE_PAYLOAD-1)//PAGE_PAYLOAD)}))<=PAGE_PAYLOAD
assert len(canonical({'format':FORMAT,'volume':'f'*32,'epoch':MAX_U64,'history':'f'*64,'files_root':BOUND_DESC,'tokens_root':BOUND_DESC}))<=PAGE_PAYLOAD
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()
                if self.active:
                    try:self._checkpoint_plan=self._prepare_checkpoint_plan()
                    except AdmissionRejected as exc:
                        raise AdmissionRejected(errno.ENOSPC,'recovered capsule tail has no feasible checkpoint; read-only recovery remains available') from exc
        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_plan=None
            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,
                    'admission_plans':0,'admission_planned_blocks':0,'admission_rejections':0,'admission_pressure_checkpoints':0,'executed_plans':0,
                    'reservation_offers':0,'reservation_fast_accepts':0,'reservation_exact_fallbacks':0,'reservation_cells_rebuilt':0,'reservation_route_visits':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._checkpoint_plan=None;self.stats['arena_live_blocks']=len(live)
        self._reset_reservations(ready=False)
    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=[]
    @staticmethod
    def _heap_order(heap):
        """Yield min-heap values in pop order without copying the arena heap."""
        if not heap:return
        frontier=[(heap[0],0)]
        while frontier:
            value,index=heapq.heappop(frontier);yield value
            for child in (2*index+1,2*index+2):
                if child<len(heap):heapq.heappush(frontier,(heap[child],child))
    def _reset_reservations(self,ready=True):
        self._reservation_ready=ready;self._reservation_cells={};self._reservation_ancestors=set()
        self._reservation_blob_pages={};self._reservation_logical=1
        self._reservation_decoded={};self._reservation_routes={}
    def _reservation_route(self,family,key):
        cached=self._reservation_routes.get((family,key))
        if cached is not None:return cached
        desc=self.files_root if family=='files' else self.tokens_root
        depth=0;prefix='';ancestors=[];hashed=hash_key(key)
        while desc is not None:
            identity=tuple(desc);node=self._reservation_decoded.get(identity)
            if node is None:
                node=unpack_json(self._read_object(desc,K_TRIE));self._reservation_decoded[identity]=node
            self.stats['reservation_route_visits']+=1
            if node['family']!=family or node['depth']!=depth:raise InvalidImage('reservation routing identity')
            if node['type']=='leaf':
                answer=((family,prefix),depth,node['entries'],tuple(ancestors));break
            if node['type']!='branch' or depth>=64:raise InvalidImage('reservation routing branch')
            ancestors.append(identity);nib=hashed[depth];prefix+=nib;depth+=1
            desc=node['children'].get(nib)
        else:answer=((family,prefix),depth,{},tuple(ancestors))
        self._reservation_routes[(family,key)]=answer
        return answer
    @staticmethod
    def _reservation_count(family,entries,depth):
        if not entries:return 0
        if len(canonical({'family':family,'type':'leaf','depth':depth,'entries':entries}))<=PAGE_PAYLOAD:return 1
        if depth>=64:return MAX_POOL_BLOCKS  # Force the exact compiler to decide.
        groups={}
        for key,value in entries.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
        return 1+sum(PageStore._reservation_count(family,group,depth+1) for group in groups.values())
    def _reservation_preview(self,file_changes,token_changes):
        """Pure budget proposal over affected published-leaf cells.

        Lookup caches may grow, but committed cells, totals and allocator state
        are unchanged. New descriptors use maximum widths; extra splits and
        ancestor charges are conservative, never less than the exact builder.
        """
        self.stats['reservation_offers']+=1
        proposed={};added_ancestors=set();blob_updates={};logical=self._reservation_logical
        for family,changes in (('files',file_changes),('tokens',token_changes)):
            for key,value in sorted(changes.items()):
                anchor,depth,original,ancestors=self._reservation_route(family,key)
                added_ancestors.update(a for a in ancestors if a not in self._reservation_ancestors)
                if anchor not in proposed:
                    previous=self._reservation_cells.get(anchor)
                    proposed[anchor]={'depth':depth,'entries':dict(original if previous is None else previous['entries'])}
                entries=proposed[anchor]['entries']
                if family=='files':
                    pages=0
                    if value is None:entries.pop(key,None)
                    elif len(value)<=INLINE_LIMIT:entries[key]={'inline':b64(value)}
                    else:
                        entries[key]={'blob':BOUND_DESC}
                        pages=(len(value)+PAGE_PAYLOAD-1)//PAGE_PAYLOAD+1
                    blob_updates[key]=pages
                else:entries[key]=value
        logical+=len(added_ancestors)
        for anchor,cell in proposed.items():
            old=self._reservation_cells.get(anchor)
            cell['nodes']=self._reservation_count(anchor[0],cell['entries'],cell['depth'])
            logical+=cell['nodes']-(0 if old is None else old['nodes'])
            self.stats['reservation_cells_rebuilt']+=1
        for key,pages in blob_updates.items():logical+=pages-self._reservation_blob_pages.get(key,0)
        return {'cells':proposed,'ancestors':added_ancestors,'blobs':blob_updates,'logical':logical,'physical_blocks':2*logical}
    def _reservation_adopt(self,proposal):
        self._reservation_cells.update(proposal['cells']);self._reservation_ancestors.update(proposal['ancestors'])
        self._reservation_blob_pages.update(proposal['blobs']);self._reservation_logical=proposal['logical']
    def _ensure_reservations(self):
        if getattr(self,'_reservation_ready',False):return
        self._reset_reservations(ready=False)
        proposal=self._reservation_preview(self._dirty_files,self._dirty_tokens)
        self._reservation_adopt(proposal);self._reservation_ready=True
    def admission_reservation(self):
        """Detached conservative budget, not an allocated or persisted free map."""
        self._live();self._ensure_reservations()
        exact=self._checkpoint_plan is not None and self._checkpoint_plan['binding']==self._plan_binding()
        bound=2*self._reservation_logical
        return {'certificate_kind':'empty' if not self.active else ('exact_plan' if exact else 'upper_bound'),
                'reserved_upper_blocks':bound,'free_blocks':len(self._free),'cells':len(self._reservation_cells),
                'dirty_ancestors':len(self._reservation_ancestors),
                'tail_certified':not self.active or (self.generation<MAX_U64 and (exact or bound<=len(self._free)))}
    def _plan_binding(self,epoch=None,history=None):
        return (self.volume,self.generation,self.epoch if epoch is None else epoch,
                self.history if history is None else history,canonical(self.files_root),canonical(self.tokens_root))
    def _prepare_checkpoint_plan(self,*,dirty_files=None,dirty_tokens=None,epoch=None,history=None):
        """Compile and validate exact output without disk/live-allocator mutation.

        Overlays contain only candidate objects. The sorted heap iterator visits
        only the chosen free prefix; no arena/live-graph dictionary is copied.
        This recompiles the bounded outstanding window for each offered txn.
        """
        if self.generation==MAX_U64:raise StoreError('catalogue generation exhausted')
        self.stats['admission_plans']+=1
        sandbox=object.__new__(type(self));sandbox.__dict__=dict(self.__dict__)
        sandbox.stats=dict(self.stats);sandbox._writing_generation=self.generation+1;sandbox._checkpoint_plan=None
        sandbox.epoch=self.epoch if epoch is None else epoch
        sandbox.history=self.history if history is None else history
        sandbox._dirty_files=self._dirty_files if dirty_files is None else dirty_files
        sandbox._dirty_tokens=self._dirty_tokens if dirty_tokens is None else dirty_tokens
        sandbox._cache=ChainMap({},self._cache);sandbox._graph_cache=ChainMap({},self._graph_cache)
        sandbox._block_owner=ChainMap({},self._block_owner);sandbox._pending=set();sandbox._repair_records=[]
        free=iter(self._heap_order(self._free));allocations=[];writes=[]
        def staged_alloc(kind,body):
            if len(body)>PAGE_PAYLOAD:raise StoreError('object exceeds page payload')
            try:a,b=next(free),next(free)
            except StopIteration as exc:raise AdmissionRejected(errno.ENOSPC,'offered state lacks exact COW checkpoint headroom') from exc
            desc=[a,b,sandbox._writing_generation,kind,len(body),digest(body)];key=tuple(desc)
            sandbox._pending.add(key);allocations.append(key)
            for index in (a,b):
                if index in sandbox._block_owner:raise InvalidImage('planner selected an owned block')
                sandbox._block_owner[index]=key
            raw=pack(kind,body,sandbox._writing_generation,self.volume,fixed=BLOCK_SIZE)
            writes.extend((block_offset(index),raw) for index in (a,b))
            sandbox._cache[key]=body
            return desc
        sandbox._alloc_object=staged_alloc
        try:
            changes={path:None if value is None else sandbox._file_value(value) for path,value in sorted(sandbox._dirty_files.items())}
            files_root=sandbox._update_tree(self.files_root,'files',changes)
            tokens_root=sandbox._update_tree(self.tokens_root,'tokens',dict(sorted(sandbox._dirty_tokens.items())))
            cat={'format':FORMAT,'volume':self.volume,'epoch':sandbox.epoch,'history':sandbox.history,'files_root':files_root,'tokens_root':tokens_root}
            root=sandbox._put_json(K_CATALOG,cat)
            generation=sandbox._writing_generation
            seal={'generation':generation,'volume':self.volume,'pool_blocks':self.pool_blocks,'root':root}
            seal_raw=pack(K_SEAL,canonical(seal),generation,self.volume,fixed=SECTOR)
            sandbox._scan_graph(root,generation=generation,incremental=True)
        except AdmissionRejected:
            self.stats['admission_rejections']+=1;raise
        finally:
            del sandbox._alloc_object  # Break the sandbox/closure reference cycle.
            self.stats['graph_nodes_validated']=sandbox.stats['graph_nodes_validated']
            self.stats['incremental_validations']=sandbox.stats['incremental_validations']
            self.stats['admission_planned_blocks']+=len(writes)
        targets=tuple(range(4)) if self.generation==-1 else tuple(range((generation%2)*2,(generation%2)*2+2))
        return {'binding':self._plan_binding(sandbox.epoch,sandbox.history),'generation':generation,'epoch':sandbox.epoch,
                'history':sandbox.history,'files_root':files_root,'tokens_root':tokens_root,'root':root,'seal':seal,
                'objects':tuple(allocations),'dependency_writes':tuple(writes),
                'seal_writes':tuple((SEAL_OFFSETS[i],seal_raw) for i in targets),'targets':targets,
                'cache':dict(sandbox._cache.maps[0]),'edges':dict(sandbox._graph_cache.maps[0])}
    def checkpoint_plan(self,*,include_writes=False):
        """Return a detached exact publication summary; never writes or forces.

        `writes`, when requested, includes dependency pages followed by seals;
        force boundaries give the write counts after which fsync must occur.
        """
        self._live()
        plan=self._checkpoint_plan
        if plan is None or plan['binding']!=self._plan_binding():
            plan=self._prepare_checkpoint_plan()
            if self.writable:self._checkpoint_plan=plan
        dep=plan['dependency_writes'];all_writes=dep+plan['seal_writes']
        result={'epoch':plan['epoch'],'generation':plan['generation'],'history':plan['history'],
                'pool_blocks':self.pool_blocks,'physical_blocks':len(dep),'bytes_written':sum(len(raw) for _,raw in all_writes),
                'root_sha256':plan['root'][5],'force_boundaries':(len(dep),len(all_writes))}
        if include_writes:result['writes']=all_writes
        return result
    def checkpoint(self,initial=False):
        self._writable()
        if initial and self.generation!=-1:raise ValueError('initial checkpoint restricted to creation')
        plan=self._checkpoint_plan
        if plan is None or plan['binding']!=self._plan_binding():plan=self._prepare_checkpoint_plan()
        if not initial:
            self._ensure_reservations()
            if len(plan['dependency_writes'])>2*self._reservation_logical:
                self.fenced=True;raise InvalidImage('exact checkpoint exceeded admission upper bound')
        old_root=self.catalog_desc
        try:
            # Consume exactly the free prefix certified before acknowledgment.
            for key in plan['objects']:
                for index in key[:2]:
                    if heapq.heappop(self._free)!=index or index in self._block_owner:raise InvalidImage('checkpoint plan allocation binding changed')
                    self._block_owner[index]=key
                self._pending.add(key)
            self._cache.update(plan['cache']);self._graph_cache.update(plan['edges'])
            for off,raw in plan['dependency_writes']:self._pwrite(raw,off)
            self.stats['page_allocations']+=len(plan['dependency_writes'])
            self._acquire(plan['root']);self._sync()
            for off,raw in plan['seal_writes']:self._pwrite(raw,off)
            self._sync()
            # Publication is durable before old ownership can be retired.
            self.generation=plan['generation'];self.seal=plan['seal'];self.catalog_desc=plan['root']
            self.files_root=plan['files_root'];self.tokens_root=plan['tokens_root'];self.checkpoint_epoch=self.epoch
            self._selected_valid_slots=set(plan['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._checkpoint_plan=None
            self._reset_reservations()
            self.stats['checkpoints']+=1;self.stats['executed_plans']+=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=[];logical_changes={}
        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')
            logical_changes[path]=value
            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')
        if self.generation==MAX_U64:raise StoreError('catalogue generation exhausted before admission')
        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()
        self._ensure_reservations()
        proposal=self._reservation_preview(logical_changes,{token:[e,intent]});plan=None
        if proposal['physical_blocks']>len(self._free):
            self.stats['reservation_exact_fallbacks']+=1
            future_files=dict(self._dirty_files);future_files.update(logical_changes)
            future_tokens=dict(self._dirty_tokens);future_tokens[token]=[e,intent]
            try:
                plan=self._prepare_checkpoint_plan(dirty_files=future_files,dirty_tokens=future_tokens,epoch=e,history=digest(body))
            except AdmissionRejected:
                if not self.active:raise
                # The old accepted window is still bounded or exactly planned.
                self.stats['admission_pressure_checkpoints']+=1;self.checkpoint()
                self._ensure_reservations()
                proposal=self._reservation_preview(logical_changes,{token:[e,intent]})
                if proposal['physical_blocks']>len(self._free):
                    plan=self._prepare_checkpoint_plan(dirty_files=dict(logical_changes),dirty_tokens={token:[e,intent]},epoch=e,history=digest(body))
        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._reservation_adopt(proposal)
            self.active[e]={'body':body,'obj':obj,'digest':self.history};self._checkpoint_plan=plan;self.stats['capsule_batches']+=1
            if plan is None:self.stats['reservation_fast_accepts']+=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,
            'admission':{**self.admission_reservation(),
                         'planned_blocks':None if self._checkpoint_plan is None else len(self._checkpoint_plan['dependency_writes'])},'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())