File size: 30,794 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
import errno
import importlib.util
import os
from pathlib import Path
import tempfile
import unittest
from unittest import mock

SPEC=importlib.util.spec_from_file_location('pagefs',Path(__file__).resolve().parents[1]/'pagefs.py')
m=importlib.util.module_from_spec(SPEC);SPEC.loader.exec_module(m)

class EngineTests(unittest.TestCase):
    def setUp(self):
        self.tmp=tempfile.TemporaryDirectory();self.path=Path(self.tmp.name)/'image'
    def tearDown(self):self.tmp.cleanup()
    def create(self,files=None,pool=512):return m.PageStore.create(self.path,initial_files=files,pool_blocks=pool)
    def damage(self,offset,n):
        with open(self.path,'r+b',buffering=0) as f:f.seek(offset);f.write(bytes(n));os.fsync(f.fileno())
    def test_genesis_and_fixed_capacity(self):
        with self.create({'/a':b'x'}) as s:
            self.assertEqual(s.get('/a'),b'x');self.assertEqual(s.epoch,0)
            self.assertEqual(os.stat(self.path).st_size,m.POOL_START+512*m.BLOCK_SIZE)
            self.assertEqual(len(s._live_blocks)+len(s._free),s.pool_blocks)
    def test_transaction_one_force_two_writes(self):
        with self.create() as s:
            s.reset_stats();self.assertEqual(s.transact({'/a':b'x','/b':b'y'},'tx'),1)
            self.assertEqual(s.stats['write_calls'],2);self.assertEqual(s.stats['fsync_calls'],1)
            self.assertEqual(s.stats['page_allocations'],0)
    def test_multi_path_delete_and_reopen(self):
        with self.create({'/a':b'old','/b':b'b'}) as s:
            s.transact({'/a':b'new','/b':None,'/missing':None},'one')
        with m.PageStore(self.path,writable=False) as s:
            self.assertEqual(s.files(),['/a']);self.assertEqual(s.get('/a'),b'new');self.assertEqual(s.query('one')['epoch'],1)
    def test_retry_is_no_io_and_survives_checkpoint(self):
        with self.create() as s:
            s.transact({'/a':b'x'},'same');s.checkpoint();s.reset_stats()
            self.assertEqual(s.transact({'/a':b'x'},'same'),1);self.assertEqual(s.stats['write_calls'],0)
            with self.assertRaises(m.TransactionConflict):s.transact({'/a':b'y'},'same')
        with m.PageStore(self.path) as s:self.assertEqual(s.transact({'/a':b'x'},'same'),1)
    def test_unicode_escaped_keys(self):
        data={'/雪/"name\n':b'\x00\xff','/emoji😀':b''}
        with self.create(data) as s:s.checkpoint()
        with m.PageStore(self.path,writable=False) as s:
            for key,value in data.items():self.assertEqual(s.get(key),value)
    def test_invalid_creation_inputs_have_no_file(self):
        for files in ({'/a':bytes(m.MAX_CAPSULE+1)},{'relative':b'a'},{'/a':'str'}):
            with self.assertRaises((ValueError,TypeError)):self.create(files)
            self.assertFalse(self.path.exists())
    def test_overescaped_path_rejected_before_ack(self):
        with self.create() as s:
            s.reset_stats()
            with self.assertRaises(ValueError):s.transact({'/'+chr(1)*1000:b'x'},'bad')
            self.assertEqual(s.stats['write_calls'],0)
    def test_volatile_caches_match_exact_live_identities(self):
        with self.create(pool=256) as s:
            for i in range(60):
                s.transact({'/a':str(i).encode()},f't{i}');s.checkpoint()
                self.assertEqual(set(s._cache),set(s._refs))
                self.assertEqual(set(s._graph_cache),set(s._refs))
    def test_initial_largest_value(self):
        raw=bytes(range(256))*(m.MAX_CAPSULE//256)+bytes(m.MAX_CAPSULE%256)
        with self.create({'/large':raw}):pass
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/large'),raw)
    def test_capsule_size_rejected_without_io(self):
        with self.create() as s:
            s.reset_stats()
            with self.assertRaises(ValueError):s.transact({'/a':bytes(m.MAX_CAPSULE)},'large')
            self.assertEqual(s.stats['write_calls'],0);self.assertFalse(s.fenced)
    def test_inline_boundary_and_blob(self):
        for size in (0,1,255,256,257,m.PAGE_PAYLOAD,m.PAGE_PAYLOAD+1,30000):
            with self.subTest(size=size):
                with self.create() as s:
                    value=bytes([size%256])*size;s.transact({'/a':value},'one');s.checkpoint()
                with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),value)
                self.path.unlink()
    def test_tree_splits_and_delete_preserve_neighbors(self):
        files={f'/f{i}':bytes([i%256])*128 for i in range(300)}
        with self.create(files,pool=1024) as s:
            s.transact({'/f155':None,'/f156':b'changed'},'one');s.checkpoint()
        files.pop('/f155');files['/f156']=b'changed'
        with m.PageStore(self.path,writable=False) as s:
            self.assertEqual(s.files(),sorted(files))
            for key,value in files.items():self.assertEqual(s.get(key),value)
    def test_unchanged_subtree_reused(self):
        with self.create({f'/f{i}':bytes(128) for i in range(300)},pool=1024) as s:
            old=m.unpack_json(s._read_object(s.files_root,m.K_TRIE))['children']
            s.transact({'/f1':b'new'},'one');s.checkpoint()
            new=m.unpack_json(s._read_object(s.files_root,m.K_TRIE))['children']
            nib=m.hash_key('/f1')[0]
            for key in old:
                if key!=nib:self.assertEqual(old[key],new[key])
    def test_cold_blobs_not_redecoded_during_checkpoint(self):
        with self.create({f'/f{i}':bytes([i])*4000 for i in range(32)},pool=1024) as s:
            s.transact({'/new':b'x'},'one')
            original=m.unb64;calls=[]
            def counted(value):calls.append(len(value));return original(value)
            with mock.patch.object(m,'unb64',counted):s.checkpoint()
            self.assertLess(max(calls,default=0),100)
    def test_automatic_pressure_checkpoint(self):
        with self.create() as s:
            for i in range(65):s.transact({'/a':str(i).encode()},f't{i}')
            self.assertEqual(s.checkpoint_epoch,64);self.assertEqual(len(s.active),1)
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.epoch,65);self.assertEqual(s.get('/a'),b'64')
    def test_reuse_keeps_file_bounded(self):
        with self.create(pool=256) as s:
            size=os.stat(self.path).st_size
            for i in range(300):
                s.transact({'/a':bytes([i%256])*1000},f't{i}')
                if i%20==19:s.checkpoint()
            self.assertGreater(s.stats['reclaimed_blocks'],256)
            self.assertEqual(os.stat(self.path).st_size,size)
            self.assertFalse(set(s._free)&s._live_blocks)
            self.assertEqual(len(set(s._free))+len(s._live_blocks),256)
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),bytes([299%256])*1000)
    def test_empty_checkpoint_and_reopen(self):
        with self.create() as s:
            for _ in range(5):self.assertEqual(s.checkpoint(),0)
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.epoch,0)
    def test_read_only_cannot_mutate(self):
        with self.create():pass
        with m.PageStore(self.path,writable=False) as s:
            with self.assertRaises(m.WriterFenced):s.transact({'/a':b'a'},'x')
            with self.assertRaises(m.WriterFenced):s.checkpoint()
    def test_single_pool_mirror_recovery_and_repair(self):
        with self.create({'/a':b'x'}) as s:root=list(s.catalog_desc)
        self.damage(m.block_offset(root[0]),m.BLOCK_SIZE)
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
        with m.PageStore(self.path) as s:self.assertGreater(s.stats['write_calls'],0)
        self.damage(m.block_offset(root[1]),m.BLOCK_SIZE)
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
    def test_both_newest_root_mirrors_block_fallback(self):
        with self.create({'/a':b'old'}) as s:
            s.transact({'/a':b'new'},'one');s.checkpoint();root=list(s.catalog_desc)
        for index in root[:2]:self.damage(m.block_offset(index),m.BLOCK_SIZE)
        with self.assertRaises(m.RecoveryBlocked):m.PageStore(self.path,writable=False)
    def test_capsule_mirror_repair(self):
        with self.create() as s:s.transact({'/a':b'x'},'one')
        self.damage(m.capsule_offset(1,0),m.SPAN)
        with m.PageStore(self.path) as s:self.assertEqual(s.get('/a'),b'x');self.assertGreater(s.stats['write_calls'],0)
        self.damage(m.capsule_offset(1,1),m.SPAN)
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
    def test_valid_header_without_payload_blocks(self):
        with self.create() as s:s.transact({'/a':b'x'},'one')
        for replica in range(2):self.damage(m.capsule_offset(1,replica)+m.HEADER.size,400)
        with self.assertRaises(m.RecoveryBlocked):m.PageStore(self.path,writable=False)
    def test_single_latest_seal_is_normalized(self):
        with self.create() as s:s.transact({'/a':b'x'},'one');s.checkpoint();generation=s.generation
        pair=range((generation%2)*2,(generation%2)*2+2)
        self.damage(m.SEAL_OFFSETS[list(pair)[0]],m.SECTOR)
        with m.PageStore(self.path) as s:self.assertEqual(len(s._selected_valid_slots),2)
    def test_dependency_failure_fences_and_preserves_ack(self):
        with self.create({'/a':b'old'}) as s:
            s.transact({'/a':b'new'},'one')
            with mock.patch.object(s,'_sync',side_effect=OSError('force failed')):
                with self.assertRaises(OSError):s.checkpoint()
            self.assertTrue(s.fenced)
            with self.assertRaises(m.WriterFenced):s.get('/a')
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'new');self.assertEqual(s.query('one')['epoch'],1)
    def test_publication_failure_fences_and_reopens(self):
        with self.create() as s:
            s.transact({'/a':b'x'},'one');original=s._pwrite
            def fail_seals(raw,off):
                if off in m.SEAL_OFFSETS:raise OSError('seal failed')
                original(raw,off)
            with mock.patch.object(s,'_pwrite',fail_seals):
                with self.assertRaises(OSError):s.checkpoint()
            self.assertTrue(s.fenced)
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
    def test_enospc_offer_rejected_before_ack(self):
        with self.create(pool=16) as s:
            s.reset_stats();before=self.path.read_bytes()
            with self.assertRaises(m.AdmissionRejected) as caught:s.transact({'/a':bytes(16000)},'not-ack')
            self.assertEqual(caught.exception.errno,errno.ENOSPC);self.assertFalse(s.fenced)
            self.assertEqual(s.epoch,0);self.assertIsNone(s.query('not-ack'))
            self.assertEqual(s.stats['write_calls'],0);self.assertEqual(before,self.path.read_bytes())
            s.transact({'/a':b'fits'},'ack');s.checkpoint()
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'fits');self.assertIsNotNone(s.query('ack'))
    def test_transaction_adoption_exception_fences(self):
        with self.create() as s:
            with mock.patch.object(s,'_apply',side_effect=RuntimeError('RAM failure')):
                with self.assertRaises(RuntimeError):s.transact({'/a':b'x'},'one')
            self.assertTrue(s.fenced)
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
    def test_minimum_epoch(self):
        with self.create():pass
        with self.assertRaises(m.RecoveryBlocked):m.PageStore(self.path,writable=False,minimum_epoch=1)
    def test_exclusive_writer(self):
        with self.create():
            with self.assertRaises(BlockingIOError):m.PageStore(self.path)
    def test_descriptor_future_birth_rejected(self):
        with self.create({'/a':b'x'}) as s:
            root=list(s.catalog_desc);root[2]+=1
            with self.assertRaises(m.InvalidImage):s._scan_graph(root)
    def test_generation_exhaustion_no_io(self):
        with self.create() as s:
            s.generation=m.MAX_U64;s.reset_stats()
            with self.assertRaises(m.StoreError):s.checkpoint()
            self.assertEqual(s.stats['write_calls'],0)
    def test_checkpoint_avoids_full_scan_and_pool_rebuild(self):
        with self.create({f'/f{i}':bytes(128) for i in range(500)},pool=1024) as s:
            s.transact({'/f1':b'changed'},'one');s.reset_stats();s.checkpoint()
            self.assertEqual(s.stats['full_graph_scans'],0)
            self.assertEqual(s.stats['pool_rebuilds'],0)
            self.assertEqual(s.stats['incremental_validations'],1)
            self.assertLess(s.stats['graph_nodes_validated'],20)
            self.assertLess(s.stats['refcount_steps'],100)
    def test_incremental_refcounts_equal_independent_full_graph(self):
        with self.create({f'/f{i}':bytes(128) for i in range(100)},pool=512) as s:
            for i in range(80):
                s.transact({f'/f{i%100}':None if i%3==0 else str(i).encode()},f't{i}')
                if i%8==7:
                    s.checkpoint()
                    _,blocks,_,_=s._scan_graph(s.catalog_desc)
                    self.assertEqual(blocks,s._live_blocks)
                    self.assertEqual(set(s._refs),set(s._graph_cache))
                    self.assertTrue(all(count==1 for count in s._refs.values()))
                    self.assertEqual(set(s._free),set(range(s.pool_blocks))-blocks)
    def test_candidate_and_selected_roots_pinned_before_publication(self):
        with self.create({'/a':bytes(8000)},pool=256) as s:
            old=set(s._live_blocks);s.transact({'/a':b'new'},'one')
            original=s._sync;calls=[]
            def observe():
                calls.append(set(s._live_blocks));self.assertTrue(old<=s._live_blocks)
                return original()
            with mock.patch.object(s,'_sync',observe):s.checkpoint()
            self.assertEqual(len(calls),2);self.assertGreater(len(calls[0]),len(s._live_blocks))
    def test_unreachable_reserved_allocation_is_released_after_publication(self):
        with self.create(pool=128) as s:
            s._writing_generation=s.generation+1
            orphan=s._alloc_object(m.K_DATA,b'orphan');s.checkpoint()
            self.assertNotIn(tuple(orphan),s._pending);self.assertNotIn(tuple(orphan),s._cache)
            self.assertTrue(set(orphan[:2])<=set(s._free))
    def test_reference_metadata_exception_fences_after_durable_publication(self):
        with self.create() as s:
            s.transact({'/a':b'x'},'one')
            with mock.patch.object(s,'_release',side_effect=RuntimeError('RAM reference failure')):
                with self.assertRaises(RuntimeError):s.checkpoint()
            self.assertTrue(s.fenced)
        with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
    def test_unchanged_subtree_family_context_rejected(self):
        with self.create({'/a':b'old'}) as s:
            old_files=s.files_root;original=m.PageStore._update_tree
            def wrong_family(instance,desc,family,changes,depth=0):
                return old_files if family=='tokens' else original(instance,desc,family,changes,depth)
            s.reset_stats()
            s.transact({'/a':b'new'},'bad');s.reset_stats()
            with mock.patch.object(m.PageStore,'_update_tree',wrong_family):
                with self.assertRaises(m.InvalidImage):s.checkpoint_plan()
            self.assertEqual(s.stats['write_calls'],0);self.assertEqual(s.epoch,1)
            self.assertEqual(s.get('/a'),b'new')
    def test_unchanged_blob_cannot_alias_another_file_owner(self):
        with self.create({'/a':bytes(8000)}) as s:
            value=m.unpack_json(s._read_object(s.files_root,m.K_TRIE))['entries']['/a'];s.reset_stats()
            s.transact({'/b':b'offer'},'bad');s.reset_stats()
            with mock.patch.object(m.PageStore,'_file_value',return_value=value):
                with self.assertRaises(m.InvalidImage):s.checkpoint_plan()
            self.assertEqual(s.stats['write_calls'],0);self.assertEqual(s.query('bad')['epoch'],1)
    def test_nonlive_stale_object_cannot_be_resurrected(self):
        with self.create({'/a':b'old'}) as s:
            stale=s.files_root;s.transact({'/a':b'new'},'one');s.checkpoint()
            self.assertNotIn(tuple(stale),s._refs);original=m.PageStore._update_tree
            def stale_files(instance,desc,family,changes,depth=0):
                return stale if family=='files' else original(instance,desc,family,changes,depth)
            s.reset_stats()
            s.transact({'/a':b'latest'},'two');s.reset_stats()
            with mock.patch.object(m.PageStore,'_update_tree',stale_files):
                with self.assertRaises(m.InvalidImage):s.checkpoint_plan()
            self.assertEqual(s.stats['write_calls'],0);self.assertEqual(s.get('/a'),b'latest')
    def test_recovery_builds_references_once(self):
        with self.create({'/a':bytes(8000)}) as s:s.transact({'/a':b'x'},'one');s.checkpoint()
        with m.PageStore(self.path) as s:
            self.assertEqual(s.stats['full_graph_scans'],1);self.assertEqual(s.stats['pool_rebuilds'],1)
            self.assertTrue(all(count==1 for count in s._refs.values()))
            s.transact({'/a':b'y'},'two');s.reset_stats();s.checkpoint()
            self.assertEqual(s.stats['full_graph_scans'],0);self.assertEqual(s.stats['pool_rebuilds'],0)
    def test_epoch_exhaustion_no_io(self):
        with self.create() as s:
            s.epoch=m.MAX_U64;s.reset_stats()
            with self.assertRaises(m.StoreError):s.transact({'/a':b'x'},'one')
            self.assertEqual(s.stats['write_calls'],0)

    def test_lazy_heap_order_is_exact_and_nondestructive(self):
        import heapq,random
        rng=random.Random(1345)
        for n in (0,1,2,7,100,1000):
            heap=rng.sample(range(10000),n);heapq.heapify(heap);before=list(heap)
            self.assertEqual(list(m.PageStore._heap_order(heap)),sorted(before));self.assertEqual(heap,before)
    def test_admission_and_plan_query_do_not_write_or_reserve(self):
        with self.create({'/a':b'old'}) as s:
            free=list(s._free);owners=dict(s._block_owner);refs=dict(s._refs);s.reset_stats()
            s.transact({'/a':b'new'},'offer')
            self.assertEqual(s._free,free);self.assertEqual(s._block_owner,owners);self.assertEqual(s._refs,refs)
            calls=s.stats['write_calls'];forces=s.stats['fsync_calls'];plans=s.stats['admission_plans']
            answer=s.checkpoint_plan(include_writes=True)
            self.assertGreater(answer['physical_blocks'],0)
            self.assertEqual(s.stats['write_calls'],calls);self.assertEqual(s.stats['fsync_calls'],forces)
            self.assertEqual(s.stats['admission_plans'],plans+1)
    def test_checkpoint_executes_exact_admitted_bytes_without_rebuild(self):
        with self.create({'/a':b'old'}) as s:
            s.transact({'/a':bytes(9000),'/b':b'inline'},'offer')
            plan=s.checkpoint_plan(include_writes=True);writes=[];boundaries=[];original_write=s._pwrite;original_sync=s._sync
            def write(raw,offset):writes.append((offset,bytes(raw)));return original_write(raw,offset)
            def sync():boundaries.append(len(writes));return original_sync()
            with mock.patch.object(s,'_prepare_checkpoint_plan',side_effect=AssertionError('must use admitted plan')):
                with mock.patch.object(s,'_pwrite',write),mock.patch.object(s,'_sync',sync):s.checkpoint()
            self.assertEqual(tuple(writes),plan['writes']);self.assertEqual(tuple(boundaries),plan['force_boundaries'])
            self.assertEqual(sum(len(raw) for _,raw in writes),plan['bytes_written'])
    def test_rejected_offer_drains_previous_certified_window(self):
        with self.create(pool=32) as s:
            s.transact({'/a':b'fits'},'ack');before=s.checkpoint_plan(include_writes=True)
            with self.assertRaises(m.AdmissionRejected):s.transact({'/b':bytes(45000)},'reject')
            self.assertEqual(s.get('/a'),b'fits');self.assertIsNone(s.query('reject'));s.checkpoint()
            self.assertFalse(s.fenced)
    def test_recovery_recompiles_exact_acked_tail(self):
        with self.create() as s:s.transact({'/a':bytes(8000)},'ack')
        with m.PageStore(self.path) as s:
            self.assertEqual(s.checkpoint_plan()['epoch'],1);s.checkpoint()
            self.assertEqual(s.get('/a'),bytes(8000));self.assertEqual(s.query('ack')['epoch'],1)
    def test_readonly_plan_query_has_no_writes(self):
        with self.create() as s:s.transact({'/a':b'x'},'ack')
        before=self.path.read_bytes()
        with m.PageStore(self.path,writable=False) as s:
            self.assertEqual(s.checkpoint_plan()['epoch'],1);self.assertEqual(s.stats['write_calls'],0)
        self.assertEqual(self.path.read_bytes(),before)
    def test_caller_dictionary_changes_do_not_change_admitted_intent(self):
        with self.create() as s:
            request={'/a':b'original'};preview=s._reservation_preview
            def changed(*args):request['/a']=b'changed-after-validation';return preview(*args)
            with mock.patch.object(s,'_reservation_preview',changed):s.transact(request,'ack')
            self.assertEqual(s.get('/a'),b'original');s.checkpoint();self.assertEqual(s.get('/a'),b'original')
    def test_admitted_plan_holds_after_multiple_overwrites(self):
        with self.create({'/a':b'initial'},pool=256) as s:
            for i in range(40):
                s.transact({'/a':bytes([i])*((i%5)*1000+10)},f'token-{i}')
                self.assertEqual(s.checkpoint_plan()['epoch'],i+1)
            s.checkpoint();self.assertEqual(s.get('/a'),bytes([39])*4010)
    def test_fast_admissions_do_not_compile_pending_window(self):
        with self.create({f'/f{i}':bytes(128) for i in range(200)},pool=1024) as s:
            s.reset_stats()
            with mock.patch.object(s,'_prepare_checkpoint_plan',side_effect=AssertionError('fast path recompiled')):
                for i in range(64):s.transact({f'/f{i}':bytes([i])*128},f'fast-{i}')
            summary=s.admission_reservation()
            self.assertEqual(summary['certificate_kind'],'upper_bound')
            self.assertTrue(summary['tail_certified']);self.assertEqual(s.stats['reservation_fast_accepts'],64)
            self.assertEqual(s.stats['admission_plans'],0)
            self.assertLessEqual(len(s._prepare_checkpoint_plan()['dependency_writes']),summary['reserved_upper_blocks'])
            s.checkpoint()
    def test_symbolic_bound_dominates_mixed_exact_plans(self):
        import random
        rng=random.Random(7047)
        with self.create({f'/f{i}':rng.randbytes(128) for i in range(300)},pool=2048) as s:
            for i in range(120):
                changes={f'/f{rng.randrange(350)}':None if i%9==0 else rng.randbytes((0,128,256,257,3992,8000)[i%6])}
                s.transact(changes,f'mixed-{i}')
                if i%7==0:
                    bound=s.admission_reservation()['reserved_upper_blocks']
                    actual=len(s._prepare_checkpoint_plan()['dependency_writes'])
                    self.assertLessEqual(actual,bound)
                if i%30==29:s.checkpoint()
    def test_blob_credit_is_replaced_not_accumulated(self):
        with self.create(pool=256) as s:
            s.transact({'/a':bytes(30000)},'big');large=s.admission_reservation()['reserved_upper_blocks']
            s.transact({'/a':b'small'},'small');small=s.admission_reservation()['reserved_upper_blocks']
            self.assertGreater(large,small+10)
            self.assertEqual(s._reservation_blob_pages['/a'],0);s.checkpoint()
    def test_loose_bound_uses_exact_fallback_without_false_refusal(self):
        initial={};used=set()
        for i in range(1000):
            key=f'/p{i:04d}/'+('x'*900);nib=m.hash_key(key)[0]
            if nib not in used:initial[key]=bytes(256);used.add(nib)
            if len(initial)==4:break
        with self.create(initial,pool=16) as s:
            self.assertEqual(len(s._free),4);key=next(iter(initial));s.reset_stats()
            s.transact({key:initial[key]},'same')
            self.assertEqual(s.stats['reservation_exact_fallbacks'],1)
            self.assertEqual(s.admission_reservation()['certificate_kind'],'exact_plan')
            self.assertGreater(s.admission_reservation()['reserved_upper_blocks'],len(s._free))
            self.assertEqual(s.checkpoint_plan()['physical_blocks'],4);s.checkpoint()
    def test_reservation_failure_does_not_adopt_proposal(self):
        import copy
        with self.create({'/a':b'old'},pool=256) as s:
            s.transact({'/a':b'accepted'},'one');before=copy.deepcopy(s._reservation_cells)
            bound=s._reservation_logical;s.reset_stats()
            with mock.patch.object(m.PageStore,'_budget_update',side_effect=MemoryError('symbolic OOM')):
                with self.assertRaises(MemoryError):s.transact({'/a':b'offer'},'two')
            self.assertEqual(s._reservation_cells,before);self.assertEqual(s._reservation_logical,bound)
            self.assertEqual(s.stats['write_calls'],0);self.assertIsNone(s.query('two'));self.assertFalse(s.fenced)
            s.checkpoint()
    def test_generation_exhaustion_rejects_fast_offer_without_io(self):
        with self.create(pool=256) as s:
            s.generation=m.MAX_U64;s.reset_stats()
            with self.assertRaises(m.StoreError):s.transact({'/a':b'no'},'exhausted')
            self.assertEqual(s.stats['write_calls'],0);self.assertEqual(s.epoch,0)
    def test_bound_reconstructed_after_reopen(self):
        with self.create({'/a':b'old'},pool=256) as s:
            s.transact({'/a':bytes(9000),'/b':b'new'},'accepted')
            bound=s.admission_reservation()['reserved_upper_blocks']
        with m.PageStore(self.path) as s:
            self.assertEqual(s.admission_reservation()['reserved_upper_blocks'],bound)
            self.assertLessEqual(s.checkpoint_plan()['physical_blocks'],bound);s.checkpoint()
    def test_format_maximum_reference_containers_fit(self):
        self.assertLessEqual(len(m.canonical({'family':'tokens','type':'branch','depth':63,'children':{n:m.BOUND_DESC for n in m.HEX}})),m.PAGE_PAYLOAD)
        self.assertLessEqual(len(m.canonical({'length':m.MAX_CAPSULE,'digest':'f'*64,'chunks':[m.BOUND_DESC]*17})),m.PAGE_PAYLOAD)
    def test_weighted_budget_never_serializes_nonempty_symbolic_leaf(self):
        real=m.canonical
        def guarded(obj):
            if isinstance(obj,dict) and obj.get('type')=='leaf' and obj.get('entries'):
                raise AssertionError('whole symbolic leaf serialized')
            return real(obj)
        with self.create(pool=2048) as store:
            with mock.patch.object(m,'canonical',side_effect=guarded), \
                 mock.patch.object(store,'_prepare_checkpoint_plan',side_effect=AssertionError('late exact plan')), \
                 mock.patch.object(store,'_reservation_count',side_effect=AssertionError('whole cell recounted')):
                for i in range(32):
                    store.transact({f'/new/{i:03d}/{j}':bytes([i])*128 for j in range(8)},f'weighted-{i}')
            bound=store.admission_reservation()['reserved_upper_blocks']
            self.assertGreater(store.stats['reservation_leaf_splits'],0)
            self.assertEqual(store.stats['reservation_fast_accepts'],32)
            self.assertLessEqual(len(store._prepare_checkpoint_plan()['dependency_writes']),bound)
            store.checkpoint()
    def test_equal_size_replacement_reuses_file_budget_identity(self):
        with self.create(pool=2048) as store:
            store.transact({f'/item/{i:03d}':bytes(128) for i in range(40)},'seed')
            anchor=store._reservation_route('files','/item/000')[0]
            previous=store._reservation_cells[anchor]['tree']
            store.transact({'/item/000':b'x'*128},'replace')
            self.assertIs(store._reservation_cells[anchor]['tree'],previous)
            store.checkpoint();self.assertEqual(store.get('/item/000'),b'x'*128)
    def test_partial_weighted_proposal_failure_preserves_accepted_tree(self):
        with self.create(pool=2048) as store:
            store.transact({'/old':b'accepted'},'accepted')
            before=dict(store._reservation_cells);budget=store._reservation_logical
            calls=0;update=store._budget_update
            def fail(family,node,key,weight,depth,hashed=None):
                nonlocal calls
                calls+=1
                if calls==2:raise MemoryError('second weighted edit')
                return update(family,node,key,weight,depth,hashed)
            store.reset_stats()
            with mock.patch.object(store,'_budget_update',side_effect=fail):
                with self.assertRaises(MemoryError):store.transact({'/new/1':b'a','/new/2':b'b'},'refused')
            self.assertEqual(store._reservation_cells,before);self.assertEqual(store._reservation_logical,budget)
            self.assertEqual(store.stats['write_calls'],0);self.assertEqual(store.epoch,1)
            self.assertIsNone(store.query('refused'));self.assertFalse(store.fenced)
            store.checkpoint()
    def test_weighted_leaf_byte_identity_for_escaped_published_values(self):
        paths=('/plain','/quote\"/line\n','/雪/😀','/'+chr(1)*500)
        with self.create(pool=1024) as store:
            for depth in (0,9,10,63,64):
                entries={path:{'inline':m.b64(bytes([i])*128)} for i,path in enumerate(paths)}
                weights={key:store._budget_published_weight('files',key,value) for key,value in entries.items()}
                predicted=store._budget_leaf_bytes('files',depth,weights,sum(weights.values()))
                self.assertEqual(predicted,len(m.canonical({'family':'files','type':'leaf','depth':depth,'entries':entries})))
            for epoch in (1,9,10,m.MAX_U64):
                token='receipt_09';value=[epoch,'a'*64]
                self.assertEqual(store._budget_published_weight('tokens',token,value),len(m.canonical(token))+1+len(m.canonical(value)))
            desc=[0,m.MAX_POOL_BLOCKS-1,m.MAX_U64,m.K_BLOB,m.PAGE_PAYLOAD,'f'*64]
            self.assertEqual(store._budget_published_weight('files',paths[2],{'blob':desc}),len(m.canonical(paths[2]))+1+len(m.canonical({'blob':desc})))
    def test_published_entry_weights_are_computed_once_per_cell(self):
        with self.create({'/same':bytes(128)},pool=512) as store:
            store.transact({'/same':b'a'*128},'first')
            with mock.patch.object(store,'_budget_published_weight',side_effect=AssertionError('published cell reweighted')):
                for i in range(12):store.transact({'/same':bytes([i])*128},f'overwrite-{i}')
            store.checkpoint()
if __name__=='__main__':unittest.main()