PureOne commited on
Commit
bbff072
·
verified ·
1 Parent(s): fa25917

Upload research package with Eve Uploader

Browse files
evidence/reuse_model.txt ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "all_suite_crash_erasure_checks": 71334,
3
+ "assumptions": [
4
+ "one serialized publisher; truthful dependency and publication forces",
5
+ "all pending dependency and seal records may independently remain old, persist new, or become invalid",
6
+ "zero or one additional detected logical-record erasure per evaluated image",
7
+ "two disjoint replicas of each live page; four seals in two banks",
8
+ "allocate outside current-root closure, active reader pins, and in-flight reservations",
9
+ "old current dependencies become reusable only after both new seals are forced",
10
+ "strict maximum complete-valid-seal election before dependency validation; no older fallback",
11
+ "uncertain sessions fenced and old I/O drained before a later session writes",
12
+ "idealized digest detection; no malicious rehashing, epochs never reused"
13
+ ],
14
+ "counterexamples": {
15
+ "failed_io_fence": "the model refuses publication from an uncertain writer; delayed old I/O is excluded by assumption",
16
+ "missing_dependency_force": "a complete higher-generation seal can name missing root/leaf pages",
17
+ "omitted_reader_pin": "latest root remains valid but reclaiming old-only pages destroys an active reader view",
18
+ "premature_old_root_reuse": "reuse current root after one new seal, then erase that seal: last acknowledged root cannot be read",
19
+ "premature_single_seal_ack": "ack=1 after one successor witness; one erasure recovers epoch0"
20
+ },
21
+ "model": "finite physical-page reuse with mirrored COW roots v1",
22
+ "no_space_result": "allocation refuses before any write when a disjoint candidate cannot fit",
23
+ "restart": {
24
+ "normalization_crash_erasure_checks": 45,
25
+ "scope": "one partial-publication restart and subsequent commit; no arbitrary restart tree or renewed unrepaired fault budget",
26
+ "subsequent_publication_crash_erasure_checks": 2025,
27
+ "unsafe_restart_counterexample": "overwrite old bank before repairing singleton latest bank; both replacements tear and one erasure removes last seal"
28
+ },
29
+ "scope": [
30
+ "three-page binary COW tree: mirrored root plus two mirrored leaves",
31
+ "a bounded address-indexed logical page pool is overwritten and reused inside the model; no actual page-device I/O",
32
+ "unchanged leaves share physical pages; old reader roots can remain pinned",
33
+ "uninterrupted finite commit traces and one targeted partial-publication/restart trace",
34
+ "no byte-level engine proof, storage hardware qualification, physical power cuts or exhaustive restart/repair tree",
35
+ "stale lower-generation seals may name reclaimed graphs; recovery is guaranteed within the bounded erasure model, not after every newer witness disappears"
36
+ ],
37
+ "suites": [
38
+ {
39
+ "checkpoint_images_with_unreadable_stale_root": 187,
40
+ "commits": 5,
41
+ "crash_erasure_checks": 675,
42
+ "crash_images": 675,
43
+ "fault_budget": 0,
44
+ "pair_allocation_disjointness_checks": 13,
45
+ "physical_page_reuses": 12,
46
+ "pinned_reader_checks": 270,
47
+ "pool_pages": 20,
48
+ "program_checkpoints": 45,
49
+ "scenario": "dirty_paths_with_pin"
50
+ },
51
+ {
52
+ "checkpoint_images_with_unreadable_stale_root": 187,
53
+ "commits": 5,
54
+ "crash_erasure_checks": 11353,
55
+ "crash_images": 675,
56
+ "fault_budget": 1,
57
+ "pair_allocation_disjointness_checks": 13,
58
+ "physical_page_reuses": 12,
59
+ "pinned_reader_checks": 4394,
60
+ "pool_pages": 20,
61
+ "program_checkpoints": 45,
62
+ "scenario": "dirty_paths_with_pin"
63
+ },
64
+ {
65
+ "checkpoint_images_with_unreadable_stale_root": 1706,
66
+ "commits": 3,
67
+ "crash_erasure_checks": 3321,
68
+ "crash_images": 3321,
69
+ "fault_budget": 0,
70
+ "pair_allocation_disjointness_checks": 12,
71
+ "physical_page_reuses": 12,
72
+ "pinned_reader_checks": 0,
73
+ "pool_pages": 20,
74
+ "program_checkpoints": 33,
75
+ "scenario": "multi_leaf_atomic"
76
+ },
77
+ {
78
+ "checkpoint_images_with_unreadable_stale_root": 1706,
79
+ "commits": 3,
80
+ "crash_erasure_checks": 53915,
81
+ "crash_images": 3321,
82
+ "fault_budget": 1,
83
+ "pair_allocation_disjointness_checks": 12,
84
+ "physical_page_reuses": 12,
85
+ "pinned_reader_checks": 0,
86
+ "pool_pages": 20,
87
+ "program_checkpoints": 33,
88
+ "scenario": "multi_leaf_atomic"
89
+ }
90
+ ],
91
+ "total_main_crash_erasure_checks": 69264,
92
+ "total_pinned_reader_checks": 4664,
93
+ "total_restart_crash_erasure_checks": 2070
94
+ }
evidence/review_all_tests.txt ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ test_binary_value_roundtrip_and_new_output_file (test_cli.CliTests.test_binary_value_roundtrip_and_new_output_file) ... ok
2
+ test_checkpoint_and_empty_value (test_cli.CliTests.test_checkpoint_and_empty_value) ... ok
3
+ test_export_digest_and_readonly_verification (test_cli.CliTests.test_export_digest_and_readonly_verification) ... ok
4
+ test_init_refuses_existing_image (test_cli.CliTests.test_init_refuses_existing_image) ... ok
5
+ test_invalid_transaction_preserves_whole_image (test_cli.CliTests.test_invalid_transaction_preserves_whole_image) ... ok
6
+ test_missing_get_does_not_create_output (test_cli.CliTests.test_missing_get_does_not_create_output) ... ok
7
+ test_multi_key_transaction_and_delete_are_atomic_requests (test_cli.CliTests.test_multi_key_transaction_and_delete_are_atomic_requests) ... ok
8
+ test_plan_is_readonly_and_reports_force_boundaries (test_cli.CliTests.test_plan_is_readonly_and_reports_force_boundaries) ... ok
9
+ test_retry_conflict_and_receipt_persistence (test_cli.CliTests.test_retry_conflict_and_receipt_persistence) ... ok
10
+ test_zipapp_runs_outside_source_tree_without_pythonpath (test_cli.CliTests.test_zipapp_runs_outside_source_tree_without_pythonpath) ... ok
11
+ test_admission_and_plan_query_do_not_write_or_reserve (test_engine.EngineTests.test_admission_and_plan_query_do_not_write_or_reserve) ... ok
12
+ test_admitted_plan_holds_after_multiple_overwrites (test_engine.EngineTests.test_admitted_plan_holds_after_multiple_overwrites) ... ok
13
+ test_automatic_pressure_checkpoint (test_engine.EngineTests.test_automatic_pressure_checkpoint) ... ok
14
+ test_blob_credit_is_replaced_not_accumulated (test_engine.EngineTests.test_blob_credit_is_replaced_not_accumulated) ... ok
15
+ test_both_newest_root_mirrors_block_fallback (test_engine.EngineTests.test_both_newest_root_mirrors_block_fallback) ... ok
16
+ test_bound_reconstructed_after_reopen (test_engine.EngineTests.test_bound_reconstructed_after_reopen) ... ok
17
+ test_caller_dictionary_changes_do_not_change_admitted_intent (test_engine.EngineTests.test_caller_dictionary_changes_do_not_change_admitted_intent) ... ok
18
+ test_candidate_and_selected_roots_pinned_before_publication (test_engine.EngineTests.test_candidate_and_selected_roots_pinned_before_publication) ... ok
19
+ test_capsule_mirror_repair (test_engine.EngineTests.test_capsule_mirror_repair) ... ok
20
+ test_capsule_size_rejected_without_io (test_engine.EngineTests.test_capsule_size_rejected_without_io) ... ok
21
+ test_checkpoint_avoids_full_scan_and_pool_rebuild (test_engine.EngineTests.test_checkpoint_avoids_full_scan_and_pool_rebuild) ... ok
22
+ test_checkpoint_executes_exact_admitted_bytes_without_rebuild (test_engine.EngineTests.test_checkpoint_executes_exact_admitted_bytes_without_rebuild) ... ok
23
+ test_cold_blobs_not_redecoded_during_checkpoint (test_engine.EngineTests.test_cold_blobs_not_redecoded_during_checkpoint) ... ok
24
+ test_dependency_failure_fences_and_preserves_ack (test_engine.EngineTests.test_dependency_failure_fences_and_preserves_ack) ... ok
25
+ test_descriptor_future_birth_rejected (test_engine.EngineTests.test_descriptor_future_birth_rejected) ... ok
26
+ test_empty_checkpoint_and_reopen (test_engine.EngineTests.test_empty_checkpoint_and_reopen) ... ok
27
+ test_enospc_offer_rejected_before_ack (test_engine.EngineTests.test_enospc_offer_rejected_before_ack) ... ok
28
+ test_epoch_exhaustion_no_io (test_engine.EngineTests.test_epoch_exhaustion_no_io) ... ok
29
+ test_equal_size_replacement_reuses_file_budget_identity (test_engine.EngineTests.test_equal_size_replacement_reuses_file_budget_identity) ... ok
30
+ test_exclusive_writer (test_engine.EngineTests.test_exclusive_writer) ... ok
31
+ test_fast_admissions_do_not_compile_pending_window (test_engine.EngineTests.test_fast_admissions_do_not_compile_pending_window) ... ok
32
+ test_format_maximum_reference_containers_fit (test_engine.EngineTests.test_format_maximum_reference_containers_fit) ... ok
33
+ test_generation_exhaustion_no_io (test_engine.EngineTests.test_generation_exhaustion_no_io) ... ok
34
+ test_generation_exhaustion_rejects_fast_offer_without_io (test_engine.EngineTests.test_generation_exhaustion_rejects_fast_offer_without_io) ... ok
35
+ test_genesis_and_fixed_capacity (test_engine.EngineTests.test_genesis_and_fixed_capacity) ... ok
36
+ test_incremental_refcounts_equal_independent_full_graph (test_engine.EngineTests.test_incremental_refcounts_equal_independent_full_graph) ... ok
37
+ test_initial_largest_value (test_engine.EngineTests.test_initial_largest_value) ... ok
38
+ test_inline_boundary_and_blob (test_engine.EngineTests.test_inline_boundary_and_blob) ... ok
39
+ test_invalid_creation_inputs_have_no_file (test_engine.EngineTests.test_invalid_creation_inputs_have_no_file) ... ok
40
+ test_lazy_heap_order_is_exact_and_nondestructive (test_engine.EngineTests.test_lazy_heap_order_is_exact_and_nondestructive) ... ok
41
+ test_loose_bound_uses_exact_fallback_without_false_refusal (test_engine.EngineTests.test_loose_bound_uses_exact_fallback_without_false_refusal) ... ok
42
+ test_minimum_epoch (test_engine.EngineTests.test_minimum_epoch) ... ok
43
+ test_multi_path_delete_and_reopen (test_engine.EngineTests.test_multi_path_delete_and_reopen) ... ok
44
+ test_nonlive_stale_object_cannot_be_resurrected (test_engine.EngineTests.test_nonlive_stale_object_cannot_be_resurrected) ... ok
45
+ test_overescaped_path_rejected_before_ack (test_engine.EngineTests.test_overescaped_path_rejected_before_ack) ... ok
46
+ test_partial_weighted_proposal_failure_preserves_accepted_tree (test_engine.EngineTests.test_partial_weighted_proposal_failure_preserves_accepted_tree) ... ok
47
+ test_publication_failure_fences_and_reopens (test_engine.EngineTests.test_publication_failure_fences_and_reopens) ... ok
48
+ test_published_entry_weights_are_computed_once_per_cell (test_engine.EngineTests.test_published_entry_weights_are_computed_once_per_cell) ... ok
49
+ test_read_only_cannot_mutate (test_engine.EngineTests.test_read_only_cannot_mutate) ... ok
50
+ test_readonly_plan_query_has_no_writes (test_engine.EngineTests.test_readonly_plan_query_has_no_writes) ... ok
51
+ test_recovery_builds_references_once (test_engine.EngineTests.test_recovery_builds_references_once) ... ok
52
+ test_recovery_recompiles_exact_acked_tail (test_engine.EngineTests.test_recovery_recompiles_exact_acked_tail) ... ok
53
+ test_reference_metadata_exception_fences_after_durable_publication (test_engine.EngineTests.test_reference_metadata_exception_fences_after_durable_publication) ... ok
54
+ test_rejected_offer_drains_previous_certified_window (test_engine.EngineTests.test_rejected_offer_drains_previous_certified_window) ... ok
55
+ test_reservation_failure_does_not_adopt_proposal (test_engine.EngineTests.test_reservation_failure_does_not_adopt_proposal) ... ok
56
+ test_retry_is_no_io_and_survives_checkpoint (test_engine.EngineTests.test_retry_is_no_io_and_survives_checkpoint) ... ok
57
+ test_reuse_keeps_file_bounded (test_engine.EngineTests.test_reuse_keeps_file_bounded) ... ok
58
+ test_single_latest_seal_is_normalized (test_engine.EngineTests.test_single_latest_seal_is_normalized) ... ok
59
+ test_single_pool_mirror_recovery_and_repair (test_engine.EngineTests.test_single_pool_mirror_recovery_and_repair) ... ok
60
+ test_symbolic_bound_dominates_mixed_exact_plans (test_engine.EngineTests.test_symbolic_bound_dominates_mixed_exact_plans) ... ok
61
+ test_transaction_adoption_exception_fences (test_engine.EngineTests.test_transaction_adoption_exception_fences) ... ok
62
+ test_transaction_one_force_two_writes (test_engine.EngineTests.test_transaction_one_force_two_writes) ... ok
63
+ test_tree_splits_and_delete_preserve_neighbors (test_engine.EngineTests.test_tree_splits_and_delete_preserve_neighbors) ... ok
64
+ test_unchanged_blob_cannot_alias_another_file_owner (test_engine.EngineTests.test_unchanged_blob_cannot_alias_another_file_owner) ... ok
65
+ test_unchanged_subtree_family_context_rejected (test_engine.EngineTests.test_unchanged_subtree_family_context_rejected) ... ok
66
+ test_unchanged_subtree_reused (test_engine.EngineTests.test_unchanged_subtree_reused) ... ok
67
+ test_unicode_escaped_keys (test_engine.EngineTests.test_unicode_escaped_keys) ... ok
68
+ test_unreachable_reserved_allocation_is_released_after_publication (test_engine.EngineTests.test_unreachable_reserved_allocation_is_released_after_publication) ... ok
69
+ test_valid_header_without_payload_blocks (test_engine.EngineTests.test_valid_header_without_payload_blocks) ... ok
70
+ test_volatile_caches_match_exact_live_identities (test_engine.EngineTests.test_volatile_caches_match_exact_live_identities) ... ok
71
+ test_weighted_budget_never_serializes_nonempty_symbolic_leaf (test_engine.EngineTests.test_weighted_budget_never_serializes_nonempty_symbolic_leaf) ... ok
72
+ test_weighted_leaf_byte_identity_for_escaped_published_values (test_engine.EngineTests.test_weighted_leaf_byte_identity_for_escaped_published_values) ... ok
73
+ test_admission_never_encodes_nonempty_leaf_after_weighted_cache_exists (test_reservation_review.ReservationReview.test_admission_never_encodes_nonempty_leaf_after_weighted_cache_exists) ... ok
74
+ test_bound_dominates_pure_exact_oracle_at_every_ack (test_reservation_review.ReservationReview.test_bound_dominates_pure_exact_oracle_at_every_ack) ... ok
75
+ test_entry_weight_formulas_match_actual_json_for_all_value_families (test_reservation_review.ReservationReview.test_entry_weight_formulas_match_actual_json_for_all_value_families) ... ok
76
+ test_failed_proposal_preserves_accepted_cells_and_certificate (test_reservation_review.ReservationReview.test_failed_proposal_preserves_accepted_cells_and_certificate) ... ok
77
+ test_global_descriptor_widths_and_fixed_records_fit (test_reservation_review.ReservationReview.test_global_descriptor_widths_and_fixed_records_fit) ... ok
78
+ test_last_generation_width_is_within_bound (test_reservation_review.ReservationReview.test_last_generation_width_is_within_bound) ... ok
79
+ test_loose_bound_calls_exact_fallback_and_accepts_real_fit (test_reservation_review.ReservationReview.test_loose_bound_calls_exact_fallback_and_accepts_real_fit) ... ok
80
+ test_only_affected_cell_objects_are_replaced (test_reservation_review.ReservationReview.test_only_affected_cell_objects_are_replaced) ... ok
81
+ test_readonly_replay_reconstructs_same_upper_bound (test_reservation_review.ReservationReview.test_readonly_replay_reconstructs_same_upper_bound) ... ok
82
+ test_retained_split_can_compact_on_restart_without_losing_feasibility (test_reservation_review.ReservationReview.test_retained_split_can_compact_on_restart_without_losing_feasibility) ... ok
83
+ test_roomy_admission_does_not_compile_whole_pending_window (test_reservation_review.ReservationReview.test_roomy_admission_does_not_compile_whole_pending_window) ... ok
84
+ test_symbolic_overflow_at_full_hash_depth_forces_exact_fallback (test_reservation_review.ReservationReview.test_symbolic_overflow_at_full_hash_depth_forces_exact_fallback) ... ok
85
+ test_weighted_leaf_size_equals_complete_canonical_payload (test_reservation_review.ReservationReview.test_weighted_leaf_size_equals_complete_canonical_payload) ... ok
86
+ test_checkpoint_replays_exact_admitted_writes_and_forces (test_review.AdmissionReview.test_checkpoint_replays_exact_admitted_writes_and_forces) ... ok
87
+ test_failed_dependency_force_preserves_ack_and_rebuilds_plan (test_review.AdmissionReview.test_failed_dependency_force_preserves_ack_and_rebuilds_plan) ... ok
88
+ test_failed_publication_force_still_recovers_acked_logical_state (test_review.AdmissionReview.test_failed_publication_force_still_recovers_acked_logical_state) ... ok
89
+ test_host_enospc_remains_an_io_failure_not_an_arena_promise (test_review.AdmissionReview.test_host_enospc_remains_an_io_failure_not_an_arena_promise) ... ok
90
+ test_legacy_acknowledged_but_undrainable_counterexample (test_review.AdmissionReview.test_legacy_acknowledged_but_undrainable_counterexample) ... ok
91
+ test_long_escaped_key_and_large_blob_are_prevalidated (test_review.AdmissionReview.test_long_escaped_key_and_large_blob_are_prevalidated) ... ok
92
+ test_partial_capsule_write_fences_and_recovery_still_has_feasible_plan (test_review.AdmissionReview.test_partial_capsule_write_fences_and_recovery_still_has_feasible_plan) ... ok
93
+ test_plan_is_byte_identical_after_replay_of_unsorted_input_and_coalescing (test_review.AdmissionReview.test_plan_is_byte_identical_after_replay_of_unsorted_input_and_coalescing) ... ok
94
+ test_plan_is_pure_and_public_summary_is_detached (test_review.AdmissionReview.test_plan_is_pure_and_public_summary_is_detached) ... ok
95
+ test_planning_memory_failure_is_before_capsule_and_preserves_old_plan (test_review.AdmissionReview.test_planning_memory_failure_is_before_capsule_and_preserves_old_plan) ... ok
96
+ test_refused_offer_does_not_write_capsule_or_fence (test_review.AdmissionReview.test_refused_offer_does_not_write_capsule_or_fence) ... ok
97
+ test_rejected_offer_may_checkpoint_old_tail_but_never_adds_its_epoch (test_review.AdmissionReview.test_rejected_offer_may_checkpoint_old_tail_but_never_adds_its_epoch) ... ok
98
+ test_reopen_acknowledged_window_has_executable_drain_plan (test_review.AdmissionReview.test_reopen_acknowledged_window_has_executable_drain_plan) ... ok
99
+ test_repeated_overwrites_coalesce_but_all_receipts_survive (test_review.AdmissionReview.test_repeated_overwrites_coalesce_but_all_receipts_survive) ... ok
100
+ test_retry_needs_no_fresh_admission_or_io (test_review.AdmissionReview.test_retry_needs_no_fresh_admission_or_io) ... ok
101
+ test_window_pressure_executes_prior_admitted_plan_before_capsule_reuse (test_review.AdmissionReview.test_window_pressure_executes_prior_admitted_plan_before_capsule_reuse) ... ok
102
+
103
+ ----------------------------------------------------------------------
104
+ Ran 101 tests in 2.987s
105
+
106
+ OK
evidence/sequences.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "passed": true,
3
+ "engine_source_sha256": "e22e219b85e4b2a777b295ecad616cf4ef400e0189d7d7583d14f432d89ed807",
4
+ "transactions": 2048,
5
+ "retry_assertions": 2048,
6
+ "reopens": 8,
7
+ "checkpoints": 32,
8
+ "pool_blocks": 1024,
9
+ "cumulative_physical_block_allocations": 5002,
10
+ "cumulative_reclaimed_blocks": 4458,
11
+ "final_live_blocks": 580,
12
+ "fixed_apparent_image_bytes": 12599296,
13
+ "final_file_count": 144,
14
+ "all_file_bytes_and_token_epochs_verified": true,
15
+ "claim": "finite real-file reuse trace, not indefinite capacity or hardware fault proof"
16
+ }
evidence/tests.txt ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ test_binary_value_roundtrip_and_new_output_file (test_cli.CliTests.test_binary_value_roundtrip_and_new_output_file) ... ok
2
+ test_checkpoint_and_empty_value (test_cli.CliTests.test_checkpoint_and_empty_value) ... ok
3
+ test_export_digest_and_readonly_verification (test_cli.CliTests.test_export_digest_and_readonly_verification) ... ok
4
+ test_init_refuses_existing_image (test_cli.CliTests.test_init_refuses_existing_image) ... ok
5
+ test_invalid_transaction_preserves_whole_image (test_cli.CliTests.test_invalid_transaction_preserves_whole_image) ... ok
6
+ test_missing_get_does_not_create_output (test_cli.CliTests.test_missing_get_does_not_create_output) ... ok
7
+ test_multi_key_transaction_and_delete_are_atomic_requests (test_cli.CliTests.test_multi_key_transaction_and_delete_are_atomic_requests) ... ok
8
+ test_plan_is_readonly_and_reports_force_boundaries (test_cli.CliTests.test_plan_is_readonly_and_reports_force_boundaries) ... ok
9
+ test_retry_conflict_and_receipt_persistence (test_cli.CliTests.test_retry_conflict_and_receipt_persistence) ... ok
10
+ test_zipapp_runs_outside_source_tree_without_pythonpath (test_cli.CliTests.test_zipapp_runs_outside_source_tree_without_pythonpath) ... ok
11
+ test_admission_and_plan_query_do_not_write_or_reserve (test_engine.EngineTests.test_admission_and_plan_query_do_not_write_or_reserve) ... ok
12
+ test_admitted_plan_holds_after_multiple_overwrites (test_engine.EngineTests.test_admitted_plan_holds_after_multiple_overwrites) ... ok
13
+ test_automatic_pressure_checkpoint (test_engine.EngineTests.test_automatic_pressure_checkpoint) ... ok
14
+ test_blob_credit_is_replaced_not_accumulated (test_engine.EngineTests.test_blob_credit_is_replaced_not_accumulated) ... ok
15
+ test_both_newest_root_mirrors_block_fallback (test_engine.EngineTests.test_both_newest_root_mirrors_block_fallback) ... ok
16
+ test_bound_reconstructed_after_reopen (test_engine.EngineTests.test_bound_reconstructed_after_reopen) ... ok
17
+ test_caller_dictionary_changes_do_not_change_admitted_intent (test_engine.EngineTests.test_caller_dictionary_changes_do_not_change_admitted_intent) ... ok
18
+ test_candidate_and_selected_roots_pinned_before_publication (test_engine.EngineTests.test_candidate_and_selected_roots_pinned_before_publication) ... ok
19
+ test_capsule_mirror_repair (test_engine.EngineTests.test_capsule_mirror_repair) ... ok
20
+ test_capsule_size_rejected_without_io (test_engine.EngineTests.test_capsule_size_rejected_without_io) ... ok
21
+ test_checkpoint_avoids_full_scan_and_pool_rebuild (test_engine.EngineTests.test_checkpoint_avoids_full_scan_and_pool_rebuild) ... ok
22
+ test_checkpoint_executes_exact_admitted_bytes_without_rebuild (test_engine.EngineTests.test_checkpoint_executes_exact_admitted_bytes_without_rebuild) ... ok
23
+ test_cold_blobs_not_redecoded_during_checkpoint (test_engine.EngineTests.test_cold_blobs_not_redecoded_during_checkpoint) ... ok
24
+ test_dependency_failure_fences_and_preserves_ack (test_engine.EngineTests.test_dependency_failure_fences_and_preserves_ack) ... ok
25
+ test_descriptor_future_birth_rejected (test_engine.EngineTests.test_descriptor_future_birth_rejected) ... ok
26
+ test_empty_checkpoint_and_reopen (test_engine.EngineTests.test_empty_checkpoint_and_reopen) ... ok
27
+ test_enospc_offer_rejected_before_ack (test_engine.EngineTests.test_enospc_offer_rejected_before_ack) ... ok
28
+ test_epoch_exhaustion_no_io (test_engine.EngineTests.test_epoch_exhaustion_no_io) ... ok
29
+ test_equal_size_replacement_reuses_file_budget_identity (test_engine.EngineTests.test_equal_size_replacement_reuses_file_budget_identity) ... ok
30
+ test_exclusive_writer (test_engine.EngineTests.test_exclusive_writer) ... ok
31
+ test_fast_admissions_do_not_compile_pending_window (test_engine.EngineTests.test_fast_admissions_do_not_compile_pending_window) ... ok
32
+ test_format_maximum_reference_containers_fit (test_engine.EngineTests.test_format_maximum_reference_containers_fit) ... ok
33
+ test_generation_exhaustion_no_io (test_engine.EngineTests.test_generation_exhaustion_no_io) ... ok
34
+ test_generation_exhaustion_rejects_fast_offer_without_io (test_engine.EngineTests.test_generation_exhaustion_rejects_fast_offer_without_io) ... ok
35
+ test_genesis_and_fixed_capacity (test_engine.EngineTests.test_genesis_and_fixed_capacity) ... ok
36
+ test_incremental_refcounts_equal_independent_full_graph (test_engine.EngineTests.test_incremental_refcounts_equal_independent_full_graph) ... ok
37
+ test_initial_largest_value (test_engine.EngineTests.test_initial_largest_value) ... ok
38
+ test_inline_boundary_and_blob (test_engine.EngineTests.test_inline_boundary_and_blob) ... ok
39
+ test_invalid_creation_inputs_have_no_file (test_engine.EngineTests.test_invalid_creation_inputs_have_no_file) ... ok
40
+ test_lazy_heap_order_is_exact_and_nondestructive (test_engine.EngineTests.test_lazy_heap_order_is_exact_and_nondestructive) ... ok
41
+ test_loose_bound_uses_exact_fallback_without_false_refusal (test_engine.EngineTests.test_loose_bound_uses_exact_fallback_without_false_refusal) ... ok
42
+ test_minimum_epoch (test_engine.EngineTests.test_minimum_epoch) ... ok
43
+ test_multi_path_delete_and_reopen (test_engine.EngineTests.test_multi_path_delete_and_reopen) ... ok
44
+ test_nonlive_stale_object_cannot_be_resurrected (test_engine.EngineTests.test_nonlive_stale_object_cannot_be_resurrected) ... ok
45
+ test_overescaped_path_rejected_before_ack (test_engine.EngineTests.test_overescaped_path_rejected_before_ack) ... ok
46
+ test_partial_weighted_proposal_failure_preserves_accepted_tree (test_engine.EngineTests.test_partial_weighted_proposal_failure_preserves_accepted_tree) ... ok
47
+ test_publication_failure_fences_and_reopens (test_engine.EngineTests.test_publication_failure_fences_and_reopens) ... ok
48
+ test_published_entry_weights_are_computed_once_per_cell (test_engine.EngineTests.test_published_entry_weights_are_computed_once_per_cell) ... ok
49
+ test_read_only_cannot_mutate (test_engine.EngineTests.test_read_only_cannot_mutate) ... ok
50
+ test_readonly_plan_query_has_no_writes (test_engine.EngineTests.test_readonly_plan_query_has_no_writes) ... ok
51
+ test_recovery_builds_references_once (test_engine.EngineTests.test_recovery_builds_references_once) ... ok
52
+ test_recovery_recompiles_exact_acked_tail (test_engine.EngineTests.test_recovery_recompiles_exact_acked_tail) ... ok
53
+ test_reference_metadata_exception_fences_after_durable_publication (test_engine.EngineTests.test_reference_metadata_exception_fences_after_durable_publication) ... ok
54
+ test_rejected_offer_drains_previous_certified_window (test_engine.EngineTests.test_rejected_offer_drains_previous_certified_window) ... ok
55
+ test_reservation_failure_does_not_adopt_proposal (test_engine.EngineTests.test_reservation_failure_does_not_adopt_proposal) ... ok
56
+ test_retry_is_no_io_and_survives_checkpoint (test_engine.EngineTests.test_retry_is_no_io_and_survives_checkpoint) ... ok
57
+ test_reuse_keeps_file_bounded (test_engine.EngineTests.test_reuse_keeps_file_bounded) ... ok
58
+ test_single_latest_seal_is_normalized (test_engine.EngineTests.test_single_latest_seal_is_normalized) ... ok
59
+ test_single_pool_mirror_recovery_and_repair (test_engine.EngineTests.test_single_pool_mirror_recovery_and_repair) ... ok
60
+ test_symbolic_bound_dominates_mixed_exact_plans (test_engine.EngineTests.test_symbolic_bound_dominates_mixed_exact_plans) ... ok
61
+ test_transaction_adoption_exception_fences (test_engine.EngineTests.test_transaction_adoption_exception_fences) ... ok
62
+ test_transaction_one_force_two_writes (test_engine.EngineTests.test_transaction_one_force_two_writes) ... ok
63
+ test_tree_splits_and_delete_preserve_neighbors (test_engine.EngineTests.test_tree_splits_and_delete_preserve_neighbors) ... ok
64
+ test_unchanged_blob_cannot_alias_another_file_owner (test_engine.EngineTests.test_unchanged_blob_cannot_alias_another_file_owner) ... ok
65
+ test_unchanged_subtree_family_context_rejected (test_engine.EngineTests.test_unchanged_subtree_family_context_rejected) ... ok
66
+ test_unchanged_subtree_reused (test_engine.EngineTests.test_unchanged_subtree_reused) ... ok
67
+ test_unicode_escaped_keys (test_engine.EngineTests.test_unicode_escaped_keys) ... ok
68
+ test_unreachable_reserved_allocation_is_released_after_publication (test_engine.EngineTests.test_unreachable_reserved_allocation_is_released_after_publication) ... ok
69
+ test_valid_header_without_payload_blocks (test_engine.EngineTests.test_valid_header_without_payload_blocks) ... ok
70
+ test_volatile_caches_match_exact_live_identities (test_engine.EngineTests.test_volatile_caches_match_exact_live_identities) ... ok
71
+ test_weighted_budget_never_serializes_nonempty_symbolic_leaf (test_engine.EngineTests.test_weighted_budget_never_serializes_nonempty_symbolic_leaf) ... ok
72
+ test_weighted_leaf_byte_identity_for_escaped_published_values (test_engine.EngineTests.test_weighted_leaf_byte_identity_for_escaped_published_values) ... ok
73
+ test_admission_never_encodes_nonempty_leaf_after_weighted_cache_exists (test_reservation_review.ReservationReview.test_admission_never_encodes_nonempty_leaf_after_weighted_cache_exists) ... ok
74
+ test_bound_dominates_pure_exact_oracle_at_every_ack (test_reservation_review.ReservationReview.test_bound_dominates_pure_exact_oracle_at_every_ack) ... ok
75
+ test_entry_weight_formulas_match_actual_json_for_all_value_families (test_reservation_review.ReservationReview.test_entry_weight_formulas_match_actual_json_for_all_value_families) ... ok
76
+ test_failed_proposal_preserves_accepted_cells_and_certificate (test_reservation_review.ReservationReview.test_failed_proposal_preserves_accepted_cells_and_certificate) ... ok
77
+ test_global_descriptor_widths_and_fixed_records_fit (test_reservation_review.ReservationReview.test_global_descriptor_widths_and_fixed_records_fit) ... ok
78
+ test_last_generation_width_is_within_bound (test_reservation_review.ReservationReview.test_last_generation_width_is_within_bound) ... ok
79
+ test_loose_bound_calls_exact_fallback_and_accepts_real_fit (test_reservation_review.ReservationReview.test_loose_bound_calls_exact_fallback_and_accepts_real_fit) ... ok
80
+ test_only_affected_cell_objects_are_replaced (test_reservation_review.ReservationReview.test_only_affected_cell_objects_are_replaced) ... ok
81
+ test_readonly_replay_reconstructs_same_upper_bound (test_reservation_review.ReservationReview.test_readonly_replay_reconstructs_same_upper_bound) ... ok
82
+ test_retained_split_can_compact_on_restart_without_losing_feasibility (test_reservation_review.ReservationReview.test_retained_split_can_compact_on_restart_without_losing_feasibility) ... ok
83
+ test_roomy_admission_does_not_compile_whole_pending_window (test_reservation_review.ReservationReview.test_roomy_admission_does_not_compile_whole_pending_window) ... ok
84
+ test_symbolic_overflow_at_full_hash_depth_forces_exact_fallback (test_reservation_review.ReservationReview.test_symbolic_overflow_at_full_hash_depth_forces_exact_fallback) ... ok
85
+ test_weighted_leaf_size_equals_complete_canonical_payload (test_reservation_review.ReservationReview.test_weighted_leaf_size_equals_complete_canonical_payload) ... ok
86
+ test_checkpoint_replays_exact_admitted_writes_and_forces (test_review.AdmissionReview.test_checkpoint_replays_exact_admitted_writes_and_forces) ... ok
87
+ test_failed_dependency_force_preserves_ack_and_rebuilds_plan (test_review.AdmissionReview.test_failed_dependency_force_preserves_ack_and_rebuilds_plan) ... ok
88
+ test_failed_publication_force_still_recovers_acked_logical_state (test_review.AdmissionReview.test_failed_publication_force_still_recovers_acked_logical_state) ... ok
89
+ test_host_enospc_remains_an_io_failure_not_an_arena_promise (test_review.AdmissionReview.test_host_enospc_remains_an_io_failure_not_an_arena_promise) ... ok
90
+ test_legacy_acknowledged_but_undrainable_counterexample (test_review.AdmissionReview.test_legacy_acknowledged_but_undrainable_counterexample) ... ok
91
+ test_long_escaped_key_and_large_blob_are_prevalidated (test_review.AdmissionReview.test_long_escaped_key_and_large_blob_are_prevalidated) ... ok
92
+ test_partial_capsule_write_fences_and_recovery_still_has_feasible_plan (test_review.AdmissionReview.test_partial_capsule_write_fences_and_recovery_still_has_feasible_plan) ... ok
93
+ test_plan_is_byte_identical_after_replay_of_unsorted_input_and_coalescing (test_review.AdmissionReview.test_plan_is_byte_identical_after_replay_of_unsorted_input_and_coalescing) ... ok
94
+ test_plan_is_pure_and_public_summary_is_detached (test_review.AdmissionReview.test_plan_is_pure_and_public_summary_is_detached) ... ok
95
+ test_planning_memory_failure_is_before_capsule_and_preserves_old_plan (test_review.AdmissionReview.test_planning_memory_failure_is_before_capsule_and_preserves_old_plan) ... ok
96
+ test_refused_offer_does_not_write_capsule_or_fence (test_review.AdmissionReview.test_refused_offer_does_not_write_capsule_or_fence) ... ok
97
+ test_rejected_offer_may_checkpoint_old_tail_but_never_adds_its_epoch (test_review.AdmissionReview.test_rejected_offer_may_checkpoint_old_tail_but_never_adds_its_epoch) ... ok
98
+ test_reopen_acknowledged_window_has_executable_drain_plan (test_review.AdmissionReview.test_reopen_acknowledged_window_has_executable_drain_plan) ... ok
99
+ test_repeated_overwrites_coalesce_but_all_receipts_survive (test_review.AdmissionReview.test_repeated_overwrites_coalesce_but_all_receipts_survive) ... ok
100
+ test_retry_needs_no_fresh_admission_or_io (test_review.AdmissionReview.test_retry_needs_no_fresh_admission_or_io) ... ok
101
+ test_window_pressure_executes_prior_admitted_plan_before_capsule_reuse (test_review.AdmissionReview.test_window_pressure_executes_prior_admitted_plan_before_capsule_reuse) ... ok
102
+
103
+ ----------------------------------------------------------------------
104
+ Ran 101 tests in 3.518s
105
+
106
+ OK
evidence/weighted_budget.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "passed": true,
3
+ "engine_source_sha256": "e22e219b85e4b2a777b295ecad616cf4ef400e0189d7d7583d14f432d89ed807",
4
+ "seed": 889104,
5
+ "mixed_updates": 4400,
6
+ "full_weight_shape_oracle_checks": 400,
7
+ "forced_common_prefix_digits": 50,
8
+ "value_cases": "empty, inline up to 256 bytes, maximum-width blob descriptor, deletion",
9
+ "key_cases": "ordinary ASCII, escaped control character, supplementary Unicode",
10
+ "scope": "pure weighted helper stress and fresh raw-JSON shape comparison; not storage I/O, hardware faults or a universal proof"
11
+ }
experiments/README.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Final release experiments
2
+
3
+ The runtime has one default engine: `../pagefs.py`. Frozen V5 and V7 code under
4
+ `baselines/` is present only for reproducible comparisons and compatibility
5
+ checks. These older engines are not selectable CLI modes.
6
+
7
+ ## Functional evidence
8
+
9
+ From the source root, run `python3 run_checks.py`. It checks the complete
10
+ unit/integration suite, actual checkpoint crash images, deterministic
11
+ mutation/reopen/retry trace, inherited logical reuse model, format exchange,
12
+ finite arena-admission sweep, and bound-versus-exact-compiler oracle. The
13
+ separate tools write their JSON result files locally and bind them to source
14
+ hashes. Logical model checks, actual byte-image checks and hardware power cuts
15
+ are different kinds of evidence; no hardware qualification is claimed.
16
+
17
+ The three-backend capacity sweep uses 240 configurations per backend, with
18
+ eight offers per configuration. V5 can acknowledge a state that later runs
19
+ out of logical checkpoint-arena addresses. The accepted-window invariant of
20
+ V7 and the final engine is checked by draining accepted state and validating
21
+ all surviving file bytes and exact receipt epochs after reopening. The bound
22
+ oracle calls the exact compiler without installing the resulting cached plan,
23
+ so it does not disguise an admission shortcut that never runs independently.
24
+
25
+ ## Frozen performance comparison
26
+
27
+ The reviewed final measurement uses:
28
+
29
+ ```bash
30
+ python3 experiments/benchmark_final.py --namespaces 4096 16384 65536 --operations 128 --trials 3 --pool-blocks 32768
31
+ ```
32
+
33
+ To repeat without replacing the supplied result file, add an output path:
34
+
35
+ ```bash
36
+ python3 experiments/benchmark_final.py --output rerun_benchmark_results.json
37
+ ```
38
+
39
+ The default has 63 trials: 54 single-key trials and nine separate bulk-append
40
+ trials. Each backend starts one of the three trials per workload. Every timed
41
+ interval includes transaction admission, automatic maintenance, persistence
42
+ calls and an explicit final checkpoint drain. Creation, opening and final
43
+ validation are excluded. Every file value and exact receipt epoch is checked
44
+ before and after read-only reopen; hashes must stay unchanged during timing.
45
+
46
+ The single-key workloads perform 128 durable transactions over existing
47
+ 4,096-, 16,384- and 65,536-file namespaces. Each value is 128 bytes. Hot-prefix
48
+ traffic selects existing keys whose SHA-256 starts with hexadecimal `0`;
49
+ uniform traffic selects from the full namespace using a fixed seed.
50
+
51
+ The structural stress workload starts with an empty namespace and performs
52
+ 64 atomic transactions, each adding 128 new keys with 128-byte values:
53
+ 8,192 logical key updates in total. Its transaction throughput and logical-key
54
+ throughput are both reported. They must not be substituted for the single-key
55
+ transaction throughput. This workload exposes growth of a pending reservation
56
+ cell anchored to an empty published trie.
57
+
58
+ Both source-bound engines and their baseline share the configured arena size.
59
+ Requested host-write bytes, apparent image length, filesystem-reported
60
+ allocation and physical NAND traffic are different quantities. The benchmark
61
+ records the first three where applicable and does not measure NAND traffic.
62
+
63
+ `RESULTS.md` contains the final table and interpretation. These are Python/POSIX
64
+ regular-file experiments; they provide no native NTFS result, no simulated
65
+ flush-latency claim and no physical power-cut qualification. The audit command
66
+ does not rerun or overwrite frozen performance measurements.
experiments/RESULTS.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Final release measurements
2
+
3
+ These source-bound results compare the complete V5, V7 and final V8 engines on Python 3.12.14 / Linux / overlay. Each trial includes admission, automatic maintenance, persistence and an explicit final checkpoint drain. Setup/open and final value/receipt validation are excluded. All 63 trials passed unchanged-source guards and exact contents/receipt validation. These are POSIX regular-file prototype measurements, not native NTFS results.
4
+
5
+ ## Single-key workloads
6
+
7
+ Each trial has 128 durable single-key transactions with 128-byte values and a 32,768-block arena. There are three trials per workload with rotated backend order. The table shows medians and ratios of medians.
8
+
9
+ | Initial files | Workload | V5 tx/s | V7 tx/s | V8 tx/s | V8/V7 | V8/V5 |
10
+ |---|---|---|---|---|---|---|
11
+ | 4,096 | Hot prefix | 2006.66 | 1600.22 | 1908.01 | 1.192x | 0.951x |
12
+ | 4,096 | Uniform | 1782.60 | 1418.28 | 1472.93 | 1.039x | 0.826x |
13
+ | 16,384 | Hot prefix | 2089.76 | 1413.31 | 1411.53 | 0.999x | 0.675x |
14
+ | 16,384 | Uniform | 1265.12 | 794.46 | 977.93 | 1.231x | 0.773x |
15
+ | 65,536 | Hot prefix | 1592.08 | 1138.89 | 1370.66 | 1.204x | 0.861x |
16
+ | 65,536 | Uniform | 1214.78 | 910.83 | 841.64 | 0.924x | 0.693x |
17
+
18
+ V8/V7 single-key throughput ranges from 0.924x to 1.231x. The 65,536-file uniform case is 7.6% lower than V7; the 16,384-file hot-prefix case is effectively equal in these three-trial medians. Against V5, V8 ranges from 0.675x to 0.951x, with a worst measured throughput deficit of 32.5%. V5 has the weaker arena-admission contract. These results support neither a universal speedup nor an NTFS-superiority claim.
19
+
20
+ All three engines request identical host-write bytes and perform 132 fsync calls in each single-key trial. Every V8 single-key trial has 128 fast accepts, zero exact fallbacks, two exact compiler calls and zero full-graph scans.
21
+
22
+ ## Separate growing-cell stress workload
23
+
24
+ This workload starts with an empty published namespace and performs 64 atomic transactions, each adding 128 new keys with 128-byte values: 8,192 logical key updates. It deliberately exposes growth of a pending reservation cell anchored to an empty root. Transaction throughput and logical-key throughput differ by 128 and must not be substituted for the single-key rates above. There are three trials per backend, with the same complete final-drain timing boundary.
25
+
26
+ | Engine | Durable atomic tx/s | Logical key updates/s | Final checkpoint ms |
27
+ |---|---|---|---|
28
+ | V5 | 186.96 | 23930.40 | 224.60 |
29
+ | V7 | 37.66 | 4820.00 | 247.06 |
30
+ | V8 | 135.38 | 17328.43 | 281.08 |
31
+
32
+ V8 improves 3.595x over V7 on this specific structural stress and reaches 0.724x V5 throughput. All three engines request identical host-write bytes and perform 66 fsync calls. V8 has 64 fast accepts, zero exact fallbacks, one exact compiler call and no full-graph scan. The gain demonstrates this workload's reduced reservation recounting, not a general filesystem frontier.
33
+
34
+ ## Interpretation and reproduction
35
+
36
+ The weighted persistent budget keeps encoded entry weights and leaf sums, copies the affected symbolic path, and caches subtree page counts. This removes repeated serialization and repartitioning of a growing pending cell. The single-key profile already showed much of the remaining time in actual checkpoint construction/validation and fsync, so ordinary-workload gains are more modest and some regressions remain.
37
+
38
+ Raw trials, latency samples, engine counters, allocation metadata, logical-workload digests and source hashes are in `benchmark_final_results.json`. Counter names are implementation-scoped: for example, `reservation_entry_encodings` counts initial published-leaf weights; a zero value for empty genesis does not mean newly offered keys required no encoding.
39
+
40
+ Run the frozen experiment from the source root:
41
+
42
+ ```bash
43
+ python3 experiments/benchmark_final.py --namespaces 4096 16384 65536 --operations 128 --trials 3 --pool-blocks 32768
44
+ ```
45
+
46
+ Add `--output rerun_benchmark_results.json` to preserve the supplied result. No simulated flush delay, direct IO, cache dropping, NAND traffic measurement or physical power-cut qualification is used. All live logical data remain in RAM.
47
+
48
+ Engine and benchmark hashes:
49
+
50
+ ```json
51
+ {
52
+ "benchmark": "6bdd994db6ab30d9a30e1e393534d18528218bfe4c2afc3f4a7fb5840f7b2f74",
53
+ "v5": "3685cd31ebf282050e26001439f3bd06b9cf3cff765ab7085399786c2f9616bd",
54
+ "v7": "a67c93290fd561eff480f84b483dee0b44833c694da9b96c5d830af00616b980",
55
+ "v8": "e22e219b85e4b2a777b295ecad616cf4ef400e0189d7d7583d14f432d89ed807"
56
+ }
57
+ ```
experiments/admission_results.json ADDED
The diff for this file is too large to render. See raw diff
 
experiments/baselines/v5.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """NYARION V fixed-pool immutable page-tree research image engine.
3
+
4
+ Regular POSIX files only. All logical values are held in RAM. Capsule commits
5
+ use one fsync; checkpoints copy changed trie paths and publish through two
6
+ protected seal banks. The fixed object pool is reclaimed by root reachability.
7
+ This is not a mounted filesystem or a hardware durability qualification.
8
+ """
9
+ from __future__ import annotations
10
+ import argparse,base64,errno,hashlib,heapq,json,os,re,stat,struct,sys,uuid
11
+ from pathlib import Path
12
+ try:
13
+ import fcntl
14
+ except ImportError:
15
+ fcntl=None
16
+
17
+ FORMAT=5
18
+ MAGIC=b'NYPAGES5'
19
+ SLOTS=64
20
+ SPAN=65536
21
+ SECTOR=512
22
+ BLOCK_SIZE=4096
23
+ SEAL_OFFSETS=(0,4096,8192,12288)
24
+ RING_START=16384
25
+ POOL_START=RING_START+2*SLOTS*SPAN
26
+ APPEND_START=POOL_START
27
+ DEFAULT_POOL_BLOCKS=16384
28
+ MAX_POOL_BLOCKS=1<<20
29
+ MAX_U64=(1<<64)-1
30
+ K_SEAL,K_CATALOG,K_TRIE,K_BLOB,K_DATA,K_CAPSULE=1,2,3,4,5,6
31
+ PREFIX=struct.Struct('>8sHHIQ16s32s')
32
+ HEADER=struct.Struct('>8sHHIQ16s32s32s')
33
+ PAGE_PAYLOAD=BLOCK_SIZE-HEADER.size
34
+ MAX_CAPSULE=SPAN-HEADER.size
35
+ INLINE_LIMIT=256
36
+ ZERO='0'*64
37
+ HEX32=re.compile(r'^[0-9a-f]{32}$')
38
+ HEX64=re.compile(r'^[0-9a-f]{64}$')
39
+ TOKEN=re.compile(r'^[A-Za-z0-9_.:-]{1,64}$')
40
+ HEX='0123456789abcdef'
41
+
42
+ class StoreError(Exception):pass
43
+ class InvalidImage(StoreError):pass
44
+ class RecoveryBlocked(StoreError):pass
45
+ class SplitIdentity(RecoveryBlocked):pass
46
+ class UnsupportedFormat(RecoveryBlocked):pass
47
+ class WriterFenced(StoreError):pass
48
+ class TransactionConflict(StoreError):pass
49
+
50
+ def canonical(obj):return json.dumps(obj,sort_keys=True,separators=(',',':'),ensure_ascii=True,allow_nan=False).encode('ascii')
51
+ def digest(raw):return hashlib.sha256(raw).hexdigest()
52
+ def uint(x,maximum=MAX_U64):return type(x) is int and 0<=x<=maximum
53
+ def hash_key(key):return hashlib.sha256(key.encode('utf8')).hexdigest()
54
+ def path_key(path):
55
+ 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('/')):
56
+ raise ValueError('canonical absolute flat path key required')
57
+ return path
58
+ def token_key(token):
59
+ if not isinstance(token,str) or not TOKEN.fullmatch(token):raise ValueError('safe ASCII token required')
60
+ return token
61
+ def b64(raw):return base64.b64encode(raw).decode('ascii')
62
+ def unb64(value):
63
+ if not isinstance(value,str):raise InvalidImage('base64 type')
64
+ try:raw=base64.b64decode(value,validate=True)
65
+ except (ValueError,UnicodeError) as exc:raise InvalidImage('base64 encoding') from exc
66
+ if b64(raw)!=value:raise InvalidImage('noncanonical base64')
67
+ return raw
68
+ def unpack_json(raw):
69
+ def pairs(items):
70
+ d={}
71
+ for k,v in items:
72
+ if k in d:raise InvalidImage('duplicate JSON field')
73
+ d[k]=v
74
+ return d
75
+ try:obj=json.loads(raw.decode('ascii'),object_pairs_hook=pairs,parse_constant=lambda _:(_ for _ in ()).throw(ValueError()))
76
+ except (ValueError,UnicodeError,RecursionError) as exc:raise InvalidImage('invalid JSON') from exc
77
+ if not isinstance(obj,dict) or canonical(obj)!=raw:raise InvalidImage('noncanonical JSON object')
78
+ return obj
79
+ def pack(kind,payload,epoch,volume,fixed=None):
80
+ if not uint(epoch) or not isinstance(volume,str) or not HEX32.fullmatch(volume):raise ValueError('record identity')
81
+ prefix=PREFIX.pack(MAGIC,FORMAT,kind,len(payload),epoch,bytes.fromhex(volume),hashlib.sha256(payload).digest())
82
+ raw=prefix+hashlib.sha256(prefix).digest()+payload
83
+ if fixed is not None:
84
+ if len(raw)>fixed:raise ValueError('record exceeds reserved unit')
85
+ raw+=bytes(fixed-len(raw))
86
+ return raw
87
+ def read_header(raw,kind,maximum):
88
+ if len(raw)<HEADER.size:raise InvalidImage('short header')
89
+ magic,version,k,n,e,vol,h,check=HEADER.unpack_from(raw)
90
+ if magic!=MAGIC or k!=kind or hashlib.sha256(raw[:PREFIX.size]).digest()!=check:raise InvalidImage('header identity/checksum')
91
+ if version!=FORMAT:raise UnsupportedFormat('checksum-valid unsupported format')
92
+ if n>maximum:raise RecoveryBlocked('checksum-valid length exceeds bound')
93
+ return {'epoch':e,'volume':vol.hex(),'length':n,'digest':h.hex()}
94
+ def read_payload(raw,head):
95
+ body=raw[HEADER.size:HEADER.size+head['length']]
96
+ if len(body)!=head['length'] or digest(body)!=head['digest']:raise InvalidImage('payload length/digest')
97
+ return body
98
+ def capsule_offset(epoch,replica):return RING_START+(replica*SLOTS+epoch%SLOTS)*SPAN
99
+ def block_offset(index):return POOL_START+index*BLOCK_SIZE
100
+
101
+ class PageStore:
102
+ """Single serialized publisher; fixed-capacity mirrored object arena."""
103
+ def __init__(self,path,*,writable=True,minimum_epoch=None):
104
+ if fcntl is None:raise StoreError('POSIX flock required')
105
+ self.path=os.fspath(path);self.fd=None;self.writable=writable;self.fenced=False;self.reset_stats()
106
+ fd=os.open(self.path,(os.O_RDWR if writable else os.O_RDONLY)|getattr(os,'O_NOFOLLOW',0))
107
+ try:
108
+ if not stat.S_ISREG(os.fstat(fd).st_mode):raise InvalidImage('regular image file required')
109
+ fcntl.flock(fd,(fcntl.LOCK_EX if writable else fcntl.LOCK_SH)|fcntl.LOCK_NB);self.fd=fd
110
+ self._recover()
111
+ if minimum_epoch is not None and (not uint(minimum_epoch) or self.epoch<minimum_epoch):raise RecoveryBlocked('below caller minimum epoch')
112
+ if writable:self._reprotect()
113
+ except BaseException:os.close(fd);self.fd=None;raise
114
+ @classmethod
115
+ def create(cls,path,*,initial_files=None,pool_blocks=DEFAULT_POOL_BLOCKS):
116
+ if fcntl is None:raise StoreError('POSIX flock required')
117
+ if not uint(pool_blocks,MAX_POOL_BLOCKS) or pool_blocks<16:raise ValueError('pool_blocks must be 16..1048576')
118
+ if initial_files is not None and not isinstance(initial_files,dict):raise TypeError('initial_files dictionary required')
119
+ files={}
120
+ for key,value in (initial_files or {}).items():
121
+ path_key(key)
122
+ if not isinstance(value,bytes):raise TypeError('bytes values required')
123
+ if len(value)>MAX_CAPSULE:raise ValueError('initial value exceeds supported size')
124
+ files[key]=value
125
+ fd=os.open(os.fspath(path),os.O_RDWR|os.O_CREAT|os.O_EXCL|getattr(os,'O_NOFOLLOW',0),0o600)
126
+ self=cls.__new__(cls);self.path=os.fspath(path);self.fd=fd;self.writable=True;self.fenced=False;self.reset_stats()
127
+ try:
128
+ if not stat.S_ISREG(os.fstat(fd).st_mode):raise InvalidImage('regular image file required')
129
+ fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB);os.ftruncate(fd,POOL_START+pool_blocks*BLOCK_SIZE)
130
+ self.volume=uuid.uuid4().hex;self.pool_blocks=pool_blocks;self.generation=-1;self.epoch=0;self.checkpoint_epoch=0;self.history=ZERO
131
+ self.files_root=None;self.tokens_root=None;self.catalog_desc=None;self._files=files;self._tokens={};self.active={}
132
+ 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()
133
+ self._free=list(range(pool_blocks));heapq.heapify(self._free)
134
+ self._refs={};self._block_owner={};self._pending=set()
135
+ self.checkpoint(initial=True)
136
+ parent=os.open(str(Path(path).resolve().parent),os.O_RDONLY|getattr(os,'O_DIRECTORY',0))
137
+ try:os.fsync(parent)
138
+ finally:os.close(parent)
139
+ return self
140
+ except BaseException:self.close();raise
141
+ def __enter__(self):return self
142
+ def __exit__(self,*exc):self.close()
143
+ def close(self):
144
+ if self.fd is not None:os.close(self.fd);self.fd=None
145
+ def _live(self):
146
+ if self.fd is None:raise StoreError('closed')
147
+ if self.fenced:raise WriterFenced('uncertain state: close and recover')
148
+ def _writable(self):
149
+ self._live()
150
+ if not self.writable:raise WriterFenced('read-only image')
151
+ def reset_stats(self):
152
+ self.stats={'bytes_written':0,'write_calls':0,'fsync_calls':0,'capsule_batches':0,'checkpoints':0,
153
+ 'page_allocations':0,'reclaimed_blocks':0,'arena_live_blocks':0,'full_graph_scans':0,
154
+ 'incremental_validations':0,'graph_nodes_validated':0,'refcount_steps':0,'pool_rebuilds':0}
155
+ def _pwrite(self,raw,offset):
156
+ view=memoryview(raw)
157
+ while view:
158
+ n=os.pwrite(self.fd,view,offset)
159
+ if n<=0:raise OSError('zero-length write')
160
+ self.stats['bytes_written']+=n;self.stats['write_calls']+=1;view=view[n:];offset+=n
161
+ def _sync(self):self.stats['fsync_calls']+=1;os.fsync(self.fd)
162
+ def _valid_desc(self,desc,kind=None):
163
+ if not isinstance(desc,list) or len(desc)!=6:return False
164
+ a,b,g,k,n,h=desc
165
+ return (uint(a,self.pool_blocks-1) and uint(b,self.pool_blocks-1) and a!=b and uint(g) and
166
+ type(k) is int and k in (K_CATALOG,K_TRIE,K_BLOB,K_DATA) and (kind is None or k==kind)
167
+ and uint(n,PAGE_PAYLOAD) and isinstance(h,str) and bool(HEX64.fullmatch(h)))
168
+ def _alloc_object(self,kind,body):
169
+ if len(body)>PAGE_PAYLOAD:raise StoreError('object exceeds page payload')
170
+ if len(self._free)<2:raise OSError(errno.ENOSPC,'fixed object arena lacks COW checkpoint headroom')
171
+ a,b=heapq.heappop(self._free),heapq.heappop(self._free)
172
+ desc=[a,b,self._writing_generation,kind,len(body),digest(body)]
173
+ key=tuple(desc);self._pending.add(key)
174
+ for index in (a,b):
175
+ if index in self._block_owner:raise InvalidImage('allocator selected an owned block')
176
+ self._block_owner[index]=key
177
+ raw=pack(kind,body,self._writing_generation,self.volume,fixed=BLOCK_SIZE)
178
+ for index in (a,b):self._pwrite(raw,block_offset(index))
179
+ self._cache[tuple(desc)]=body;self.stats['page_allocations']+=2
180
+ return desc
181
+ def _read_object(self,desc,kind=None):
182
+ if not self._valid_desc(desc,kind):raise InvalidImage('object descriptor bounds/identity')
183
+ key=tuple(desc)
184
+ if key in self._cache:return self._cache[key]
185
+ good=None;bad=[]
186
+ for index in desc[:2]:
187
+ try:
188
+ raw=os.pread(self.fd,BLOCK_SIZE,block_offset(index));head=read_header(raw,desc[3],PAGE_PAYLOAD);body=read_payload(raw,head)
189
+ 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')
190
+ good=body
191
+ except (InvalidImage,OSError):bad.append(index)
192
+ if good is None:raise RecoveryBlocked('required object has no valid mirror; fallback refused')
193
+ expected=pack(desc[3],good,desc[2],self.volume,fixed=BLOCK_SIZE)
194
+ for index in bad:self._repair_records.append((block_offset(index),expected))
195
+ self._cache[key]=good;return good
196
+ def _put_json(self,kind,obj):return self._alloc_object(kind,canonical(obj))
197
+ def _file_value(self,data):
198
+ if len(data)>MAX_CAPSULE:raise ValueError('value exceeds supported size')
199
+ if len(data)<=INLINE_LIMIT:return {'inline':b64(data)}
200
+ chunks=[self._alloc_object(K_DATA,data[i:i+PAGE_PAYLOAD]) for i in range(0,len(data),PAGE_PAYLOAD)]
201
+ return {'blob':self._put_json(K_BLOB,{'length':len(data),'digest':digest(data),'chunks':chunks})}
202
+ def _build_tree(self,family,entries,depth=0):
203
+ if not entries:return None
204
+ leaf={'family':family,'type':'leaf','depth':depth,'entries':entries};raw=canonical(leaf)
205
+ if len(raw)<=PAGE_PAYLOAD:return self._alloc_object(K_TRIE,raw)
206
+ if depth>=64:raise StoreError('hash collision leaf exceeds page capacity')
207
+ groups={}
208
+ for key,value in entries.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
209
+ children={nib:self._build_tree(family,group,depth+1) for nib,group in groups.items()}
210
+ return self._put_json(K_TRIE,{'family':family,'type':'branch','depth':depth,'children':children})
211
+ def _update_tree(self,desc,family,changes,depth=0):
212
+ if not changes:return desc
213
+ if desc is None:return self._build_tree(family,{k:v for k,v in changes.items() if v is not None},depth)
214
+ node=unpack_json(self._read_object(desc,K_TRIE))
215
+ if node.get('family')!=family or node.get('depth')!=depth:raise InvalidImage('trie update identity/depth')
216
+ if node.get('type')=='leaf':
217
+ entries=dict(node['entries'])
218
+ for key,value in changes.items():
219
+ if value is None:entries.pop(key,None)
220
+ else:entries[key]=value
221
+ if entries==node['entries']:return desc
222
+ return self._build_tree(family,entries,depth)
223
+ if node.get('type')!='branch' or depth>=64:raise InvalidImage('trie branch update')
224
+ children=dict(node['children']);groups={}
225
+ for key,value in changes.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
226
+ for nib,group in groups.items():
227
+ child=self._update_tree(children.get(nib),family,group,depth+1)
228
+ if child is None:children.pop(nib,None)
229
+ else:children[nib]=child
230
+ if children==node['children']:return desc
231
+ if not children:return None
232
+ return self._put_json(K_TRIE,{'family':family,'type':'branch','depth':depth,'children':children})
233
+ def _scan_graph(self,catalog_desc,*,decode=False,generation=None,incremental=False):
234
+ """Full recovery validation, or validation of newly reserved objects only.
235
+
236
+ An unchanged pointer is accepted only when its complete identity is live
237
+ and its validated family/routing/owner context matches the new edge.
238
+ """
239
+ self.stats['incremental_validations' if incremental else 'full_graph_scans']+=1
240
+ seen=set();identities=set();files={};tokens={}
241
+ selected_generation=self.generation if generation is None else generation
242
+ if not self._valid_desc(catalog_desc,K_CATALOG) or catalog_desc[2]!=selected_generation:raise InvalidImage('catalogue birth differs from selected generation')
243
+ def known(desc,kind,context):
244
+ if not self._valid_desc(desc,kind) or desc[2]>selected_generation:raise InvalidImage('invalid reachable descriptor/birth')
245
+ if not incremental:return False
246
+ key=tuple(desc)
247
+ if any(self._block_owner.get(index)!=key for index in desc[:2]):raise InvalidImage('descriptor does not own its reserved/live blocks')
248
+ if self._refs.get(key,0):
249
+ info=self._graph_cache.get(key)
250
+ if info is None or info['context']!=context or info['max_epoch']>cat['epoch']:raise InvalidImage('unchanged object context/epoch mismatch')
251
+ return True
252
+ if key not in self._pending:raise InvalidImage('pointer is neither live nor reserved')
253
+ return False
254
+ def claim(desc,kind):
255
+ if not self._valid_desc(desc,kind) or desc[2]>selected_generation:raise InvalidImage('invalid reachable descriptor/birth')
256
+ if seen.intersection(desc[:2]):raise InvalidImage('object block alias/cycle')
257
+ seen.update(desc[:2]);identities.add(tuple(desc));self.stats['graph_nodes_validated']+=1
258
+ return self._read_object(desc,kind)
259
+ if incremental:
260
+ key=tuple(catalog_desc)
261
+ 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')
262
+ cat=unpack_json(claim(catalog_desc,K_CATALOG))
263
+ if (set(cat)!={'format','volume','epoch','history','files_root','tokens_root'} or type(cat['format']) is not int or cat['format']!=FORMAT or
264
+ 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')
265
+ if incremental and (cat['epoch']!=self.epoch or cat['history']!=self.history):raise InvalidImage('candidate logical head mismatch')
266
+ def remember(desc,links,context,max_epoch=0):
267
+ self._graph_cache[tuple(desc)]={'links':links,'context':context,'max_epoch':max_epoch}
268
+ def file_value(path,obj):
269
+ if not isinstance(obj,dict):raise InvalidImage('file value schema')
270
+ if set(obj)=={'inline'}:
271
+ data=unb64(obj['inline'])
272
+ if len(data)>INLINE_LIMIT:raise InvalidImage('oversized inline value')
273
+ return data,[]
274
+ if set(obj)!={'blob'}:raise InvalidImage('file encoding')
275
+ desc=obj['blob'];links=[(desc,K_BLOB)]
276
+ if known(desc,K_BLOB,('blob',path)):return None,links
277
+ manifest=unpack_json(claim(desc,K_BLOB))
278
+ if (set(manifest)!={'length','digest','chunks'} or not uint(manifest['length'],MAX_CAPSULE) or manifest['length']<=INLINE_LIMIT or
279
+ not isinstance(manifest['digest'],str) or not HEX64.fullmatch(manifest['digest']) or
280
+ not isinstance(manifest['chunks'],list) or len(manifest['chunks'])!=(manifest['length']+PAGE_PAYLOAD-1)//PAGE_PAYLOAD):raise InvalidImage('blob manifest')
281
+ parts=[]
282
+ for i,chunk in enumerate(manifest['chunks']):
283
+ context=('data',path,i)
284
+ if known(chunk,K_DATA,context):part=self._read_object(chunk,K_DATA)
285
+ else:
286
+ part=claim(chunk,K_DATA);remember(chunk,[],context)
287
+ if len(part)!=min(PAGE_PAYLOAD,manifest['length']-i*PAGE_PAYLOAD):raise InvalidImage('blob chunk length')
288
+ parts.append(part)
289
+ data=b''.join(parts)
290
+ if len(data)!=manifest['length'] or digest(data)!=manifest['digest']:raise InvalidImage('blob data mismatch')
291
+ remember(desc,[(chunk,K_DATA) for chunk in manifest['chunks']],('blob',path))
292
+ return data,links
293
+ def walk(desc,family,depth=0,prefix=''):
294
+ if desc is None:return
295
+ context=('trie',family,depth,prefix)
296
+ if known(desc,K_TRIE,context):return
297
+ node=unpack_json(claim(desc,K_TRIE))
298
+ 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')
299
+ links=[];max_epoch=0
300
+ if node.get('type')=='leaf':
301
+ if set(node)!={'family','type','depth','entries'} or not isinstance(node['entries'],dict) or not node['entries']:raise InvalidImage('leaf schema')
302
+ for key,value in node['entries'].items():
303
+ try:path_key(key) if family=='files' else token_key(key)
304
+ except ValueError as exc:raise InvalidImage('trie key') from exc
305
+ if not hash_key(key).startswith(prefix):raise InvalidImage('trie key routing')
306
+ if family=='files':
307
+ data,dependencies=file_value(key,value);links.extend(dependencies)
308
+ if decode:files[key]=data
309
+ else:
310
+ 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')
311
+ max_epoch=max(max_epoch,value[0])
312
+ if decode:tokens[key]=value
313
+ remember(desc,links,context,max_epoch);return
314
+ if (node.get('type')!='branch' or set(node)!={'family','type','depth','children'} or depth>=64 or
315
+ 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')
316
+ for nib,child in node['children'].items():
317
+ walk(child,family,depth+1,prefix+nib);links.append((child,K_TRIE))
318
+ max_epoch=max(max_epoch,self._graph_cache[tuple(child)]['max_epoch'])
319
+ remember(desc,links,context,max_epoch)
320
+ walk(cat['files_root'],'files');walk(cat['tokens_root'],'tokens')
321
+ remember(catalog_desc,[(desc,K_TRIE) for desc in (cat['files_root'],cat['tokens_root']) if desc is not None],('catalog',))
322
+ return cat,seen,files,tokens
323
+ def _acquire(self,desc):
324
+ """Activate outgoing edges only on the object's zero-to-one transition."""
325
+ key=tuple(desc);previous=self._refs.get(key,0);self._refs[key]=previous+1;self.stats['refcount_steps']+=1
326
+ if previous:return
327
+ info=self._graph_cache.get(key)
328
+ if info is None:raise InvalidImage('acquiring unvalidated object')
329
+ self._pending.discard(key);self._live_blocks.update(desc[:2])
330
+ for child,kind in info['links']:self._acquire(child)
331
+ def _release(self,desc):
332
+ """Retire outgoing edges and recycle blocks only at the last reference."""
333
+ key=tuple(desc);count=self._refs.get(key,0);self.stats['refcount_steps']+=1
334
+ if count<=0:raise InvalidImage('reference count underflow')
335
+ if count>1:self._refs[key]=count-1;return
336
+ del self._refs[key];info=self._graph_cache.pop(key)
337
+ for child,kind in info['links']:self._release(child)
338
+ self._cache.pop(key,None)
339
+ for index in desc[:2]:
340
+ if self._block_owner.pop(index,None)!=key:raise InvalidImage('releasing object ownership mismatch')
341
+ self._live_blocks.remove(index);heapq.heappush(self._free,index)
342
+ self.stats['reclaimed_blocks']+=2
343
+ def _discard_unreachable_reservations(self):
344
+ # Normally empty: retain this guard for allocations omitted by a builder.
345
+ for key in self._pending:
346
+ if self._refs.get(key,0):raise InvalidImage('live allocation remained reserved')
347
+ self._cache.pop(key,None);self._graph_cache.pop(key,None)
348
+ for index in key[:2]:
349
+ if self._block_owner.pop(index,None)!=key:raise InvalidImage('reservation ownership mismatch')
350
+ heapq.heappush(self._free,index)
351
+ self.stats['reclaimed_blocks']+=2
352
+ self._pending.clear()
353
+ def _validate_capsule(self,obj,head):
354
+ if (set(obj)!={'format','volume','epoch','parent','token','intent','changes'} or type(obj['format']) is not int or obj['format']!=FORMAT or
355
+ obj['volume']!=self.volume or obj['epoch']!=head['epoch'] or not uint(obj['epoch']) or not obj['epoch'] or
356
+ 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')
357
+ try:token_key(obj['token'])
358
+ except ValueError as exc:raise InvalidImage('capsule token') from exc
359
+ previous=None;items=[]
360
+ for change in obj['changes']:
361
+ if not isinstance(change,list) or len(change)!=2:raise InvalidImage('change schema')
362
+ path,value=change
363
+ try:path_key(path)
364
+ except ValueError as exc:raise InvalidImage('capsule path') from exc
365
+ if previous is not None and path<=previous:raise InvalidImage('unsorted/duplicate changes')
366
+ previous=path;raw=None if value is None else unb64(value)
367
+ items.append([path,None if raw is None else [len(raw),digest(raw)]])
368
+ if digest(canonical(items))!=obj['intent']:raise InvalidImage('intent mismatch')
369
+ return obj
370
+ def _apply(self,obj):
371
+ if obj['token'] in self._tokens:raise RecoveryBlocked('duplicate committed token')
372
+ for path,value in obj['changes']:
373
+ data=None if value is None else unb64(value)
374
+ if data is None:self._files.pop(path,None)
375
+ else:self._files[path]=data
376
+ self._dirty_files[path]=data
377
+ entry=[obj['epoch'],obj['intent']];self._tokens[obj['token']]=entry;self._dirty_tokens[obj['token']]=entry
378
+ def _recover(self):
379
+ self._cache={};self._graph_cache={};self._repair_records=[];seals=[];places=[]
380
+ for slot,off in enumerate(SEAL_OFFSETS):
381
+ try:
382
+ raw=os.pread(self.fd,SECTOR,off);head=read_header(raw,K_SEAL,SECTOR-HEADER.size);obj=unpack_json(read_payload(raw,head))
383
+ if (set(obj)!={'generation','volume','pool_blocks','root'} or not uint(obj['generation']) or obj['generation']!=head['epoch'] or
384
+ obj['volume']!=head['volume'] or not uint(obj['pool_blocks'],MAX_POOL_BLOCKS) or obj['pool_blocks']<16):raise InvalidImage('seal schema')
385
+ seals.append(obj);places.append((slot,obj))
386
+ except (InvalidImage,OSError):continue
387
+ if not seals:raise RecoveryBlocked('no valid catalogue seal')
388
+ if len({s['volume'] for s in seals})!=1:raise SplitIdentity('volume disagreement')
389
+ g=max(s['generation'] for s in seals);newest=[s for s in seals if s['generation']==g]
390
+ if len({canonical(s) for s in newest})!=1:raise SplitIdentity('same-generation disagreement')
391
+ self.seal=newest[0];self.generation=g;self.volume=self.seal['volume'];self.pool_blocks=self.seal['pool_blocks']
392
+ if os.fstat(self.fd).st_size!=POOL_START+self.pool_blocks*BLOCK_SIZE:raise InvalidImage('fixed image capacity mismatch')
393
+ self._selected_valid_slots={i for i,s in places if canonical(s)==canonical(self.seal)}
394
+ self.catalog_desc=self.seal['root']
395
+ cat,live,files,tokens=self._scan_graph(self.catalog_desc,decode=True)
396
+ self.files_root=cat['files_root'];self.tokens_root=cat['tokens_root'];self.epoch=self.checkpoint_epoch=cat['epoch'];self.history=cat['history']
397
+ self._files=files;self._tokens=tokens;self._dirty_files={};self._dirty_tokens={};self._live_blocks=live
398
+ self._free=[i for i in range(self.pool_blocks) if i not in live];heapq.heapify(self._free);self.stats['pool_rebuilds']+=1
399
+ self._refs={key:1 for key in self._graph_cache}
400
+ self._block_owner={index:key for key in self._refs for index in key[:2]};self._pending=set()
401
+ headers={};complete={};valid={}
402
+ for slot in range(SLOTS):
403
+ for replica in range(2):
404
+ off=RING_START+(replica*SLOTS+slot)*SPAN
405
+ try:rawhead=os.pread(self.fd,HEADER.size,off);head=read_header(rawhead,K_CAPSULE,MAX_CAPSULE)
406
+ except (InvalidImage,OSError):continue
407
+ if head['volume']!=self.volume:raise SplitIdentity('capsule volume disagreement')
408
+ e=head['epoch']
409
+ if e<=self.checkpoint_epoch:continue
410
+ if e%SLOTS!=slot or e-self.checkpoint_epoch>SLOTS:raise RecoveryBlocked('capsule outside bounded window')
411
+ identity=(head['length'],head['digest']);headers.setdefault(e,set()).add(identity)
412
+ if len(headers[e])!=1:raise SplitIdentity('same-epoch capsule disagreement')
413
+ try:
414
+ body=read_payload(rawhead+os.pread(self.fd,head['length'],off+HEADER.size),head)
415
+ obj=self._validate_capsule(unpack_json(body),head)
416
+ except (InvalidImage,OSError):continue
417
+ complete[e]={'body':body,'obj':obj,'digest':digest(body)};valid.setdefault(e,set()).add(replica)
418
+ if any(e not in complete for e in headers):raise RecoveryBlocked('newer valid header lacks complete capsule')
419
+ for e,item in sorted(complete.items()):
420
+ if e!=self.epoch+1 or item['obj']['parent']!=self.history:raise RecoveryBlocked('capsule history gap/parent mismatch')
421
+ self._apply(item['obj']);self.epoch=e;self.history=item['digest']
422
+ raw=pack(K_CAPSULE,item['body'],e,self.volume)
423
+ for replica in range(2):
424
+ if replica not in valid[e]:self._repair_records.append((capsule_offset(e,replica),raw))
425
+ self.active=complete;self.stats['arena_live_blocks']=len(live)
426
+ def _reprotect(self):
427
+ try:
428
+ for off,raw in self._repair_records:self._pwrite(raw,off)
429
+ if self._repair_records:self._sync()
430
+ targets=[i for i in range((self.generation%2)*2,(self.generation%2)*2+2) if i not in self._selected_valid_slots]
431
+ if targets:
432
+ raw=pack(K_SEAL,canonical(self.seal),self.generation,self.volume,fixed=SECTOR)
433
+ for i in targets:self._pwrite(raw,SEAL_OFFSETS[i])
434
+ self._sync();self._selected_valid_slots.update(targets)
435
+ except BaseException:self.fenced=True;raise
436
+ self._repair_records=[]
437
+ def checkpoint(self,initial=False):
438
+ self._writable()
439
+ if initial and self.generation!=-1:raise ValueError('initial checkpoint restricted to creation')
440
+ if self.generation==MAX_U64:raise StoreError('catalogue generation exhausted')
441
+ generation=self.generation+1;self._writing_generation=generation
442
+ old_root=self.catalog_desc
443
+ try:
444
+ changes={path:None if value is None else self._file_value(value) for path,value in self._dirty_files.items()}
445
+ files_root=self._update_tree(self.files_root,'files',changes)
446
+ tokens_root=self._update_tree(self.tokens_root,'tokens',self._dirty_tokens)
447
+ cat={'format':FORMAT,'volume':self.volume,'epoch':self.epoch,'history':self.history,'files_root':files_root,'tokens_root':tokens_root}
448
+ root=self._put_json(K_CATALOG,cat)
449
+ seal={'generation':generation,'volume':self.volume,'pool_blocks':self.pool_blocks,'root':root}
450
+ raw=pack(K_SEAL,canonical(seal),generation,self.volume,fixed=SECTOR)
451
+ self._scan_graph(root,generation=generation,incremental=True)
452
+ self._acquire(root)
453
+ self._sync()
454
+ targets=range(4) if initial else range((generation%2)*2,(generation%2)*2+2)
455
+ for i in targets:self._pwrite(raw,SEAL_OFFSETS[i])
456
+ self._sync()
457
+ # Publication is durable before the allocator changes ownership.
458
+ self.generation=generation;self.seal=seal;self.catalog_desc=root;self.files_root=files_root;self.tokens_root=tokens_root
459
+ self.checkpoint_epoch=self.epoch;self._selected_valid_slots=set(targets)
460
+ if old_root is not None:self._release(old_root)
461
+ self._discard_unreachable_reservations()
462
+ self._repair_records=[];self.active={};self._dirty_files={};self._dirty_tokens={}
463
+ self.stats['checkpoints']+=1;self.stats['arena_live_blocks']=len(self._live_blocks)
464
+ except BaseException:self.fenced=True;raise
465
+ return self.checkpoint_epoch
466
+ def transact(self,changes,token):
467
+ self._writable();token_key(token)
468
+ if not isinstance(changes,dict) or not changes:raise ValueError('nonempty changes dictionary required')
469
+ encoded=[];items=[]
470
+ for path,value in sorted(changes.items()):
471
+ path_key(path)
472
+ if value is not None and not isinstance(value,bytes):raise TypeError('bytes or None values required')
473
+ encoded.append([path,None if value is None else b64(value)]);items.append([path,None if value is None else [len(value),digest(value)]])
474
+ intent=digest(canonical(items));old=self._tokens.get(token)
475
+ if old:
476
+ if old[1]!=intent:raise TransactionConflict('token reused with different intent')
477
+ return old[0]
478
+ if self.epoch==MAX_U64:raise StoreError('epoch exhausted')
479
+ e=self.epoch+1;obj={'format':FORMAT,'volume':self.volume,'epoch':e,'parent':self.history,'token':token,'intent':intent,'changes':encoded}
480
+ body=canonical(obj)
481
+ if len(body)>MAX_CAPSULE:raise ValueError('capsule payload exceeds bound')
482
+ if len(self.active)>=SLOTS:self.checkpoint()
483
+ raw=pack(K_CAPSULE,body,e,self.volume)
484
+ try:
485
+ for replica in range(2):self._pwrite(raw,capsule_offset(e,replica))
486
+ self._sync();self._apply(obj);self.epoch=e;self.history=digest(body)
487
+ self.active[e]={'body':body,'obj':obj,'digest':self.history};self.stats['capsule_batches']+=1
488
+ except BaseException:self.fenced=True;raise
489
+ return e
490
+ def get(self,path):
491
+ self._live();path_key(path)
492
+ try:return self._files[path]
493
+ except KeyError:raise FileNotFoundError(path) from None
494
+ def files(self):self._live();return sorted(self._files)
495
+ def query(self,token):
496
+ self._live();token_key(token);entry=self._tokens.get(token)
497
+ return None if entry is None else {'epoch':entry[0],'intent_sha256':entry[1]}
498
+ def inspect(self):
499
+ self._live();return {'format':FORMAT,'volume':self.volume,'epoch':self.epoch,'checkpoint_epoch':self.checkpoint_epoch,
500
+ 'generation':self.generation,'pool_blocks':self.pool_blocks,'live_blocks':len(self._live_blocks),'free_blocks':len(self._free),
501
+ 'files':self.files(),'tokens':len(self._tokens),'fixed_image_bytes':POOL_START+self.pool_blocks*BLOCK_SIZE,'io':dict(self.stats)}
502
+
503
+ CutStore=ImageStore=PageStore
504
+ def main(argv=None):
505
+ parser=argparse.ArgumentParser(description=__doc__);sub=parser.add_subparsers(dest='command',required=True)
506
+ for name in ('init','demo','inspect','ls'):
507
+ p=sub.add_parser(name);p.add_argument('image')
508
+ args=parser.parse_args(argv)
509
+ try:
510
+ if args.command in ('init','demo'):
511
+ with PageStore.create(args.image) as store:
512
+ if args.command=='demo':store.transact({'/measurement':b'12.345','/index':b'revision=1'},'demo')
513
+ print(json.dumps(store.inspect(),indent=2))
514
+ else:
515
+ with PageStore(args.image,writable=False) as store:
516
+ print('\n'.join(store.files()) if args.command=='ls' else json.dumps(store.inspect(),indent=2))
517
+ return 0
518
+ except (StoreError,OSError,ValueError,TypeError) as exc:print('error: '+str(exc),file=sys.stderr);return 2
519
+ if __name__=='__main__':raise SystemExit(main())
experiments/baselines/v7.py ADDED
@@ -0,0 +1,731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """NYARION VII incremental-reservation immutable page-tree research engine.
3
+
4
+ Regular POSIX files only. All logical values are held in RAM. Capsule commits
5
+ use one fsync; checkpoints copy changed trie paths and publish through two
6
+ protected seal banks. The fixed object pool is reclaimed by root reachability.
7
+ This is not a mounted filesystem or a hardware durability qualification.
8
+ """
9
+ from __future__ import annotations
10
+ import argparse,base64,errno,hashlib,heapq,json,os,re,stat,struct,sys,uuid
11
+ from pathlib import Path
12
+ from collections import ChainMap
13
+ try:
14
+ import fcntl
15
+ except ImportError:
16
+ fcntl=None
17
+
18
+ FORMAT=5
19
+ MAGIC=b'NYPAGES5'
20
+ SLOTS=64
21
+ SPAN=65536
22
+ SECTOR=512
23
+ BLOCK_SIZE=4096
24
+ SEAL_OFFSETS=(0,4096,8192,12288)
25
+ RING_START=16384
26
+ POOL_START=RING_START+2*SLOTS*SPAN
27
+ APPEND_START=POOL_START
28
+ DEFAULT_POOL_BLOCKS=16384
29
+ MAX_POOL_BLOCKS=1<<20
30
+ MAX_U64=(1<<64)-1
31
+ K_SEAL,K_CATALOG,K_TRIE,K_BLOB,K_DATA,K_CAPSULE=1,2,3,4,5,6
32
+ PREFIX=struct.Struct('>8sHHIQ16s32s')
33
+ HEADER=struct.Struct('>8sHHIQ16s32s32s')
34
+ PAGE_PAYLOAD=BLOCK_SIZE-HEADER.size
35
+ MAX_CAPSULE=SPAN-HEADER.size
36
+ INLINE_LIMIT=256
37
+ ZERO='0'*64
38
+ HEX32=re.compile(r'^[0-9a-f]{32}$')
39
+ HEX64=re.compile(r'^[0-9a-f]{64}$')
40
+ TOKEN=re.compile(r'^[A-Za-z0-9_.:-]{1,64}$')
41
+ HEX='0123456789abcdef'
42
+ # Descriptor fields use their largest allowed encoded widths. A symbolic leaf
43
+ # built with this descriptor is never smaller than its physical counterpart.
44
+ BOUND_DESC=(MAX_POOL_BLOCKS-1,MAX_POOL_BLOCKS-1,MAX_U64,K_BLOB,PAGE_PAYLOAD,'f'*64)
45
+
46
+ class StoreError(Exception):pass
47
+ class InvalidImage(StoreError):pass
48
+ class RecoveryBlocked(StoreError):pass
49
+ class SplitIdentity(RecoveryBlocked):pass
50
+ class UnsupportedFormat(RecoveryBlocked):pass
51
+ class WriterFenced(StoreError):pass
52
+ class TransactionConflict(StoreError):pass
53
+ class AdmissionRejected(OSError):
54
+ """No offered capsule was written: its exact checkpoint cannot fit."""
55
+ pass
56
+
57
+ def canonical(obj):return json.dumps(obj,sort_keys=True,separators=(',',':'),ensure_ascii=True,allow_nan=False).encode('ascii')
58
+ # All branch/manifest/catalogue records fit even at the declared format bounds.
59
+ assert len(canonical({'family':'tokens','type':'branch','depth':63,'children':{n:BOUND_DESC for n in HEX}}))<=PAGE_PAYLOAD
60
+ assert len(canonical({'length':MAX_CAPSULE,'digest':'f'*64,'chunks':[BOUND_DESC]*((MAX_CAPSULE+PAGE_PAYLOAD-1)//PAGE_PAYLOAD)}))<=PAGE_PAYLOAD
61
+ assert len(canonical({'format':FORMAT,'volume':'f'*32,'epoch':MAX_U64,'history':'f'*64,'files_root':BOUND_DESC,'tokens_root':BOUND_DESC}))<=PAGE_PAYLOAD
62
+ def digest(raw):return hashlib.sha256(raw).hexdigest()
63
+ def uint(x,maximum=MAX_U64):return type(x) is int and 0<=x<=maximum
64
+ def hash_key(key):return hashlib.sha256(key.encode('utf8')).hexdigest()
65
+ def path_key(path):
66
+ 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('/')):
67
+ raise ValueError('canonical absolute flat path key required')
68
+ return path
69
+ def token_key(token):
70
+ if not isinstance(token,str) or not TOKEN.fullmatch(token):raise ValueError('safe ASCII token required')
71
+ return token
72
+ def b64(raw):return base64.b64encode(raw).decode('ascii')
73
+ def unb64(value):
74
+ if not isinstance(value,str):raise InvalidImage('base64 type')
75
+ try:raw=base64.b64decode(value,validate=True)
76
+ except (ValueError,UnicodeError) as exc:raise InvalidImage('base64 encoding') from exc
77
+ if b64(raw)!=value:raise InvalidImage('noncanonical base64')
78
+ return raw
79
+ def unpack_json(raw):
80
+ def pairs(items):
81
+ d={}
82
+ for k,v in items:
83
+ if k in d:raise InvalidImage('duplicate JSON field')
84
+ d[k]=v
85
+ return d
86
+ try:obj=json.loads(raw.decode('ascii'),object_pairs_hook=pairs,parse_constant=lambda _:(_ for _ in ()).throw(ValueError()))
87
+ except (ValueError,UnicodeError,RecursionError) as exc:raise InvalidImage('invalid JSON') from exc
88
+ if not isinstance(obj,dict) or canonical(obj)!=raw:raise InvalidImage('noncanonical JSON object')
89
+ return obj
90
+ def pack(kind,payload,epoch,volume,fixed=None):
91
+ if not uint(epoch) or not isinstance(volume,str) or not HEX32.fullmatch(volume):raise ValueError('record identity')
92
+ prefix=PREFIX.pack(MAGIC,FORMAT,kind,len(payload),epoch,bytes.fromhex(volume),hashlib.sha256(payload).digest())
93
+ raw=prefix+hashlib.sha256(prefix).digest()+payload
94
+ if fixed is not None:
95
+ if len(raw)>fixed:raise ValueError('record exceeds reserved unit')
96
+ raw+=bytes(fixed-len(raw))
97
+ return raw
98
+ def read_header(raw,kind,maximum):
99
+ if len(raw)<HEADER.size:raise InvalidImage('short header')
100
+ magic,version,k,n,e,vol,h,check=HEADER.unpack_from(raw)
101
+ if magic!=MAGIC or k!=kind or hashlib.sha256(raw[:PREFIX.size]).digest()!=check:raise InvalidImage('header identity/checksum')
102
+ if version!=FORMAT:raise UnsupportedFormat('checksum-valid unsupported format')
103
+ if n>maximum:raise RecoveryBlocked('checksum-valid length exceeds bound')
104
+ return {'epoch':e,'volume':vol.hex(),'length':n,'digest':h.hex()}
105
+ def read_payload(raw,head):
106
+ body=raw[HEADER.size:HEADER.size+head['length']]
107
+ if len(body)!=head['length'] or digest(body)!=head['digest']:raise InvalidImage('payload length/digest')
108
+ return body
109
+ def capsule_offset(epoch,replica):return RING_START+(replica*SLOTS+epoch%SLOTS)*SPAN
110
+ def block_offset(index):return POOL_START+index*BLOCK_SIZE
111
+
112
+ class PageStore:
113
+ """Single serialized publisher; fixed-capacity mirrored object arena."""
114
+ def __init__(self,path,*,writable=True,minimum_epoch=None):
115
+ if fcntl is None:raise StoreError('POSIX flock required')
116
+ self.path=os.fspath(path);self.fd=None;self.writable=writable;self.fenced=False;self.reset_stats()
117
+ fd=os.open(self.path,(os.O_RDWR if writable else os.O_RDONLY)|getattr(os,'O_NOFOLLOW',0))
118
+ try:
119
+ if not stat.S_ISREG(os.fstat(fd).st_mode):raise InvalidImage('regular image file required')
120
+ fcntl.flock(fd,(fcntl.LOCK_EX if writable else fcntl.LOCK_SH)|fcntl.LOCK_NB);self.fd=fd
121
+ self._recover()
122
+ if minimum_epoch is not None and (not uint(minimum_epoch) or self.epoch<minimum_epoch):raise RecoveryBlocked('below caller minimum epoch')
123
+ if writable:
124
+ self._reprotect()
125
+ if self.active:
126
+ try:self._checkpoint_plan=self._prepare_checkpoint_plan()
127
+ except AdmissionRejected as exc:
128
+ raise AdmissionRejected(errno.ENOSPC,'recovered capsule tail has no feasible checkpoint; read-only recovery remains available') from exc
129
+ except BaseException:os.close(fd);self.fd=None;raise
130
+ @classmethod
131
+ def create(cls,path,*,initial_files=None,pool_blocks=DEFAULT_POOL_BLOCKS):
132
+ if fcntl is None:raise StoreError('POSIX flock required')
133
+ if not uint(pool_blocks,MAX_POOL_BLOCKS) or pool_blocks<16:raise ValueError('pool_blocks must be 16..1048576')
134
+ if initial_files is not None and not isinstance(initial_files,dict):raise TypeError('initial_files dictionary required')
135
+ files={}
136
+ for key,value in (initial_files or {}).items():
137
+ path_key(key)
138
+ if not isinstance(value,bytes):raise TypeError('bytes values required')
139
+ if len(value)>MAX_CAPSULE:raise ValueError('initial value exceeds supported size')
140
+ files[key]=value
141
+ fd=os.open(os.fspath(path),os.O_RDWR|os.O_CREAT|os.O_EXCL|getattr(os,'O_NOFOLLOW',0),0o600)
142
+ self=cls.__new__(cls);self.path=os.fspath(path);self.fd=fd;self.writable=True;self.fenced=False;self.reset_stats()
143
+ try:
144
+ if not stat.S_ISREG(os.fstat(fd).st_mode):raise InvalidImage('regular image file required')
145
+ fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB);os.ftruncate(fd,POOL_START+pool_blocks*BLOCK_SIZE)
146
+ self.volume=uuid.uuid4().hex;self.pool_blocks=pool_blocks;self.generation=-1;self.epoch=0;self.checkpoint_epoch=0;self.history=ZERO
147
+ self.files_root=None;self.tokens_root=None;self.catalog_desc=None;self._files=files;self._tokens={};self.active={}
148
+ 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()
149
+ self._free=list(range(pool_blocks));heapq.heapify(self._free)
150
+ self._refs={};self._block_owner={};self._pending=set();self._checkpoint_plan=None
151
+ self.checkpoint(initial=True)
152
+ parent=os.open(str(Path(path).resolve().parent),os.O_RDONLY|getattr(os,'O_DIRECTORY',0))
153
+ try:os.fsync(parent)
154
+ finally:os.close(parent)
155
+ return self
156
+ except BaseException:self.close();raise
157
+ def __enter__(self):return self
158
+ def __exit__(self,*exc):self.close()
159
+ def close(self):
160
+ if self.fd is not None:os.close(self.fd);self.fd=None
161
+ def _live(self):
162
+ if self.fd is None:raise StoreError('closed')
163
+ if self.fenced:raise WriterFenced('uncertain state: close and recover')
164
+ def _writable(self):
165
+ self._live()
166
+ if not self.writable:raise WriterFenced('read-only image')
167
+ def reset_stats(self):
168
+ self.stats={'bytes_written':0,'write_calls':0,'fsync_calls':0,'capsule_batches':0,'checkpoints':0,
169
+ 'page_allocations':0,'reclaimed_blocks':0,'arena_live_blocks':0,'full_graph_scans':0,
170
+ 'incremental_validations':0,'graph_nodes_validated':0,'refcount_steps':0,'pool_rebuilds':0,
171
+ 'admission_plans':0,'admission_planned_blocks':0,'admission_rejections':0,'admission_pressure_checkpoints':0,'executed_plans':0,
172
+ 'reservation_offers':0,'reservation_fast_accepts':0,'reservation_exact_fallbacks':0,'reservation_cells_rebuilt':0,'reservation_route_visits':0}
173
+ def _pwrite(self,raw,offset):
174
+ view=memoryview(raw)
175
+ while view:
176
+ n=os.pwrite(self.fd,view,offset)
177
+ if n<=0:raise OSError('zero-length write')
178
+ self.stats['bytes_written']+=n;self.stats['write_calls']+=1;view=view[n:];offset+=n
179
+ def _sync(self):self.stats['fsync_calls']+=1;os.fsync(self.fd)
180
+ def _valid_desc(self,desc,kind=None):
181
+ if not isinstance(desc,list) or len(desc)!=6:return False
182
+ a,b,g,k,n,h=desc
183
+ return (uint(a,self.pool_blocks-1) and uint(b,self.pool_blocks-1) and a!=b and uint(g) and
184
+ type(k) is int and k in (K_CATALOG,K_TRIE,K_BLOB,K_DATA) and (kind is None or k==kind)
185
+ and uint(n,PAGE_PAYLOAD) and isinstance(h,str) and bool(HEX64.fullmatch(h)))
186
+ def _alloc_object(self,kind,body):
187
+ if len(body)>PAGE_PAYLOAD:raise StoreError('object exceeds page payload')
188
+ if len(self._free)<2:raise OSError(errno.ENOSPC,'fixed object arena lacks COW checkpoint headroom')
189
+ a,b=heapq.heappop(self._free),heapq.heappop(self._free)
190
+ desc=[a,b,self._writing_generation,kind,len(body),digest(body)]
191
+ key=tuple(desc);self._pending.add(key)
192
+ for index in (a,b):
193
+ if index in self._block_owner:raise InvalidImage('allocator selected an owned block')
194
+ self._block_owner[index]=key
195
+ raw=pack(kind,body,self._writing_generation,self.volume,fixed=BLOCK_SIZE)
196
+ for index in (a,b):self._pwrite(raw,block_offset(index))
197
+ self._cache[tuple(desc)]=body;self.stats['page_allocations']+=2
198
+ return desc
199
+ def _read_object(self,desc,kind=None):
200
+ if not self._valid_desc(desc,kind):raise InvalidImage('object descriptor bounds/identity')
201
+ key=tuple(desc)
202
+ if key in self._cache:return self._cache[key]
203
+ good=None;bad=[]
204
+ for index in desc[:2]:
205
+ try:
206
+ raw=os.pread(self.fd,BLOCK_SIZE,block_offset(index));head=read_header(raw,desc[3],PAGE_PAYLOAD);body=read_payload(raw,head)
207
+ 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')
208
+ good=body
209
+ except (InvalidImage,OSError):bad.append(index)
210
+ if good is None:raise RecoveryBlocked('required object has no valid mirror; fallback refused')
211
+ expected=pack(desc[3],good,desc[2],self.volume,fixed=BLOCK_SIZE)
212
+ for index in bad:self._repair_records.append((block_offset(index),expected))
213
+ self._cache[key]=good;return good
214
+ def _put_json(self,kind,obj):return self._alloc_object(kind,canonical(obj))
215
+ def _file_value(self,data):
216
+ if len(data)>MAX_CAPSULE:raise ValueError('value exceeds supported size')
217
+ if len(data)<=INLINE_LIMIT:return {'inline':b64(data)}
218
+ chunks=[self._alloc_object(K_DATA,data[i:i+PAGE_PAYLOAD]) for i in range(0,len(data),PAGE_PAYLOAD)]
219
+ return {'blob':self._put_json(K_BLOB,{'length':len(data),'digest':digest(data),'chunks':chunks})}
220
+ def _build_tree(self,family,entries,depth=0):
221
+ if not entries:return None
222
+ leaf={'family':family,'type':'leaf','depth':depth,'entries':entries};raw=canonical(leaf)
223
+ if len(raw)<=PAGE_PAYLOAD:return self._alloc_object(K_TRIE,raw)
224
+ if depth>=64:raise StoreError('hash collision leaf exceeds page capacity')
225
+ groups={}
226
+ for key,value in entries.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
227
+ children={nib:self._build_tree(family,group,depth+1) for nib,group in groups.items()}
228
+ return self._put_json(K_TRIE,{'family':family,'type':'branch','depth':depth,'children':children})
229
+ def _update_tree(self,desc,family,changes,depth=0):
230
+ if not changes:return desc
231
+ if desc is None:return self._build_tree(family,{k:v for k,v in changes.items() if v is not None},depth)
232
+ node=unpack_json(self._read_object(desc,K_TRIE))
233
+ if node.get('family')!=family or node.get('depth')!=depth:raise InvalidImage('trie update identity/depth')
234
+ if node.get('type')=='leaf':
235
+ entries=dict(node['entries'])
236
+ for key,value in changes.items():
237
+ if value is None:entries.pop(key,None)
238
+ else:entries[key]=value
239
+ if entries==node['entries']:return desc
240
+ return self._build_tree(family,entries,depth)
241
+ if node.get('type')!='branch' or depth>=64:raise InvalidImage('trie branch update')
242
+ children=dict(node['children']);groups={}
243
+ for key,value in changes.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
244
+ for nib,group in groups.items():
245
+ child=self._update_tree(children.get(nib),family,group,depth+1)
246
+ if child is None:children.pop(nib,None)
247
+ else:children[nib]=child
248
+ if children==node['children']:return desc
249
+ if not children:return None
250
+ return self._put_json(K_TRIE,{'family':family,'type':'branch','depth':depth,'children':children})
251
+ def _scan_graph(self,catalog_desc,*,decode=False,generation=None,incremental=False):
252
+ """Full recovery validation, or validation of newly reserved objects only.
253
+
254
+ An unchanged pointer is accepted only when its complete identity is live
255
+ and its validated family/routing/owner context matches the new edge.
256
+ """
257
+ self.stats['incremental_validations' if incremental else 'full_graph_scans']+=1
258
+ seen=set();identities=set();files={};tokens={}
259
+ selected_generation=self.generation if generation is None else generation
260
+ if not self._valid_desc(catalog_desc,K_CATALOG) or catalog_desc[2]!=selected_generation:raise InvalidImage('catalogue birth differs from selected generation')
261
+ def known(desc,kind,context):
262
+ if not self._valid_desc(desc,kind) or desc[2]>selected_generation:raise InvalidImage('invalid reachable descriptor/birth')
263
+ if not incremental:return False
264
+ key=tuple(desc)
265
+ if any(self._block_owner.get(index)!=key for index in desc[:2]):raise InvalidImage('descriptor does not own its reserved/live blocks')
266
+ if self._refs.get(key,0):
267
+ info=self._graph_cache.get(key)
268
+ if info is None or info['context']!=context or info['max_epoch']>cat['epoch']:raise InvalidImage('unchanged object context/epoch mismatch')
269
+ return True
270
+ if key not in self._pending:raise InvalidImage('pointer is neither live nor reserved')
271
+ return False
272
+ def claim(desc,kind):
273
+ if not self._valid_desc(desc,kind) or desc[2]>selected_generation:raise InvalidImage('invalid reachable descriptor/birth')
274
+ if seen.intersection(desc[:2]):raise InvalidImage('object block alias/cycle')
275
+ seen.update(desc[:2]);identities.add(tuple(desc));self.stats['graph_nodes_validated']+=1
276
+ return self._read_object(desc,kind)
277
+ if incremental:
278
+ key=tuple(catalog_desc)
279
+ 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')
280
+ cat=unpack_json(claim(catalog_desc,K_CATALOG))
281
+ if (set(cat)!={'format','volume','epoch','history','files_root','tokens_root'} or type(cat['format']) is not int or cat['format']!=FORMAT or
282
+ 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')
283
+ if incremental and (cat['epoch']!=self.epoch or cat['history']!=self.history):raise InvalidImage('candidate logical head mismatch')
284
+ def remember(desc,links,context,max_epoch=0):
285
+ self._graph_cache[tuple(desc)]={'links':links,'context':context,'max_epoch':max_epoch}
286
+ def file_value(path,obj):
287
+ if not isinstance(obj,dict):raise InvalidImage('file value schema')
288
+ if set(obj)=={'inline'}:
289
+ data=unb64(obj['inline'])
290
+ if len(data)>INLINE_LIMIT:raise InvalidImage('oversized inline value')
291
+ return data,[]
292
+ if set(obj)!={'blob'}:raise InvalidImage('file encoding')
293
+ desc=obj['blob'];links=[(desc,K_BLOB)]
294
+ if known(desc,K_BLOB,('blob',path)):return None,links
295
+ manifest=unpack_json(claim(desc,K_BLOB))
296
+ if (set(manifest)!={'length','digest','chunks'} or not uint(manifest['length'],MAX_CAPSULE) or manifest['length']<=INLINE_LIMIT or
297
+ not isinstance(manifest['digest'],str) or not HEX64.fullmatch(manifest['digest']) or
298
+ not isinstance(manifest['chunks'],list) or len(manifest['chunks'])!=(manifest['length']+PAGE_PAYLOAD-1)//PAGE_PAYLOAD):raise InvalidImage('blob manifest')
299
+ parts=[]
300
+ for i,chunk in enumerate(manifest['chunks']):
301
+ context=('data',path,i)
302
+ if known(chunk,K_DATA,context):part=self._read_object(chunk,K_DATA)
303
+ else:
304
+ part=claim(chunk,K_DATA);remember(chunk,[],context)
305
+ if len(part)!=min(PAGE_PAYLOAD,manifest['length']-i*PAGE_PAYLOAD):raise InvalidImage('blob chunk length')
306
+ parts.append(part)
307
+ data=b''.join(parts)
308
+ if len(data)!=manifest['length'] or digest(data)!=manifest['digest']:raise InvalidImage('blob data mismatch')
309
+ remember(desc,[(chunk,K_DATA) for chunk in manifest['chunks']],('blob',path))
310
+ return data,links
311
+ def walk(desc,family,depth=0,prefix=''):
312
+ if desc is None:return
313
+ context=('trie',family,depth,prefix)
314
+ if known(desc,K_TRIE,context):return
315
+ node=unpack_json(claim(desc,K_TRIE))
316
+ 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')
317
+ links=[];max_epoch=0
318
+ if node.get('type')=='leaf':
319
+ if set(node)!={'family','type','depth','entries'} or not isinstance(node['entries'],dict) or not node['entries']:raise InvalidImage('leaf schema')
320
+ for key,value in node['entries'].items():
321
+ try:path_key(key) if family=='files' else token_key(key)
322
+ except ValueError as exc:raise InvalidImage('trie key') from exc
323
+ if not hash_key(key).startswith(prefix):raise InvalidImage('trie key routing')
324
+ if family=='files':
325
+ data,dependencies=file_value(key,value);links.extend(dependencies)
326
+ if decode:files[key]=data
327
+ else:
328
+ 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')
329
+ max_epoch=max(max_epoch,value[0])
330
+ if decode:tokens[key]=value
331
+ remember(desc,links,context,max_epoch);return
332
+ if (node.get('type')!='branch' or set(node)!={'family','type','depth','children'} or depth>=64 or
333
+ 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')
334
+ for nib,child in node['children'].items():
335
+ walk(child,family,depth+1,prefix+nib);links.append((child,K_TRIE))
336
+ max_epoch=max(max_epoch,self._graph_cache[tuple(child)]['max_epoch'])
337
+ remember(desc,links,context,max_epoch)
338
+ walk(cat['files_root'],'files');walk(cat['tokens_root'],'tokens')
339
+ remember(catalog_desc,[(desc,K_TRIE) for desc in (cat['files_root'],cat['tokens_root']) if desc is not None],('catalog',))
340
+ return cat,seen,files,tokens
341
+ def _acquire(self,desc):
342
+ """Activate outgoing edges only on the object's zero-to-one transition."""
343
+ key=tuple(desc);previous=self._refs.get(key,0);self._refs[key]=previous+1;self.stats['refcount_steps']+=1
344
+ if previous:return
345
+ info=self._graph_cache.get(key)
346
+ if info is None:raise InvalidImage('acquiring unvalidated object')
347
+ self._pending.discard(key);self._live_blocks.update(desc[:2])
348
+ for child,kind in info['links']:self._acquire(child)
349
+ def _release(self,desc):
350
+ """Retire outgoing edges and recycle blocks only at the last reference."""
351
+ key=tuple(desc);count=self._refs.get(key,0);self.stats['refcount_steps']+=1
352
+ if count<=0:raise InvalidImage('reference count underflow')
353
+ if count>1:self._refs[key]=count-1;return
354
+ del self._refs[key];info=self._graph_cache.pop(key)
355
+ for child,kind in info['links']:self._release(child)
356
+ self._cache.pop(key,None)
357
+ for index in desc[:2]:
358
+ if self._block_owner.pop(index,None)!=key:raise InvalidImage('releasing object ownership mismatch')
359
+ self._live_blocks.remove(index);heapq.heappush(self._free,index)
360
+ self.stats['reclaimed_blocks']+=2
361
+ def _discard_unreachable_reservations(self):
362
+ # Normally empty: retain this guard for allocations omitted by a builder.
363
+ for key in self._pending:
364
+ if self._refs.get(key,0):raise InvalidImage('live allocation remained reserved')
365
+ self._cache.pop(key,None);self._graph_cache.pop(key,None)
366
+ for index in key[:2]:
367
+ if self._block_owner.pop(index,None)!=key:raise InvalidImage('reservation ownership mismatch')
368
+ heapq.heappush(self._free,index)
369
+ self.stats['reclaimed_blocks']+=2
370
+ self._pending.clear()
371
+ def _validate_capsule(self,obj,head):
372
+ if (set(obj)!={'format','volume','epoch','parent','token','intent','changes'} or type(obj['format']) is not int or obj['format']!=FORMAT or
373
+ obj['volume']!=self.volume or obj['epoch']!=head['epoch'] or not uint(obj['epoch']) or not obj['epoch'] or
374
+ 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')
375
+ try:token_key(obj['token'])
376
+ except ValueError as exc:raise InvalidImage('capsule token') from exc
377
+ previous=None;items=[]
378
+ for change in obj['changes']:
379
+ if not isinstance(change,list) or len(change)!=2:raise InvalidImage('change schema')
380
+ path,value=change
381
+ try:path_key(path)
382
+ except ValueError as exc:raise InvalidImage('capsule path') from exc
383
+ if previous is not None and path<=previous:raise InvalidImage('unsorted/duplicate changes')
384
+ previous=path;raw=None if value is None else unb64(value)
385
+ items.append([path,None if raw is None else [len(raw),digest(raw)]])
386
+ if digest(canonical(items))!=obj['intent']:raise InvalidImage('intent mismatch')
387
+ return obj
388
+ def _apply(self,obj):
389
+ if obj['token'] in self._tokens:raise RecoveryBlocked('duplicate committed token')
390
+ for path,value in obj['changes']:
391
+ data=None if value is None else unb64(value)
392
+ if data is None:self._files.pop(path,None)
393
+ else:self._files[path]=data
394
+ self._dirty_files[path]=data
395
+ entry=[obj['epoch'],obj['intent']];self._tokens[obj['token']]=entry;self._dirty_tokens[obj['token']]=entry
396
+ def _recover(self):
397
+ self._cache={};self._graph_cache={};self._repair_records=[];seals=[];places=[]
398
+ for slot,off in enumerate(SEAL_OFFSETS):
399
+ try:
400
+ raw=os.pread(self.fd,SECTOR,off);head=read_header(raw,K_SEAL,SECTOR-HEADER.size);obj=unpack_json(read_payload(raw,head))
401
+ if (set(obj)!={'generation','volume','pool_blocks','root'} or not uint(obj['generation']) or obj['generation']!=head['epoch'] or
402
+ obj['volume']!=head['volume'] or not uint(obj['pool_blocks'],MAX_POOL_BLOCKS) or obj['pool_blocks']<16):raise InvalidImage('seal schema')
403
+ seals.append(obj);places.append((slot,obj))
404
+ except (InvalidImage,OSError):continue
405
+ if not seals:raise RecoveryBlocked('no valid catalogue seal')
406
+ if len({s['volume'] for s in seals})!=1:raise SplitIdentity('volume disagreement')
407
+ g=max(s['generation'] for s in seals);newest=[s for s in seals if s['generation']==g]
408
+ if len({canonical(s) for s in newest})!=1:raise SplitIdentity('same-generation disagreement')
409
+ self.seal=newest[0];self.generation=g;self.volume=self.seal['volume'];self.pool_blocks=self.seal['pool_blocks']
410
+ if os.fstat(self.fd).st_size!=POOL_START+self.pool_blocks*BLOCK_SIZE:raise InvalidImage('fixed image capacity mismatch')
411
+ self._selected_valid_slots={i for i,s in places if canonical(s)==canonical(self.seal)}
412
+ self.catalog_desc=self.seal['root']
413
+ cat,live,files,tokens=self._scan_graph(self.catalog_desc,decode=True)
414
+ self.files_root=cat['files_root'];self.tokens_root=cat['tokens_root'];self.epoch=self.checkpoint_epoch=cat['epoch'];self.history=cat['history']
415
+ self._files=files;self._tokens=tokens;self._dirty_files={};self._dirty_tokens={};self._live_blocks=live
416
+ self._free=[i for i in range(self.pool_blocks) if i not in live];heapq.heapify(self._free);self.stats['pool_rebuilds']+=1
417
+ self._refs={key:1 for key in self._graph_cache}
418
+ self._block_owner={index:key for key in self._refs for index in key[:2]};self._pending=set()
419
+ headers={};complete={};valid={}
420
+ for slot in range(SLOTS):
421
+ for replica in range(2):
422
+ off=RING_START+(replica*SLOTS+slot)*SPAN
423
+ try:rawhead=os.pread(self.fd,HEADER.size,off);head=read_header(rawhead,K_CAPSULE,MAX_CAPSULE)
424
+ except (InvalidImage,OSError):continue
425
+ if head['volume']!=self.volume:raise SplitIdentity('capsule volume disagreement')
426
+ e=head['epoch']
427
+ if e<=self.checkpoint_epoch:continue
428
+ if e%SLOTS!=slot or e-self.checkpoint_epoch>SLOTS:raise RecoveryBlocked('capsule outside bounded window')
429
+ identity=(head['length'],head['digest']);headers.setdefault(e,set()).add(identity)
430
+ if len(headers[e])!=1:raise SplitIdentity('same-epoch capsule disagreement')
431
+ try:
432
+ body=read_payload(rawhead+os.pread(self.fd,head['length'],off+HEADER.size),head)
433
+ obj=self._validate_capsule(unpack_json(body),head)
434
+ except (InvalidImage,OSError):continue
435
+ complete[e]={'body':body,'obj':obj,'digest':digest(body)};valid.setdefault(e,set()).add(replica)
436
+ if any(e not in complete for e in headers):raise RecoveryBlocked('newer valid header lacks complete capsule')
437
+ for e,item in sorted(complete.items()):
438
+ if e!=self.epoch+1 or item['obj']['parent']!=self.history:raise RecoveryBlocked('capsule history gap/parent mismatch')
439
+ self._apply(item['obj']);self.epoch=e;self.history=item['digest']
440
+ raw=pack(K_CAPSULE,item['body'],e,self.volume)
441
+ for replica in range(2):
442
+ if replica not in valid[e]:self._repair_records.append((capsule_offset(e,replica),raw))
443
+ self.active=complete;self._checkpoint_plan=None;self.stats['arena_live_blocks']=len(live)
444
+ self._reset_reservations(ready=False)
445
+ def _reprotect(self):
446
+ try:
447
+ for off,raw in self._repair_records:self._pwrite(raw,off)
448
+ if self._repair_records:self._sync()
449
+ targets=[i for i in range((self.generation%2)*2,(self.generation%2)*2+2) if i not in self._selected_valid_slots]
450
+ if targets:
451
+ raw=pack(K_SEAL,canonical(self.seal),self.generation,self.volume,fixed=SECTOR)
452
+ for i in targets:self._pwrite(raw,SEAL_OFFSETS[i])
453
+ self._sync();self._selected_valid_slots.update(targets)
454
+ except BaseException:self.fenced=True;raise
455
+ self._repair_records=[]
456
+ @staticmethod
457
+ def _heap_order(heap):
458
+ """Yield min-heap values in pop order without copying the arena heap."""
459
+ if not heap:return
460
+ frontier=[(heap[0],0)]
461
+ while frontier:
462
+ value,index=heapq.heappop(frontier);yield value
463
+ for child in (2*index+1,2*index+2):
464
+ if child<len(heap):heapq.heappush(frontier,(heap[child],child))
465
+ def _reset_reservations(self,ready=True):
466
+ self._reservation_ready=ready;self._reservation_cells={};self._reservation_ancestors=set()
467
+ self._reservation_blob_pages={};self._reservation_logical=1
468
+ self._reservation_decoded={};self._reservation_routes={}
469
+ def _reservation_route(self,family,key):
470
+ cached=self._reservation_routes.get((family,key))
471
+ if cached is not None:return cached
472
+ desc=self.files_root if family=='files' else self.tokens_root
473
+ depth=0;prefix='';ancestors=[];hashed=hash_key(key)
474
+ while desc is not None:
475
+ identity=tuple(desc);node=self._reservation_decoded.get(identity)
476
+ if node is None:
477
+ node=unpack_json(self._read_object(desc,K_TRIE));self._reservation_decoded[identity]=node
478
+ self.stats['reservation_route_visits']+=1
479
+ if node['family']!=family or node['depth']!=depth:raise InvalidImage('reservation routing identity')
480
+ if node['type']=='leaf':
481
+ answer=((family,prefix),depth,node['entries'],tuple(ancestors));break
482
+ if node['type']!='branch' or depth>=64:raise InvalidImage('reservation routing branch')
483
+ ancestors.append(identity);nib=hashed[depth];prefix+=nib;depth+=1
484
+ desc=node['children'].get(nib)
485
+ else:answer=((family,prefix),depth,{},tuple(ancestors))
486
+ self._reservation_routes[(family,key)]=answer
487
+ return answer
488
+ @staticmethod
489
+ def _reservation_count(family,entries,depth):
490
+ if not entries:return 0
491
+ if len(canonical({'family':family,'type':'leaf','depth':depth,'entries':entries}))<=PAGE_PAYLOAD:return 1
492
+ if depth>=64:return MAX_POOL_BLOCKS # Force the exact compiler to decide.
493
+ groups={}
494
+ for key,value in entries.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
495
+ return 1+sum(PageStore._reservation_count(family,group,depth+1) for group in groups.values())
496
+ def _reservation_preview(self,file_changes,token_changes):
497
+ """Pure budget proposal over affected published-leaf cells.
498
+
499
+ Lookup caches may grow, but committed cells, totals and allocator state
500
+ are unchanged. New descriptors use maximum widths; extra splits and
501
+ ancestor charges are conservative, never less than the exact builder.
502
+ """
503
+ self.stats['reservation_offers']+=1
504
+ proposed={};added_ancestors=set();blob_updates={};logical=self._reservation_logical
505
+ for family,changes in (('files',file_changes),('tokens',token_changes)):
506
+ for key,value in sorted(changes.items()):
507
+ anchor,depth,original,ancestors=self._reservation_route(family,key)
508
+ added_ancestors.update(a for a in ancestors if a not in self._reservation_ancestors)
509
+ if anchor not in proposed:
510
+ previous=self._reservation_cells.get(anchor)
511
+ proposed[anchor]={'depth':depth,'entries':dict(original if previous is None else previous['entries'])}
512
+ entries=proposed[anchor]['entries']
513
+ if family=='files':
514
+ pages=0
515
+ if value is None:entries.pop(key,None)
516
+ elif len(value)<=INLINE_LIMIT:entries[key]={'inline':b64(value)}
517
+ else:
518
+ entries[key]={'blob':BOUND_DESC}
519
+ pages=(len(value)+PAGE_PAYLOAD-1)//PAGE_PAYLOAD+1
520
+ blob_updates[key]=pages
521
+ else:entries[key]=value
522
+ logical+=len(added_ancestors)
523
+ for anchor,cell in proposed.items():
524
+ old=self._reservation_cells.get(anchor)
525
+ cell['nodes']=self._reservation_count(anchor[0],cell['entries'],cell['depth'])
526
+ logical+=cell['nodes']-(0 if old is None else old['nodes'])
527
+ self.stats['reservation_cells_rebuilt']+=1
528
+ for key,pages in blob_updates.items():logical+=pages-self._reservation_blob_pages.get(key,0)
529
+ return {'cells':proposed,'ancestors':added_ancestors,'blobs':blob_updates,'logical':logical,'physical_blocks':2*logical}
530
+ def _reservation_adopt(self,proposal):
531
+ self._reservation_cells.update(proposal['cells']);self._reservation_ancestors.update(proposal['ancestors'])
532
+ self._reservation_blob_pages.update(proposal['blobs']);self._reservation_logical=proposal['logical']
533
+ def _ensure_reservations(self):
534
+ if getattr(self,'_reservation_ready',False):return
535
+ self._reset_reservations(ready=False)
536
+ proposal=self._reservation_preview(self._dirty_files,self._dirty_tokens)
537
+ self._reservation_adopt(proposal);self._reservation_ready=True
538
+ def admission_reservation(self):
539
+ """Detached conservative budget, not an allocated or persisted free map."""
540
+ self._live();self._ensure_reservations()
541
+ exact=self._checkpoint_plan is not None and self._checkpoint_plan['binding']==self._plan_binding()
542
+ bound=2*self._reservation_logical
543
+ return {'certificate_kind':'empty' if not self.active else ('exact_plan' if exact else 'upper_bound'),
544
+ 'reserved_upper_blocks':bound,'free_blocks':len(self._free),'cells':len(self._reservation_cells),
545
+ 'dirty_ancestors':len(self._reservation_ancestors),
546
+ 'tail_certified':not self.active or (self.generation<MAX_U64 and (exact or bound<=len(self._free)))}
547
+ def _plan_binding(self,epoch=None,history=None):
548
+ return (self.volume,self.generation,self.epoch if epoch is None else epoch,
549
+ self.history if history is None else history,canonical(self.files_root),canonical(self.tokens_root))
550
+ def _prepare_checkpoint_plan(self,*,dirty_files=None,dirty_tokens=None,epoch=None,history=None):
551
+ """Compile and validate exact output without disk/live-allocator mutation.
552
+
553
+ Overlays contain only candidate objects. The sorted heap iterator visits
554
+ only the chosen free prefix; no arena/live-graph dictionary is copied.
555
+ This recompiles the bounded outstanding window for each offered txn.
556
+ """
557
+ if self.generation==MAX_U64:raise StoreError('catalogue generation exhausted')
558
+ self.stats['admission_plans']+=1
559
+ sandbox=object.__new__(type(self));sandbox.__dict__=dict(self.__dict__)
560
+ sandbox.stats=dict(self.stats);sandbox._writing_generation=self.generation+1;sandbox._checkpoint_plan=None
561
+ sandbox.epoch=self.epoch if epoch is None else epoch
562
+ sandbox.history=self.history if history is None else history
563
+ sandbox._dirty_files=self._dirty_files if dirty_files is None else dirty_files
564
+ sandbox._dirty_tokens=self._dirty_tokens if dirty_tokens is None else dirty_tokens
565
+ sandbox._cache=ChainMap({},self._cache);sandbox._graph_cache=ChainMap({},self._graph_cache)
566
+ sandbox._block_owner=ChainMap({},self._block_owner);sandbox._pending=set();sandbox._repair_records=[]
567
+ free=iter(self._heap_order(self._free));allocations=[];writes=[]
568
+ def staged_alloc(kind,body):
569
+ if len(body)>PAGE_PAYLOAD:raise StoreError('object exceeds page payload')
570
+ try:a,b=next(free),next(free)
571
+ except StopIteration as exc:raise AdmissionRejected(errno.ENOSPC,'offered state lacks exact COW checkpoint headroom') from exc
572
+ desc=[a,b,sandbox._writing_generation,kind,len(body),digest(body)];key=tuple(desc)
573
+ sandbox._pending.add(key);allocations.append(key)
574
+ for index in (a,b):
575
+ if index in sandbox._block_owner:raise InvalidImage('planner selected an owned block')
576
+ sandbox._block_owner[index]=key
577
+ raw=pack(kind,body,sandbox._writing_generation,self.volume,fixed=BLOCK_SIZE)
578
+ writes.extend((block_offset(index),raw) for index in (a,b))
579
+ sandbox._cache[key]=body
580
+ return desc
581
+ sandbox._alloc_object=staged_alloc
582
+ try:
583
+ changes={path:None if value is None else sandbox._file_value(value) for path,value in sorted(sandbox._dirty_files.items())}
584
+ files_root=sandbox._update_tree(self.files_root,'files',changes)
585
+ tokens_root=sandbox._update_tree(self.tokens_root,'tokens',dict(sorted(sandbox._dirty_tokens.items())))
586
+ cat={'format':FORMAT,'volume':self.volume,'epoch':sandbox.epoch,'history':sandbox.history,'files_root':files_root,'tokens_root':tokens_root}
587
+ root=sandbox._put_json(K_CATALOG,cat)
588
+ generation=sandbox._writing_generation
589
+ seal={'generation':generation,'volume':self.volume,'pool_blocks':self.pool_blocks,'root':root}
590
+ seal_raw=pack(K_SEAL,canonical(seal),generation,self.volume,fixed=SECTOR)
591
+ sandbox._scan_graph(root,generation=generation,incremental=True)
592
+ except AdmissionRejected:
593
+ self.stats['admission_rejections']+=1;raise
594
+ finally:
595
+ del sandbox._alloc_object # Break the sandbox/closure reference cycle.
596
+ self.stats['graph_nodes_validated']=sandbox.stats['graph_nodes_validated']
597
+ self.stats['incremental_validations']=sandbox.stats['incremental_validations']
598
+ self.stats['admission_planned_blocks']+=len(writes)
599
+ targets=tuple(range(4)) if self.generation==-1 else tuple(range((generation%2)*2,(generation%2)*2+2))
600
+ return {'binding':self._plan_binding(sandbox.epoch,sandbox.history),'generation':generation,'epoch':sandbox.epoch,
601
+ 'history':sandbox.history,'files_root':files_root,'tokens_root':tokens_root,'root':root,'seal':seal,
602
+ 'objects':tuple(allocations),'dependency_writes':tuple(writes),
603
+ 'seal_writes':tuple((SEAL_OFFSETS[i],seal_raw) for i in targets),'targets':targets,
604
+ 'cache':dict(sandbox._cache.maps[0]),'edges':dict(sandbox._graph_cache.maps[0])}
605
+ def checkpoint_plan(self,*,include_writes=False):
606
+ """Return a detached exact publication summary; never writes or forces.
607
+
608
+ `writes`, when requested, includes dependency pages followed by seals;
609
+ force boundaries give the write counts after which fsync must occur.
610
+ """
611
+ self._live()
612
+ plan=self._checkpoint_plan
613
+ if plan is None or plan['binding']!=self._plan_binding():
614
+ plan=self._prepare_checkpoint_plan()
615
+ if self.writable:self._checkpoint_plan=plan
616
+ dep=plan['dependency_writes'];all_writes=dep+plan['seal_writes']
617
+ result={'epoch':plan['epoch'],'generation':plan['generation'],'history':plan['history'],
618
+ 'pool_blocks':self.pool_blocks,'physical_blocks':len(dep),'bytes_written':sum(len(raw) for _,raw in all_writes),
619
+ 'root_sha256':plan['root'][5],'force_boundaries':(len(dep),len(all_writes))}
620
+ if include_writes:result['writes']=all_writes
621
+ return result
622
+ def checkpoint(self,initial=False):
623
+ self._writable()
624
+ if initial and self.generation!=-1:raise ValueError('initial checkpoint restricted to creation')
625
+ plan=self._checkpoint_plan
626
+ if plan is None or plan['binding']!=self._plan_binding():plan=self._prepare_checkpoint_plan()
627
+ if not initial:
628
+ self._ensure_reservations()
629
+ if len(plan['dependency_writes'])>2*self._reservation_logical:
630
+ self.fenced=True;raise InvalidImage('exact checkpoint exceeded admission upper bound')
631
+ old_root=self.catalog_desc
632
+ try:
633
+ # Consume exactly the free prefix certified before acknowledgment.
634
+ for key in plan['objects']:
635
+ for index in key[:2]:
636
+ if heapq.heappop(self._free)!=index or index in self._block_owner:raise InvalidImage('checkpoint plan allocation binding changed')
637
+ self._block_owner[index]=key
638
+ self._pending.add(key)
639
+ self._cache.update(plan['cache']);self._graph_cache.update(plan['edges'])
640
+ for off,raw in plan['dependency_writes']:self._pwrite(raw,off)
641
+ self.stats['page_allocations']+=len(plan['dependency_writes'])
642
+ self._acquire(plan['root']);self._sync()
643
+ for off,raw in plan['seal_writes']:self._pwrite(raw,off)
644
+ self._sync()
645
+ # Publication is durable before old ownership can be retired.
646
+ self.generation=plan['generation'];self.seal=plan['seal'];self.catalog_desc=plan['root']
647
+ self.files_root=plan['files_root'];self.tokens_root=plan['tokens_root'];self.checkpoint_epoch=self.epoch
648
+ self._selected_valid_slots=set(plan['targets'])
649
+ if old_root is not None:self._release(old_root)
650
+ self._discard_unreachable_reservations()
651
+ self._repair_records=[];self.active={};self._dirty_files={};self._dirty_tokens={};self._checkpoint_plan=None
652
+ self._reset_reservations()
653
+ self.stats['checkpoints']+=1;self.stats['executed_plans']+=1;self.stats['arena_live_blocks']=len(self._live_blocks)
654
+ except BaseException:self.fenced=True;raise
655
+ return self.checkpoint_epoch
656
+ def transact(self,changes,token):
657
+ self._writable();token_key(token)
658
+ if not isinstance(changes,dict) or not changes:raise ValueError('nonempty changes dictionary required')
659
+ encoded=[];items=[];logical_changes={}
660
+ for path,value in sorted(changes.items()):
661
+ path_key(path)
662
+ if value is not None and not isinstance(value,bytes):raise TypeError('bytes or None values required')
663
+ logical_changes[path]=value
664
+ encoded.append([path,None if value is None else b64(value)]);items.append([path,None if value is None else [len(value),digest(value)]])
665
+ intent=digest(canonical(items));old=self._tokens.get(token)
666
+ if old:
667
+ if old[1]!=intent:raise TransactionConflict('token reused with different intent')
668
+ return old[0]
669
+ if self.epoch==MAX_U64:raise StoreError('epoch exhausted')
670
+ if self.generation==MAX_U64:raise StoreError('catalogue generation exhausted before admission')
671
+ e=self.epoch+1;obj={'format':FORMAT,'volume':self.volume,'epoch':e,'parent':self.history,'token':token,'intent':intent,'changes':encoded}
672
+ body=canonical(obj)
673
+ if len(body)>MAX_CAPSULE:raise ValueError('capsule payload exceeds bound')
674
+ if len(self.active)>=SLOTS:self.checkpoint()
675
+ self._ensure_reservations()
676
+ proposal=self._reservation_preview(logical_changes,{token:[e,intent]});plan=None
677
+ if proposal['physical_blocks']>len(self._free):
678
+ self.stats['reservation_exact_fallbacks']+=1
679
+ future_files=dict(self._dirty_files);future_files.update(logical_changes)
680
+ future_tokens=dict(self._dirty_tokens);future_tokens[token]=[e,intent]
681
+ try:
682
+ plan=self._prepare_checkpoint_plan(dirty_files=future_files,dirty_tokens=future_tokens,epoch=e,history=digest(body))
683
+ except AdmissionRejected:
684
+ if not self.active:raise
685
+ # The old accepted window is still bounded or exactly planned.
686
+ self.stats['admission_pressure_checkpoints']+=1;self.checkpoint()
687
+ self._ensure_reservations()
688
+ proposal=self._reservation_preview(logical_changes,{token:[e,intent]})
689
+ if proposal['physical_blocks']>len(self._free):
690
+ plan=self._prepare_checkpoint_plan(dirty_files=dict(logical_changes),dirty_tokens={token:[e,intent]},epoch=e,history=digest(body))
691
+ raw=pack(K_CAPSULE,body,e,self.volume)
692
+ try:
693
+ for replica in range(2):self._pwrite(raw,capsule_offset(e,replica))
694
+ self._sync();self._apply(obj);self.epoch=e;self.history=digest(body)
695
+ self._reservation_adopt(proposal)
696
+ self.active[e]={'body':body,'obj':obj,'digest':self.history};self._checkpoint_plan=plan;self.stats['capsule_batches']+=1
697
+ if plan is None:self.stats['reservation_fast_accepts']+=1
698
+ except BaseException:self.fenced=True;raise
699
+ return e
700
+ def get(self,path):
701
+ self._live();path_key(path)
702
+ try:return self._files[path]
703
+ except KeyError:raise FileNotFoundError(path) from None
704
+ def files(self):self._live();return sorted(self._files)
705
+ def query(self,token):
706
+ self._live();token_key(token);entry=self._tokens.get(token)
707
+ return None if entry is None else {'epoch':entry[0],'intent_sha256':entry[1]}
708
+ def inspect(self):
709
+ self._live();return {'format':FORMAT,'volume':self.volume,'epoch':self.epoch,'checkpoint_epoch':self.checkpoint_epoch,
710
+ 'generation':self.generation,'pool_blocks':self.pool_blocks,'live_blocks':len(self._live_blocks),'free_blocks':len(self._free),
711
+ 'files':self.files(),'tokens':len(self._tokens),'fixed_image_bytes':POOL_START+self.pool_blocks*BLOCK_SIZE,
712
+ 'admission':{**self.admission_reservation(),
713
+ 'planned_blocks':None if self._checkpoint_plan is None else len(self._checkpoint_plan['dependency_writes'])},'io':dict(self.stats)}
714
+
715
+ CutStore=ImageStore=PageStore
716
+ def main(argv=None):
717
+ parser=argparse.ArgumentParser(description=__doc__);sub=parser.add_subparsers(dest='command',required=True)
718
+ for name in ('init','demo','inspect','ls'):
719
+ p=sub.add_parser(name);p.add_argument('image')
720
+ args=parser.parse_args(argv)
721
+ try:
722
+ if args.command in ('init','demo'):
723
+ with PageStore.create(args.image) as store:
724
+ if args.command=='demo':store.transact({'/measurement':b'12.345','/index':b'revision=1'},'demo')
725
+ print(json.dumps(store.inspect(),indent=2))
726
+ else:
727
+ with PageStore(args.image,writable=False) as store:
728
+ print('\n'.join(store.files()) if args.command=='ls' else json.dumps(store.inspect(),indent=2))
729
+ return 0
730
+ except (StoreError,OSError,ValueError,TypeError) as exc:print('error: '+str(exc),file=sys.stderr);return 2
731
+ if __name__=='__main__':raise SystemExit(main())
experiments/benchmark_final.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compare V5, V7 and V8 admission with every final checkpoint included.
3
+
4
+ Linux/POSIX regular-file prototype measurements only. No native NTFS result,
5
+ physical NAND measurement, simulated force delay, or device fault qualification.
6
+ """
7
+ from __future__ import annotations
8
+ import argparse
9
+ import hashlib
10
+ import importlib.util
11
+ import json
12
+ from pathlib import Path
13
+ import platform
14
+ import random
15
+ import statistics
16
+ import sys
17
+ import tempfile
18
+ import time
19
+
20
+ sys.dont_write_bytecode = True
21
+ HERE = Path(__file__).resolve().parent
22
+ ROOT = HERE.parent
23
+
24
+
25
+ def load(name, path):
26
+ spec = importlib.util.spec_from_file_location(name, path)
27
+ module = importlib.util.module_from_spec(spec)
28
+ sys.modules[name] = module
29
+ spec.loader.exec_module(module)
30
+ return module
31
+
32
+
33
+ def sha(path):
34
+ return hashlib.sha256(path.read_bytes()).hexdigest()
35
+
36
+
37
+ def percentile(values, q):
38
+ values = sorted(values)
39
+ point = (len(values) - 1) * q
40
+ lower = int(point)
41
+ upper = min(lower + 1, len(values) - 1)
42
+ return values[lower] + (values[upper] - values[lower]) * (point - lower)
43
+
44
+
45
+ def value(label, index):
46
+ return hashlib.shake_256(f'{label}/{index}'.encode()).digest(128)
47
+
48
+
49
+ def workload(namespace, operations, kind):
50
+ if kind == 'bulk_append':
51
+ # A separate atomic workload: one durable transaction contains 128 new
52
+ # keys. Transaction throughput and logical-key throughput differ.
53
+ return [({f'/append/{i:04d}/{j:04d}': value('append', i * 128 + j)
54
+ for j in range(128)}, f'append-{i:06d}') for i in range(64)]
55
+ names = [f'/file/{i:06d}' for i in range(namespace)]
56
+ candidates = [p for p in names if hashlib.sha256(p.encode()).hexdigest().startswith('0')] if kind == 'hot_prefix' else names
57
+ if not candidates:
58
+ raise ValueError('namespace has no hot-prefix keys')
59
+ rng = random.Random(601131)
60
+ return [({rng.choice(candidates): value(kind, i)}, f'{kind}-{i:06d}') for i in range(operations)]
61
+
62
+
63
+ def allocation(path):
64
+ stat = path.stat()
65
+ return {'apparent_bytes': stat.st_size, 'filesystem_allocated_bytes': getattr(stat, 'st_blocks', 0) * 512}
66
+
67
+
68
+ def run_trial(module, backend, namespace, requests, pool_blocks, kind, trial):
69
+ initial = {f'/file/{i:06d}': value('initial', i) for i in range(namespace)}
70
+ expected = dict(initial)
71
+ epochs = {}
72
+ with tempfile.TemporaryDirectory(prefix='nyarion-admission-benchmark-') as tmp:
73
+ image = Path(tmp) / 'volume.img'
74
+ store = module.PageStore.create(image, initial_files=initial, pool_blocks=pool_blocks)
75
+ before_allocation = allocation(image)
76
+ store.reset_stats()
77
+ latency = []
78
+ started = time.perf_counter_ns()
79
+ for changes, token in requests:
80
+ begin = time.perf_counter_ns()
81
+ epoch = store.transact(changes, token)
82
+ latency.append((time.perf_counter_ns() - begin) / 1e6)
83
+ epochs[token] = epoch
84
+ transaction_end = time.perf_counter_ns()
85
+ store.checkpoint()
86
+ finished = time.perf_counter_ns()
87
+ stats = dict(store.stats)
88
+ if backend == 'v8':
89
+ assert stats.get('full_graph_scans') == 0, 'timed V8 workload must not scan the full graph'
90
+ elapsed = (finished - started) / 1e9
91
+ for changes, _ in requests:
92
+ expected.update(changes)
93
+ assert store.files() == sorted(expected)
94
+ for key, data in expected.items():
95
+ assert store.get(key) == data
96
+ for token, epoch in epochs.items():
97
+ assert store.query(token)['epoch'] == epoch
98
+ assert store.epoch == len(requests)
99
+ after_allocation = allocation(image)
100
+ store.close()
101
+ with module.PageStore(image, writable=False) as reopened:
102
+ assert reopened.epoch == len(requests)
103
+ assert reopened.files() == sorted(expected)
104
+ for key, data in expected.items():
105
+ assert reopened.get(key) == data
106
+ for token, epoch in epochs.items():
107
+ assert reopened.query(token)['epoch'] == epoch
108
+ request_digest = hashlib.sha256(json.dumps(
109
+ [[[key, hashlib.sha256(data).hexdigest()] for key, data in sorted(changes.items())] + [token]
110
+ for changes, token in requests], separators=(',', ':')).encode()).hexdigest()
111
+ logical_updates = sum(len(changes) for changes, _ in requests)
112
+ return {'backend': backend, 'namespace_files': namespace, 'workload': kind,
113
+ 'workload_sha256': request_digest,
114
+ 'trial': trial, 'transactions': len(requests), 'value_bytes': 128,
115
+ 'logical_key_updates': logical_updates,
116
+ 'keys_per_transaction': len(requests[0][0]),
117
+ 'elapsed_with_final_checkpoint_seconds': elapsed,
118
+ 'drained_transactions_per_second': len(requests) / elapsed,
119
+ 'drained_logical_key_updates_per_second': logical_updates / elapsed,
120
+ 'transaction_calls_seconds': (transaction_end - started) / 1e9,
121
+ 'final_checkpoint_ms': (finished - transaction_end) / 1e6,
122
+ 'latencies_ms': latency, 'latency_ms_p50': percentile(latency, .5),
123
+ 'latency_ms_p95': percentile(latency, .95), 'latency_ms_p99': percentile(latency, .99),
124
+ 'latency_ms_max': max(latency), 'engine_stats': stats,
125
+ 'allocation_before': before_allocation, 'allocation_after': after_allocation,
126
+ 'configured_arena_blocks': pool_blocks, 'configured_arena_bytes': pool_blocks * 4096,
127
+ 'all_values_and_exact_token_epochs_verified_before_and_after_reopen': True}
128
+
129
+
130
+ def filesystem_type(path):
131
+ try:
132
+ path = str(Path(path).resolve())
133
+ matches = []
134
+ for line in Path('/proc/mounts').read_text().splitlines():
135
+ fields = line.split()
136
+ mount = fields[1].replace('\\040', ' ')
137
+ if path == mount or path.startswith(mount.rstrip('/') + '/'):
138
+ matches.append((len(mount), fields[2]))
139
+ return max(matches)[1] if matches else 'unknown'
140
+ except (OSError, IndexError):
141
+ return 'unknown'
142
+
143
+
144
+ def main():
145
+ parser = argparse.ArgumentParser(description=__doc__)
146
+ parser.add_argument('--namespaces', nargs='+', type=int, default=[4096, 16384, 65536])
147
+ parser.add_argument('--operations', type=int, default=128)
148
+ parser.add_argument('--trials', type=int, default=3)
149
+ parser.add_argument('--pool-blocks', type=int, default=32768)
150
+ parser.add_argument('--output', type=Path, default=HERE / 'benchmark_final_results.json')
151
+ args = parser.parse_args()
152
+ if min(*args.namespaces, args.operations, args.trials, args.pool_blocks) < 1:
153
+ parser.error('positive sizes required')
154
+ paths = {'v5': HERE / 'baselines/v5.py', 'v7': HERE / 'baselines/v7.py', 'v8': ROOT / 'pagefs.py', 'benchmark': Path(__file__).resolve()}
155
+ hashes = {name: sha(path) for name, path in paths.items()}
156
+ modules = {name: load('v8_benchmark_' + name, paths[name]) for name in ('v5', 'v7', 'v8')}
157
+ rows = []
158
+ configurations = [(n, kind) for n in args.namespaces for kind in ('hot_prefix', 'uniform')]
159
+ configurations.append((0, 'bulk_append'))
160
+ for n, kind in configurations:
161
+ requests = workload(n, args.operations, kind)
162
+ for trial in range(args.trials):
163
+ backends = ('v5', 'v7', 'v8')
164
+ shift = trial % len(backends)
165
+ order = backends[shift:] + backends[:shift]
166
+ for backend in order:
167
+ print(f'{backend}: N={n}, {kind}, trial {trial + 1}', flush=True)
168
+ rows.append(run_trial(modules[backend], backend, n, requests, args.pool_blocks, kind, trial))
169
+ assert hashes == {name: sha(path) for name, path in paths.items()}, 'source changed during measurement'
170
+ summaries = []
171
+ comparisons = []
172
+ for n, kind in configurations:
173
+ grouped = {}
174
+ for backend in ('v5', 'v7', 'v8'):
175
+ group = [row for row in rows if row['backend'] == backend and row['namespace_files'] == n and row['workload'] == kind]
176
+ summary = {'backend': backend, 'namespace_files': n, 'workload': kind, 'trials': len(group),
177
+ 'transactions': group[0]['transactions'],
178
+ 'logical_key_updates': group[0]['logical_key_updates'],
179
+ 'keys_per_transaction': group[0]['keys_per_transaction']}
180
+ for field in ('drained_transactions_per_second', 'drained_logical_key_updates_per_second', 'elapsed_with_final_checkpoint_seconds', 'final_checkpoint_ms', 'latency_ms_p50', 'latency_ms_p95', 'latency_ms_p99', 'latency_ms_max'):
181
+ summary['median_' + field] = statistics.median(row[field] for row in group)
182
+ for field in sorted(set().union(*(row['engine_stats'] for row in group))):
183
+ values = [row['engine_stats'].get(field, 0) for row in group]
184
+ if all(type(v) in (int, float) for v in values):
185
+ summary['median_' + field] = statistics.median(values)
186
+ grouped[backend] = summary
187
+ summaries.append(summary)
188
+ a, b, c = grouped['v5'], grouped['v7'], grouped['v8']
189
+ comparisons.append({'namespace_files': n, 'workload': kind,
190
+ 'transactions': c['transactions'], 'keys_per_transaction': c['keys_per_transaction'],
191
+ 'logical_key_updates': c['logical_key_updates'],
192
+ 'v7_over_v5_drained_throughput': b['median_drained_transactions_per_second'] / a['median_drained_transactions_per_second'],
193
+ 'v8_over_v7_drained_throughput': c['median_drained_transactions_per_second'] / b['median_drained_transactions_per_second'],
194
+ 'v8_over_v5_drained_throughput': c['median_drained_transactions_per_second'] / a['median_drained_transactions_per_second'],
195
+ 'v5_over_v8_host_write_bytes': a['median_bytes_written'] / c['median_bytes_written'],
196
+ 'v5_over_v7_host_write_bytes': a['median_bytes_written'] / b['median_bytes_written'],
197
+ 'v5_final_checkpoint_ms': a['median_final_checkpoint_ms'],
198
+ 'v7_final_checkpoint_ms': b['median_final_checkpoint_ms'],
199
+ 'v8_final_checkpoint_ms': c['median_final_checkpoint_ms']})
200
+ result = {'benchmark': 'V5/V7/V8 end-to-end admission comparison including final window drain',
201
+ 'date': '2026-11-01', 'engine_source_sha256': hashes, 'sources_unchanged_during_measurement': True,
202
+ 'environment': {'os': platform.system(), 'python': platform.python_version(),
203
+ 'temporary_filesystem': filesystem_type(tempfile.gettempdir())},
204
+ 'method': {'trials': args.trials, 'order': 'three-way rotating backend order; each engine starts one trial per workload',
205
+ 'timing': 'all transaction admission/planning, automatic maintenance, and one explicit final checkpoint; setup/open and validation excluded',
206
+ 'logical_workload': 'single-key: identical seeded key sequence and 128-byte values, hot means SHA-256 first nibble 0; separate bulk-append: empty genesis, 64 atomic transactions with 128 new 128-byte keys each (8192 logical key updates)',
207
+ 'verification': 'every file name/value and exact transaction receipt epoch before and after read-only reopen',
208
+ 'host_writes': 'engine requested bytes, not NAND traffic',
209
+ 'capacity': 'all three use the same configured fixed arena'},
210
+ 'limits': ['Different admission guarantees: V5 can acknowledge an arena-undrainable tail; V7 and V8 precheck logical checkpoint capacity.',
211
+ 'POSIX regular-file prototype comparison, not native NTFS.',
212
+ 'All live logical data remain in RAM; no physical power-cut or device qualification.',
213
+ 'No simulated flush latency, cache dropping, or direct I/O.'],
214
+ 'trials': rows, 'summaries': summaries, 'comparisons': comparisons}
215
+ args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + '\n')
216
+ print(json.dumps(comparisons, indent=2), flush=True)
217
+
218
+
219
+ if __name__ == '__main__':
220
+ main()
experiments/benchmark_final_results.json ADDED
The diff for this file is too large to render. See raw diff
 
experiments/compatibility_results.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "passed": true,
3
+ "persistent_format": 5,
4
+ "source_sha256": {
5
+ "v5": "3685cd31ebf282050e26001439f3bd06b9cf3cff765ab7085399786c2f9616bd",
6
+ "v7": "a67c93290fd561eff480f84b483dee0b44833c694da9b96c5d830af00616b980",
7
+ "v8": "e22e219b85e4b2a777b295ecad616cf4ef400e0189d7d7583d14f432d89ed807"
8
+ },
9
+ "volumes": 2,
10
+ "transactions_per_volume": 200,
11
+ "reader_checks": [
12
+ {
13
+ "initial_writer": "v5",
14
+ "subsequent_writer": "v8",
15
+ "reader": "v5",
16
+ "transactions": 200,
17
+ "exact_receipt_epochs_and_contents_verified": true
18
+ },
19
+ {
20
+ "initial_writer": "v5",
21
+ "subsequent_writer": "v8",
22
+ "reader": "v7",
23
+ "transactions": 200,
24
+ "exact_receipt_epochs_and_contents_verified": true
25
+ },
26
+ {
27
+ "initial_writer": "v5",
28
+ "subsequent_writer": "v8",
29
+ "reader": "v8",
30
+ "transactions": 200,
31
+ "exact_receipt_epochs_and_contents_verified": true
32
+ },
33
+ {
34
+ "initial_writer": "v7",
35
+ "subsequent_writer": "v8",
36
+ "reader": "v5",
37
+ "transactions": 200,
38
+ "exact_receipt_epochs_and_contents_verified": true
39
+ },
40
+ {
41
+ "initial_writer": "v7",
42
+ "subsequent_writer": "v8",
43
+ "reader": "v7",
44
+ "transactions": 200,
45
+ "exact_receipt_epochs_and_contents_verified": true
46
+ },
47
+ {
48
+ "initial_writer": "v7",
49
+ "subsequent_writer": "v8",
50
+ "reader": "v8",
51
+ "transactions": 200,
52
+ "exact_receipt_epochs_and_contents_verified": true
53
+ }
54
+ ],
55
+ "scope": "format compatibility; older writers do not inherit V8 admission guarantees"
56
+ }
experiments/reservation_bound_results.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "passed": true,
3
+ "engine_source_sha256": "e22e219b85e4b2a777b295ecad616cf4ef400e0189d7d7583d14f432d89ed807",
4
+ "exact_compiler_bound_checks": 360,
5
+ "checkpoints": 36,
6
+ "reopens": 12,
7
+ "maximum_exact_physical_blocks": 102,
8
+ "greatest_observed_bound_slack_blocks": 6,
9
+ "cached_plan_not_installed_by_oracle": true,
10
+ "scope": "finite exact-compiler comparison after mixed overwrites/deletes/inline/blob changes; not a universal bound proof"
11
+ }
experiments/verify_admission.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Finite capacity sweep of V5/V7/V8 admission and exact final arena drainability.
3
+
4
+ The guarantee tested is logical arena drainability, not future host filesystem
5
+ or device capacity, permanent media failure, or indefinite token retention.
6
+ """
7
+ from __future__ import annotations
8
+ import errno
9
+ import hashlib
10
+ import importlib.util
11
+ import json
12
+ from pathlib import Path
13
+ import sys
14
+ import tempfile
15
+
16
+ sys.dont_write_bytecode = True
17
+ HERE = Path(__file__).resolve().parent
18
+ ROOT = HERE.parent
19
+
20
+
21
+ def load(name, path):
22
+ spec = importlib.util.spec_from_file_location(name, path)
23
+ module = importlib.util.module_from_spec(spec)
24
+ sys.modules[name] = module
25
+ spec.loader.exec_module(module)
26
+ return module
27
+
28
+
29
+ def sha(path):
30
+ return hashlib.sha256(path.read_bytes()).hexdigest()
31
+
32
+
33
+ def logical_check(store, files, tokens):
34
+ assert store.files() == sorted(files)
35
+ for key, value in files.items():
36
+ assert store.get(key) == value
37
+ for token, epoch in tokens.items():
38
+ assert store.query(token)['epoch'] == epoch
39
+
40
+
41
+ def run_case(module, backend, pool, initial_count, payload, window):
42
+ files = {f'/initial/{i}': bytes([i + 1]) * 128 for i in range(initial_count)}
43
+ tokens = {}
44
+ row = {'backend': backend, 'pool_blocks': pool, 'initial_files': initial_count,
45
+ 'replacement_bytes': payload, 'checkpoint_window': window,
46
+ 'acknowledged': 0, 'clean_refusals': 0, 'executed_checkpoints': 0,
47
+ 'certified_acked_windows': 0, 'certificate_kinds': {}, 'v5_ack_then_checkpoint_enospc': False}
48
+ with tempfile.TemporaryDirectory(prefix='nyarion-admission-sweep-') as tmp:
49
+ image = Path(tmp) / 'volume.img'
50
+ try:
51
+ store = module.PageStore.create(image, initial_files=files, pool_blocks=pool)
52
+ except OSError as exc:
53
+ if exc.errno != errno.ENOSPC:
54
+ raise
55
+ row['creation_refused'] = True
56
+ return row
57
+ try:
58
+ for i in range(8):
59
+ key = f'/value/{i % 3}'
60
+ data = bytes([(i + 31) % 251]) * payload
61
+ changes = {key: None if i == 7 else data}
62
+ token = f'capacity-{i}'
63
+ old_epoch = store.epoch
64
+ try:
65
+ epoch = store.transact(changes, token)
66
+ except OSError as exc:
67
+ if exc.errno != errno.ENOSPC:
68
+ raise
69
+ if backend in ('v7', 'v8'):
70
+ row['clean_refusals'] += 1
71
+ assert store.epoch == old_epoch
72
+ assert store.query(token) is None
73
+ logical_check(store, files, tokens)
74
+ else:
75
+ # V5 can fail during a pressure checkpoint. This sweep's
76
+ # short windows normally expose the gap explicitly below.
77
+ row['v5_ack_then_checkpoint_enospc'] = bool(tokens)
78
+ break
79
+ row['acknowledged'] += 1
80
+ tokens[token] = epoch
81
+ for path, value in changes.items():
82
+ if value is None:
83
+ files.pop(path, None)
84
+ else:
85
+ files[path] = value
86
+ if backend in ('v7', 'v8'):
87
+ # Do not call checkpoint_plan here: that would cache exact
88
+ # output and could mask the normal reservation fast path.
89
+ if backend == 'v8':
90
+ certificate = store.admission_reservation()
91
+ assert certificate['tail_certified']
92
+ kind = certificate['certificate_kind']
93
+ row['certificate_kinds'][kind] = row['certificate_kinds'].get(kind, 0) + 1
94
+ row['certified_acked_windows'] += 1
95
+ if i % window == window - 1:
96
+ try:
97
+ store.checkpoint()
98
+ except OSError as exc:
99
+ if exc.errno != errno.ENOSPC:
100
+ raise
101
+ assert backend == 'v5', 'admitted safe window failed its arena checkpoint'
102
+ row['v5_ack_then_checkpoint_enospc'] = True
103
+ break
104
+ row['executed_checkpoints'] += 1
105
+ logical_check(store, files, tokens)
106
+ if backend in ('v7', 'v8') and store.epoch > store.checkpoint_epoch:
107
+ store.checkpoint()
108
+ row['executed_checkpoints'] += 1
109
+ logical_check(store, files, tokens)
110
+ finally:
111
+ store.close()
112
+ with module.PageStore(image, writable=False) as recovered:
113
+ assert recovered.epoch == len(tokens)
114
+ logical_check(recovered, files, tokens)
115
+ row['all_acknowledged_values_and_token_epochs_recovered'] = True
116
+ return row
117
+
118
+
119
+ def main():
120
+ paths = {'v5': HERE / 'baselines/v5.py', 'v7': HERE / 'baselines/v7.py', 'v8': ROOT / 'pagefs.py', 'sweep': Path(__file__).resolve()}
121
+ hashes = {name: sha(path) for name, path in paths.items()}
122
+ modules = {name: load('admission_sweep_' + name, paths[name]) for name in ('v5', 'v7', 'v8')}
123
+ rows = []
124
+ for pool in (16, 20, 24, 32, 48, 64, 96, 128):
125
+ for initial_count in (0, 4, 12):
126
+ for payload in (64, 512, 4096, 16384, 40960):
127
+ for window in (1, 4):
128
+ for backend in ('v5', 'v7', 'v8'):
129
+ rows.append(run_case(modules[backend], backend, pool, initial_count, payload, window))
130
+ assert hashes == {name: sha(path) for name, path in paths.items()}, 'source changed during sweep'
131
+ new = [row for row in rows if row['backend'] == 'v8']
132
+ exact = [row for row in rows if row['backend'] == 'v7']
133
+ old = [row for row in rows if row['backend'] == 'v5']
134
+ gaps = sum(row['v5_ack_then_checkpoint_enospc'] for row in old)
135
+ assert gaps > 0, 'sweep must demonstrate the V5 counterexample'
136
+ result = {'passed': True, 'source_sha256': hashes, 'cases_per_backend': len(new),
137
+ 'total_backend_cases': len(rows), 'v5_acknowledged_undrainable_cases': gaps,
138
+ 'v7_acknowledged_undrainable_cases': 0,
139
+ 'v8_acknowledged_undrainable_cases': 0,
140
+ 'v7_clean_capacity_refusals': sum(row['clean_refusals'] for row in exact),
141
+ 'v7_acknowledged_transactions': sum(row['acknowledged'] for row in exact),
142
+ 'v8_acknowledged_transactions': sum(row['acknowledged'] for row in new),
143
+ 'v8_clean_capacity_refusals': sum(row['clean_refusals'] for row in new),
144
+ 'v8_certified_acknowledged_windows': sum(row['certified_acked_windows'] for row in new),
145
+ 'v8_executed_checkpoints': sum(row['executed_checkpoints'] for row in new),
146
+ 'all_acknowledged_data_and_receipt_epochs_recovered': True,
147
+ 'scope': 'finite configurable logical-arena sweep; eight offers per case, not hardware faults or indefinite progress',
148
+ 'cases': rows}
149
+ (HERE / 'admission_results.json').write_text(json.dumps(result, indent=2, sort_keys=True) + '\n')
150
+ print(json.dumps({k: v for k, v in result.items() if k != 'cases'}, indent=2))
151
+
152
+
153
+ if __name__ == '__main__':
154
+ main()
experiments/verify_compatibility.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Format-5 exchange across frozen V5/V7 writers and the current V8 engine."""
3
+ import hashlib
4
+ import importlib.util
5
+ import json
6
+ from pathlib import Path
7
+ import sys
8
+ import tempfile
9
+
10
+ HERE = Path(__file__).resolve().parent
11
+ ROOT = HERE.parent
12
+ sys.dont_write_bytecode = True
13
+
14
+
15
+ def load(name, path):
16
+ spec = importlib.util.spec_from_file_location(name, path)
17
+ module = importlib.util.module_from_spec(spec)
18
+ sys.modules[name] = module
19
+ spec.loader.exec_module(module)
20
+ return module
21
+
22
+
23
+ def main():
24
+ paths = {'v5': HERE / 'baselines/v5.py', 'v7': HERE / 'baselines/v7.py',
25
+ 'v8': ROOT / 'pagefs.py'}
26
+ hashes = {name: hashlib.sha256(path.read_bytes()).hexdigest() for name, path in paths.items()}
27
+ modules = {name: load('compat_' + name, path) for name, path in paths.items()}
28
+ checks = []
29
+ for origin in ('v5', 'v7'):
30
+ expected = {f'/entry/{i:04d}': bytes([i % 251]) * 128 for i in range(128)}
31
+ receipts = {}
32
+ with tempfile.TemporaryDirectory(prefix='nyarion-v8-compatible-') as tmp:
33
+ image = Path(tmp) / 'compatible.img'
34
+ with modules[origin].PageStore.create(image, initial_files=expected, pool_blocks=2048) as store:
35
+ for i in range(100):
36
+ key, data, token = f'/entry/{i:04d}', bytes([i]) * 1024, f'old-{i}'
37
+ receipts[token] = store.transact({key: data}, token)
38
+ expected[key] = data
39
+ store.checkpoint()
40
+ with modules['v8'].PageStore(image) as store:
41
+ for key, data in expected.items():
42
+ assert store.get(key) == data
43
+ for i in range(100):
44
+ key, data, token = f'/entry/{i:04d}', bytes([i + 1]) * 128, f'new-{i}'
45
+ receipts[token] = store.transact({key: data}, token)
46
+ expected[key] = data
47
+ store.checkpoint()
48
+ for reader in ('v5', 'v7', 'v8'):
49
+ with modules[reader].PageStore(image, writable=False) as store:
50
+ assert store.epoch == 200
51
+ assert store.files() == sorted(expected)
52
+ for key, data in expected.items():
53
+ assert store.get(key) == data
54
+ for token, epoch in receipts.items():
55
+ assert store.query(token)['epoch'] == epoch
56
+ checks.append({'initial_writer': origin, 'subsequent_writer': 'v8',
57
+ 'reader': reader, 'transactions': 200,
58
+ 'exact_receipt_epochs_and_contents_verified': True})
59
+ assert {name: hashlib.sha256(path.read_bytes()).hexdigest() for name, path in paths.items()} == hashes
60
+ result = {'passed': True, 'persistent_format': 5, 'source_sha256': hashes,
61
+ 'volumes': 2, 'transactions_per_volume': 200, 'reader_checks': checks,
62
+ 'scope': 'format compatibility; older writers do not inherit V8 admission guarantees'}
63
+ (HERE / 'compatibility_results.json').write_text(json.dumps(result, indent=2) + '\n')
64
+ print(json.dumps(result, indent=2))
65
+
66
+
67
+ if __name__ == '__main__':
68
+ main()
experiments/verify_reservation_bound.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compare the incremental reservation bound to the uncached exact compiler.
3
+
4
+ This oracle is deliberately outside timing and does not install a cached plan.
5
+ The operational capacity sweep does not invoke the exact-plan query at all.
6
+ """
7
+ import hashlib
8
+ import importlib.util
9
+ import json
10
+ from pathlib import Path
11
+ import random
12
+ import sys
13
+ import tempfile
14
+
15
+ HERE = Path(__file__).resolve().parent
16
+ ROOT = HERE.parent
17
+ sys.dont_write_bytecode = True
18
+
19
+
20
+ def load(path):
21
+ spec = importlib.util.spec_from_file_location('reservation_bound_engine', path)
22
+ module = importlib.util.module_from_spec(spec)
23
+ sys.modules[spec.name] = module
24
+ spec.loader.exec_module(module)
25
+ return module
26
+
27
+
28
+ def main():
29
+ engine_path = ROOT / 'pagefs.py'
30
+ source_hash = hashlib.sha256(engine_path.read_bytes()).hexdigest()
31
+ module = load(engine_path)
32
+ rng = random.Random(701154)
33
+ checks = 0
34
+ checkpoints = 0
35
+ reopens = 0
36
+ greatest_slack = 0
37
+ max_exact = 0
38
+ for case in range(4):
39
+ with tempfile.TemporaryDirectory(prefix='nyarion-bound-oracle-') as tmp:
40
+ path = Path(tmp) / 'oracle.img'
41
+ expected = {f'/seed/{i:04d}': bytes([i]) * (128 if case < 2 else 257) for i in range(64)}
42
+ store = module.PageStore.create(path, initial_files=expected, pool_blocks=4096)
43
+ tokens = {}
44
+ try:
45
+ for i in range(90):
46
+ keys = [f'/seed/{rng.randrange(80):04d}']
47
+ if i % 9 == 0:
48
+ keys.append('/escaped/"control\t' + ('界' * 12))
49
+ changes = {}
50
+ for key in keys:
51
+ size = (0, 1, 128, 256, 257, 3992, 8192)[rng.randrange(7)]
52
+ changes[key] = None if i % 13 == 0 else rng.randbytes(size)
53
+ token = f'oracle-{case}-{i:04d}'
54
+ epoch = store.transact(changes, token)
55
+ tokens[token] = epoch
56
+ for key, value in changes.items():
57
+ if value is None:
58
+ expected.pop(key, None)
59
+ else:
60
+ expected[key] = value
61
+ budget = store.admission_reservation()
62
+ prior_cached = store._checkpoint_plan
63
+ plan = store._prepare_checkpoint_plan()
64
+ assert store._checkpoint_plan is prior_cached, 'oracle must not install a plan'
65
+ exact = len(plan['dependency_writes'])
66
+ bound = budget['reserved_upper_blocks']
67
+ assert exact <= bound, (case, i, exact, bound)
68
+ assert exact <= len(store._free), 'acknowledged window must fit the exact compiler'
69
+ max_exact = max(max_exact, exact)
70
+ greatest_slack = max(greatest_slack, bound - exact)
71
+ checks += 1
72
+ if i % 11 == 10:
73
+ store.checkpoint()
74
+ checkpoints += 1
75
+ if i % 30 == 29:
76
+ store.close()
77
+ store = module.PageStore(path)
78
+ reopens += 1
79
+ assert store.files() == sorted(expected)
80
+ for key, value in expected.items():
81
+ assert store.get(key) == value
82
+ for token, epoch in tokens.items():
83
+ assert store.query(token)['epoch'] == epoch
84
+ store.checkpoint()
85
+ checkpoints += 1
86
+ finally:
87
+ store.close()
88
+ assert hashlib.sha256(engine_path.read_bytes()).hexdigest() == source_hash, 'engine changed during oracle checks'
89
+ result = {'passed': True, 'engine_source_sha256': source_hash,
90
+ 'exact_compiler_bound_checks': checks, 'checkpoints': checkpoints,
91
+ 'reopens': reopens, 'maximum_exact_physical_blocks': max_exact,
92
+ 'greatest_observed_bound_slack_blocks': greatest_slack,
93
+ 'cached_plan_not_installed_by_oracle': True,
94
+ 'scope': 'finite exact-compiler comparison after mixed overwrites/deletes/inline/blob changes; not a universal bound proof'}
95
+ (HERE / 'reservation_bound_results.json').write_text(json.dumps(result, indent=2) + '\n')
96
+ print(json.dumps(result, indent=2))
97
+
98
+
99
+ if __name__ == '__main__':
100
+ main()
experiments/verify_weighted_budget.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Independent deterministic raw-encoding/shape oracle for weighted budgets.
3
+
4
+ This exercises pure helper functions, not persistent storage. Actual checkpoint,
5
+ fault and admission checks are separate evidence layers.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import importlib.util
11
+ import json
12
+ from pathlib import Path
13
+ import random
14
+ import sys
15
+
16
+ ROOT = Path(__file__).resolve().parents[1]
17
+
18
+
19
+ def main():
20
+ source = ROOT / 'pagefs.py'
21
+ source_hash = hashlib.sha256(source.read_bytes()).hexdigest()
22
+ spec = importlib.util.spec_from_file_location('weighted_budget_oracle_engine', source)
23
+ module = importlib.util.module_from_spec(spec)
24
+ sys.modules[spec.name] = module
25
+ spec.loader.exec_module(module)
26
+ store = module.PageStore.__new__(module.PageStore)
27
+ store.reset_stats()
28
+ rng = random.Random(889104)
29
+ checks = 0
30
+ updates = 0
31
+
32
+ for prefix in ('', '0' * 50):
33
+ original_hash = module.hash_key
34
+ if prefix:
35
+ module.hash_key = lambda key, base=original_hash, p=prefix: p + base(key)[len(p):]
36
+ values = {}
37
+ node = None
38
+
39
+ def fresh_canonical_count(entries, depth):
40
+ if not entries:
41
+ return 0
42
+ raw = module.canonical({'family': 'files', 'type': 'leaf',
43
+ 'depth': depth, 'entries': entries})
44
+ if len(raw) <= module.PAGE_PAYLOAD:
45
+ return 1
46
+ if depth == 64:
47
+ return module.MAX_POOL_BLOCKS
48
+ groups = {}
49
+ for key, value in entries.items():
50
+ groups.setdefault(module.hash_key(key)[depth], {})[key] = value
51
+ return 1 + sum(fresh_canonical_count(group, depth + 1)
52
+ for group in groups.values())
53
+
54
+ def check_shape(current, depth, route_prefix):
55
+ if current is None:
56
+ return {}
57
+ assert current['depth'] == depth
58
+ if current['type'] in ('leaf', 'overflow'):
59
+ assert current['entry_sum'] == sum(current['entries'].values())
60
+ mapped = {key: values[key] for key in current['entries']}
61
+ assert all(module.hash_key(key).startswith(route_prefix) for key in mapped)
62
+ assert all(current['entries'][key] == len(module.canonical(key)) + 1 +
63
+ len(module.canonical(values[key])) for key in mapped)
64
+ raw = module.canonical({'family': 'files', 'type': 'leaf',
65
+ 'depth': depth, 'entries': mapped})
66
+ assert store._budget_leaf_bytes('files', depth, current['entries'],
67
+ current['entry_sum']) == len(raw)
68
+ assert current['nodes'] == (1 if current['type'] == 'leaf'
69
+ else module.MAX_POOL_BLOCKS)
70
+ return mapped
71
+ assert current['type'] == 'branch' and current['children']
72
+ assert current['nodes'] == 1 + sum(child['nodes']
73
+ for child in current['children'].values())
74
+ result = {}
75
+ for nibble, child in current['children'].items():
76
+ entries = check_shape(child, depth + 1, route_prefix + nibble)
77
+ assert not result.keys() & entries.keys()
78
+ result.update(entries)
79
+ return result
80
+
81
+ try:
82
+ for i in range(2200):
83
+ key = '/e/' + str(rng.randrange(120)) + (
84
+ chr(1) if i % 17 == 0 else '\U0001f512' if i % 19 == 0 else '')
85
+ if rng.randrange(4) == 0:
86
+ value = None
87
+ elif rng.randrange(7) == 0:
88
+ value = {'blob': module.BOUND_DESC}
89
+ else:
90
+ value = {'inline': module.b64(rng.randbytes(
91
+ rng.choice((0, 16, 127, 128, 255, 256))))}
92
+ weight = None if value is None else len(module.canonical(key)) + 1 + len(module.canonical(value))
93
+ node = store._budget_update('files', node, key, weight, 0)
94
+ if value is None:
95
+ values.pop(key, None)
96
+ else:
97
+ values[key] = value
98
+ updates += 1
99
+ if i % 11 == 0:
100
+ assert check_shape(node, 0, '') == values
101
+ assert store._budget_nodes(node) >= fresh_canonical_count(values, 0)
102
+ checks += 1
103
+ finally:
104
+ module.hash_key = original_hash
105
+
106
+ assert hashlib.sha256(source.read_bytes()).hexdigest() == source_hash, 'engine changed during verification'
107
+ result = {'passed': True, 'engine_source_sha256': source_hash,
108
+ 'seed': 889104, 'mixed_updates': updates,
109
+ 'full_weight_shape_oracle_checks': checks,
110
+ 'forced_common_prefix_digits': 50,
111
+ 'value_cases': 'empty, inline up to 256 bytes, maximum-width blob descriptor, deletion',
112
+ 'key_cases': 'ordinary ASCII, escaped control character, supplementary Unicode',
113
+ 'scope': 'pure weighted helper stress and fresh raw-JSON shape comparison; not storage I/O, hardware faults or a universal proof'}
114
+ target = ROOT / 'experiments/weighted_budget_results.json'
115
+ target.write_text(json.dumps(result, indent=2) + '\n')
116
+ print(json.dumps(result, indent=2))
117
+
118
+
119
+ if __name__ == '__main__':
120
+ main()
experiments/weighted_budget_results.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "passed": true,
3
+ "engine_source_sha256": "e22e219b85e4b2a777b295ecad616cf4ef400e0189d7d7583d14f432d89ed807",
4
+ "seed": 889104,
5
+ "mixed_updates": 4400,
6
+ "full_weight_shape_oracle_checks": 400,
7
+ "forced_common_prefix_digits": 50,
8
+ "value_cases": "empty, inline up to 256 bytes, maximum-width blob descriptor, deletion",
9
+ "key_cases": "ordinary ASCII, escaped control character, supplementary Unicode",
10
+ "scope": "pure weighted helper stress and fresh raw-JSON shape comparison; not storage I/O, hardware faults or a universal proof"
11
+ }
nyarion/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """NYARION standalone image-engine tools.
2
+
3
+ The durable engine is supplied in the sibling ``pagefs`` module so it can also
4
+ be inspected and used directly without installing this command-line package.
5
+ """
6
+
7
+ __version__ = '8.0.0'
8
+
nyarion/__main__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
4
+
nyarion/cli.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Command-line access to NYARION's POSIX regular-file image engine."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import base64
6
+ import hashlib
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import sys
11
+
12
+ import pagefs
13
+ from . import __version__
14
+
15
+ INPUT_LIMIT = 1024 * 1024
16
+
17
+
18
+ def _json(value):
19
+ print(json.dumps(value, sort_keys=True, ensure_ascii=True, indent=2))
20
+
21
+
22
+ def _read(path, limit=INPUT_LIMIT):
23
+ if path == '-':
24
+ data = sys.stdin.buffer.read(limit + 1)
25
+ else:
26
+ with open(path, 'rb') as stream:
27
+ data = stream.read(limit + 1)
28
+ if len(data) > limit:
29
+ raise ValueError(f'input exceeds {limit} byte command limit')
30
+ return data
31
+
32
+
33
+ def _write(path, data):
34
+ """Exclusive creation keeps output paths from replacing an image or input."""
35
+ if path == '-':
36
+ sys.stdout.buffer.write(data)
37
+ sys.stdout.buffer.flush()
38
+ return
39
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o600)
40
+ with os.fdopen(descriptor, 'wb') as stream:
41
+ stream.write(data)
42
+ stream.flush()
43
+ os.fsync(stream.fileno())
44
+
45
+
46
+ def _pairs(items):
47
+ obj = {}
48
+ for key, value in items:
49
+ if key in obj:
50
+ raise ValueError(f'duplicate JSON key: {key!r}')
51
+ obj[key] = value
52
+ return obj
53
+
54
+
55
+ def _transaction(path):
56
+ try:
57
+ obj = json.loads(_read(path).decode('utf8'), object_pairs_hook=_pairs,
58
+ parse_constant=lambda value: (_ for _ in ()).throw(ValueError('invalid JSON constant')))
59
+ except (UnicodeError, RecursionError) as exc:
60
+ raise ValueError('transaction must be bounded UTF-8 JSON') from exc
61
+ if not isinstance(obj, dict) or set(obj) != {'token', 'changes'}:
62
+ raise ValueError('transaction fields must be exactly token and changes')
63
+ pagefs.token_key(obj['token'])
64
+ changes = obj['changes']
65
+ if not isinstance(changes, dict) or not changes:
66
+ raise ValueError('transaction changes must be a nonempty map')
67
+ decoded = {}
68
+ for key, entry in changes.items():
69
+ pagefs.path_key(key)
70
+ if entry is None:
71
+ decoded[key] = None
72
+ elif isinstance(entry, dict) and set(entry) == {'base64'}:
73
+ decoded[key] = pagefs.unb64(entry['base64'])
74
+ else:
75
+ raise ValueError('each change must be null or an object containing only base64')
76
+ return decoded, obj['token']
77
+
78
+
79
+ def _snapshot(store):
80
+ files = []
81
+ for path in store.files():
82
+ data = store.get(path)
83
+ files.append({'path': path, 'base64': base64.b64encode(data).decode('ascii'),
84
+ 'length': len(data), 'sha256': hashlib.sha256(data).hexdigest()})
85
+ # Receipt enumeration is a release-local export interface. Each value is
86
+ # retrieved through the public query function after recovery validation.
87
+ receipts = [{'token': token, **store.query(token)} for token in sorted(store._tokens)]
88
+ body = {'export_format': 1, 'engine_format': pagefs.FORMAT, 'volume': store.volume,
89
+ 'epoch': store.epoch, 'files': files, 'receipts': receipts}
90
+ body['snapshot_sha256'] = hashlib.sha256(pagefs.canonical(body)).hexdigest()
91
+ return body
92
+
93
+
94
+ def parser():
95
+ result = argparse.ArgumentParser(
96
+ prog='nyarion',
97
+ description='NYARION regular-file storage engine. Requires Python 3 and POSIX; this is not a mounted filesystem.')
98
+ result.add_argument('--version', action='version', version='NYARION ' + __version__)
99
+ commands = result.add_subparsers(dest='command', required=True)
100
+ init = commands.add_parser('init', help='exclusively create an empty image')
101
+ init.add_argument('image')
102
+ init.add_argument('--pool-blocks', type=int, default=pagefs.DEFAULT_POOL_BLOCKS,
103
+ help='number of 4 KiB physical arena blocks, including replicas')
104
+ put = commands.add_parser('put', help='durably replace one complete logical file value')
105
+ put.add_argument('image'); put.add_argument('key'); put.add_argument('--token', required=True)
106
+ data = put.add_mutually_exclusive_group(required=True)
107
+ data.add_argument('--file', metavar='PATH', help='input bytes; - reads stdin')
108
+ data.add_argument('--text', help='UTF-8 text value')
109
+ get = commands.add_parser('get', help='read a logical value as raw bytes')
110
+ get.add_argument('image'); get.add_argument('key')
111
+ get.add_argument('--output', default='-', help='new output file; default is stdout')
112
+ ls = commands.add_parser('ls', aliases=['list'], help='list logical keys as JSON')
113
+ ls.add_argument('image')
114
+ delete = commands.add_parser('delete', help='durably remove one logical key')
115
+ delete.add_argument('image'); delete.add_argument('key'); delete.add_argument('--token', required=True)
116
+ tx = commands.add_parser('transact', help='apply one atomic JSON transaction')
117
+ tx.add_argument('image'); tx.add_argument('transaction', help='UTF-8 JSON path, or - for stdin')
118
+ for command, help_text in (
119
+ ('checkpoint', 'materialize and publish the complete outstanding prefix'),
120
+ ('inspect', 'inspect recovered metadata without repairing'),
121
+ ('plan', 'show an exact checkpoint publication summary without writing'),
122
+ ('verify', 'validate recovery and report a logical snapshot digest without repairing'),
123
+ ('repair', 'open writable, restore available mirror redundancy, and inspect'),
124
+ ):
125
+ cmd = commands.add_parser(command, help=help_text); cmd.add_argument('image')
126
+ query = commands.add_parser('query', help='query a durable retry receipt')
127
+ query.add_argument('image'); query.add_argument('token')
128
+ export = commands.add_parser('export', help='export bytes and receipt metadata as audit JSON')
129
+ export.add_argument('image'); export.add_argument('--output', default='-', help='new output file; default is stdout')
130
+ return result
131
+
132
+
133
+ def main(argv=None):
134
+ args = parser().parse_args(argv)
135
+ try:
136
+ command = args.command
137
+ if command == 'init':
138
+ with pagefs.PageStore.create(args.image, pool_blocks=args.pool_blocks) as store:
139
+ _json(store.inspect())
140
+ return 0
141
+ if command == 'put':
142
+ value = args.text.encode('utf8') if args.text is not None else _read(args.file)
143
+ changes, token = {args.key: value}, args.token
144
+ elif command == 'delete':
145
+ changes, token = {args.key: None}, args.token
146
+ elif command == 'transact':
147
+ changes, token = _transaction(args.transaction)
148
+ writable = command in ('put', 'delete', 'transact', 'checkpoint', 'repair')
149
+ with pagefs.PageStore(args.image, writable=writable) as store:
150
+ if command in ('put', 'delete', 'transact'):
151
+ epoch = store.transact(changes, token)
152
+ _json({'epoch': epoch, 'receipt': store.query(token)})
153
+ elif command == 'get':
154
+ _write(args.output, store.get(args.key))
155
+ elif command in ('ls', 'list'):
156
+ _json(store.files())
157
+ elif command == 'checkpoint':
158
+ _json({'checkpoint_epoch': store.checkpoint(), 'state': store.inspect()})
159
+ elif command in ('inspect', 'repair'):
160
+ _json(store.inspect())
161
+ elif command == 'plan':
162
+ _json(store.checkpoint_plan())
163
+ elif command == 'query':
164
+ _json(store.query(args.token))
165
+ elif command in ('verify', 'export'):
166
+ snapshot = _snapshot(store)
167
+ if command == 'export':
168
+ _write(args.output, (json.dumps(snapshot, sort_keys=True, ensure_ascii=True, indent=2) + '\n').encode('ascii'))
169
+ else:
170
+ _json({'valid': True, 'epoch': store.epoch, 'files': len(snapshot['files']),
171
+ 'receipts': len(snapshot['receipts']), 'snapshot_sha256': snapshot['snapshot_sha256']})
172
+ return 0
173
+ except (pagefs.StoreError, OSError, ValueError, TypeError) as exc:
174
+ print('nyarion: ' + str(exc), file=sys.stderr)
175
+ return 2
176
+
177
+
178
+ if __name__ == '__main__':
179
+ raise SystemExit(main())
180
+
package_release.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Bind the complete research ZIP to validated sources and runtime artifacts."""
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import re
7
+ import zipfile
8
+
9
+ ROOT = Path(__file__).resolve().parent
10
+
11
+
12
+ def sha(path):
13
+ return hashlib.sha256(path.read_bytes()).hexdigest()
14
+
15
+
16
+ def main():
17
+ engine_hash = sha(ROOT / 'pagefs.py')
18
+ bench = json.loads((ROOT / 'experiments/benchmark_final_results.json').read_text())
19
+ admission = json.loads((ROOT / 'experiments/admission_results.json').read_text())
20
+ bound = json.loads((ROOT / 'experiments/reservation_bound_results.json').read_text())
21
+ assert bound['passed'] and bound['engine_source_sha256'] == engine_hash
22
+ weighted = json.loads((ROOT / 'experiments/weighted_budget_results.json').read_text())
23
+ assert weighted['passed'] and weighted['engine_source_sha256'] == engine_hash
24
+ audit = json.loads((ROOT / 'evidence/audit_release.json').read_text())
25
+ assert audit['passed'] and audit['engine_sha256'] == engine_hash
26
+ crash = json.loads((ROOT / 'crash_image_results.json').read_text())
27
+ seq = json.loads((ROOT / 'sequence_results.json').read_text())
28
+ compat = json.loads((ROOT / 'experiments/compatibility_results.json').read_text())
29
+ smoke = json.loads((ROOT / 'evidence/release_smoke.json').read_text())
30
+ build = json.loads((ROOT / 'dist/build_artifacts.json').read_text())
31
+ assert bench['sources_unchanged_during_measurement']
32
+ assert bench['engine_source_sha256']['v8'] == engine_hash
33
+ assert admission['passed'] and admission['source_sha256']['v8'] == engine_hash
34
+ assert admission['v8_acknowledged_undrainable_cases'] == 0
35
+ for result in (crash, seq):
36
+ assert result['passed'] and result['engine_source_sha256'] == engine_hash
37
+ assert engine_hash in compat['source_sha256'].values() and compat['passed']
38
+ assert smoke['passed'] and smoke['engine_sha256'] == engine_hash
39
+ assert build['engine_sha256'] == engine_hash
40
+ for item in build['artifacts']:
41
+ assert sha(ROOT / 'dist' / item['name']) == item['sha256']
42
+ tests = (ROOT / 'evidence/tests.txt').read_text()
43
+ assert tests.rstrip().endswith('OK')
44
+ test_count = int(re.search(r'Ran (\d+) tests', tests).group(1))
45
+ assert not re.search(r'__[A-Z_]+__', (ROOT / 'NYARION_FS_Manuscript.md').read_text())
46
+ provenance = {'release': '8.0.0', 'date': '2026-11-01', 'persistent_format': 5,
47
+ 'engine_sha256': engine_hash, 'unit_integration_tests': test_count,
48
+ 'capacity_backend_cases': admission['total_backend_cases'],
49
+ 'exact_compiler_bound_checks': bound['exact_compiler_bound_checks'],
50
+ 'weighted_helper_updates': weighted['mixed_updates'], 'unified_offline_audit_passed': True,
51
+ 'v5_acknowledged_undrainable_cases': admission['v5_acknowledged_undrainable_cases'],
52
+ 'v8_acknowledged_undrainable_cases': 0,
53
+ 'actual_crash_image_recovery_checks': crash['recovery_checks'],
54
+ 'sequence_transactions': seq['transactions'], 'standalone_artifacts_smoke_passed': True,
55
+ 'native_ntfs_results': False, 'benchmark_runs': len(bench['trials']),
56
+ 'contract': 'serialized POSIX engine; conditional logical-arena checkpoint feasibility',
57
+ 'performance': 'weighted paths improve targeted bulk admission; ordinary results mixed; V5 regressions remain'}
58
+ (ROOT / 'evidence/release_provenance.json').write_text(json.dumps(provenance, indent=2) + '\n')
59
+ suffixes = {'.py', '.md', '.txt', '.pdf', '.json', '.toml', '.in', '.pyz', '.whl', '.gz'}
60
+ excluded = {'SHA256SUMS.txt', 'evidence_engine_initial.txt', 'evidence/admission_draft.txt', 'evidence/build.txt', 'evidence/release_smoke.txt'}
61
+ files = sorted(p for p in ROOT.rglob('*') if p.is_file() and not p.is_symlink()
62
+ and '__pycache__' not in p.parts and not any(x.endswith('.egg-info') for x in p.parts)
63
+ and (p.suffix in suffixes or p.name == 'LICENSE')
64
+ and p.relative_to(ROOT).as_posix() not in excluded)
65
+ hashes = ROOT / 'SHA256SUMS.txt'
66
+ hashes.write_text(''.join(f'{sha(p)} {p.relative_to(ROOT).as_posix()}\n' for p in files))
67
+ files.append(hashes)
68
+ target = ROOT.parent.parent / 'output/NYARION_FS_Research_Package.zip'
69
+ target.parent.mkdir(exist_ok=True)
70
+ with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
71
+ for path in files:
72
+ info = zipfile.ZipInfo('NYARION_FS/' + path.relative_to(ROOT).as_posix(), (2026, 11, 1, 18, 0, 0))
73
+ info.compress_type = zipfile.ZIP_DEFLATED
74
+ info.external_attr = (0o100755 if path.suffix == '.pyz' else 0o100644) << 16
75
+ archive.writestr(info, path.read_bytes())
76
+ with zipfile.ZipFile(target) as archive:
77
+ assert archive.testzip() is None
78
+ assert hashlib.sha256(archive.read('NYARION_FS/pagefs.py')).hexdigest() == engine_hash
79
+ print(json.dumps({'files': len(files), 'bytes': target.stat().st_size, 'validation': 'passed'}, indent=2))
80
+
81
+
82
+ if __name__ == '__main__':
83
+ main()
pagefs.py ADDED
@@ -0,0 +1,814 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """NYARION VIII weighted-reservation immutable page-tree research engine.
3
+
4
+ Regular POSIX files only. All logical values are held in RAM. Capsule commits
5
+ use one fsync; checkpoints copy changed trie paths and publish through two
6
+ protected seal banks. The fixed object pool is reclaimed by root reachability.
7
+ This is not a mounted filesystem or a hardware durability qualification.
8
+ """
9
+ from __future__ import annotations
10
+ import argparse,base64,errno,hashlib,heapq,json,os,re,stat,struct,sys,uuid
11
+ from pathlib import Path
12
+ from collections import ChainMap
13
+ try:
14
+ import fcntl
15
+ except ImportError:
16
+ fcntl=None
17
+
18
+ FORMAT=5
19
+ MAGIC=b'NYPAGES5'
20
+ SLOTS=64
21
+ SPAN=65536
22
+ SECTOR=512
23
+ BLOCK_SIZE=4096
24
+ SEAL_OFFSETS=(0,4096,8192,12288)
25
+ RING_START=16384
26
+ POOL_START=RING_START+2*SLOTS*SPAN
27
+ APPEND_START=POOL_START
28
+ DEFAULT_POOL_BLOCKS=16384
29
+ MAX_POOL_BLOCKS=1<<20
30
+ MAX_U64=(1<<64)-1
31
+ K_SEAL,K_CATALOG,K_TRIE,K_BLOB,K_DATA,K_CAPSULE=1,2,3,4,5,6
32
+ PREFIX=struct.Struct('>8sHHIQ16s32s')
33
+ HEADER=struct.Struct('>8sHHIQ16s32s32s')
34
+ PAGE_PAYLOAD=BLOCK_SIZE-HEADER.size
35
+ MAX_CAPSULE=SPAN-HEADER.size
36
+ INLINE_LIMIT=256
37
+ ZERO='0'*64
38
+ HEX32=re.compile(r'^[0-9a-f]{32}$')
39
+ HEX64=re.compile(r'^[0-9a-f]{64}$')
40
+ TOKEN=re.compile(r'^[A-Za-z0-9_.:-]{1,64}$')
41
+ HEX='0123456789abcdef'
42
+ # Descriptor fields use their largest allowed encoded widths. A symbolic leaf
43
+ # built with this descriptor is never smaller than its physical counterpart.
44
+ BOUND_DESC=(MAX_POOL_BLOCKS-1,MAX_POOL_BLOCKS-1,MAX_U64,K_BLOB,PAGE_PAYLOAD,'f'*64)
45
+
46
+ class StoreError(Exception):pass
47
+ class InvalidImage(StoreError):pass
48
+ class RecoveryBlocked(StoreError):pass
49
+ class SplitIdentity(RecoveryBlocked):pass
50
+ class UnsupportedFormat(RecoveryBlocked):pass
51
+ class WriterFenced(StoreError):pass
52
+ class TransactionConflict(StoreError):pass
53
+ class AdmissionRejected(OSError):
54
+ """No offered capsule was written: its exact checkpoint cannot fit."""
55
+ pass
56
+
57
+ def canonical(obj):return json.dumps(obj,sort_keys=True,separators=(',',':'),ensure_ascii=True,allow_nan=False).encode('ascii')
58
+ # All branch/manifest/catalogue records fit even at the declared format bounds.
59
+ assert len(canonical({'family':'tokens','type':'branch','depth':63,'children':{n:BOUND_DESC for n in HEX}}))<=PAGE_PAYLOAD
60
+ assert len(canonical({'length':MAX_CAPSULE,'digest':'f'*64,'chunks':[BOUND_DESC]*((MAX_CAPSULE+PAGE_PAYLOAD-1)//PAGE_PAYLOAD)}))<=PAGE_PAYLOAD
61
+ assert len(canonical({'format':FORMAT,'volume':'f'*32,'epoch':MAX_U64,'history':'f'*64,'files_root':BOUND_DESC,'tokens_root':BOUND_DESC}))<=PAGE_PAYLOAD
62
+ # Empty skeleton includes both braces of the entries dictionary; entries add
63
+ # their own key/value/colon weights and n-1 commas. Sorting does not change size.
64
+ BUDGET_EMPTY_SIZES={(family,depth):len(canonical({'family':family,'type':'leaf','depth':depth,'entries':{}}))
65
+ for family in ('files','tokens') for depth in range(65)}
66
+ BOUND_BLOB_VALUE_SIZE=len(canonical({'blob':BOUND_DESC}))
67
+ def digest(raw):return hashlib.sha256(raw).hexdigest()
68
+ def uint(x,maximum=MAX_U64):return type(x) is int and 0<=x<=maximum
69
+ def hash_key(key):return hashlib.sha256(key.encode('utf8')).hexdigest()
70
+ def path_key(path):
71
+ 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('/')):
72
+ raise ValueError('canonical absolute flat path key required')
73
+ return path
74
+ def token_key(token):
75
+ if not isinstance(token,str) or not TOKEN.fullmatch(token):raise ValueError('safe ASCII token required')
76
+ return token
77
+ def b64(raw):return base64.b64encode(raw).decode('ascii')
78
+ def unb64(value):
79
+ if not isinstance(value,str):raise InvalidImage('base64 type')
80
+ try:raw=base64.b64decode(value,validate=True)
81
+ except (ValueError,UnicodeError) as exc:raise InvalidImage('base64 encoding') from exc
82
+ if b64(raw)!=value:raise InvalidImage('noncanonical base64')
83
+ return raw
84
+ def unpack_json(raw):
85
+ def pairs(items):
86
+ d={}
87
+ for k,v in items:
88
+ if k in d:raise InvalidImage('duplicate JSON field')
89
+ d[k]=v
90
+ return d
91
+ try:obj=json.loads(raw.decode('ascii'),object_pairs_hook=pairs,parse_constant=lambda _:(_ for _ in ()).throw(ValueError()))
92
+ except (ValueError,UnicodeError,RecursionError) as exc:raise InvalidImage('invalid JSON') from exc
93
+ if not isinstance(obj,dict) or canonical(obj)!=raw:raise InvalidImage('noncanonical JSON object')
94
+ return obj
95
+ def pack(kind,payload,epoch,volume,fixed=None):
96
+ if not uint(epoch) or not isinstance(volume,str) or not HEX32.fullmatch(volume):raise ValueError('record identity')
97
+ prefix=PREFIX.pack(MAGIC,FORMAT,kind,len(payload),epoch,bytes.fromhex(volume),hashlib.sha256(payload).digest())
98
+ raw=prefix+hashlib.sha256(prefix).digest()+payload
99
+ if fixed is not None:
100
+ if len(raw)>fixed:raise ValueError('record exceeds reserved unit')
101
+ raw+=bytes(fixed-len(raw))
102
+ return raw
103
+ def read_header(raw,kind,maximum):
104
+ if len(raw)<HEADER.size:raise InvalidImage('short header')
105
+ magic,version,k,n,e,vol,h,check=HEADER.unpack_from(raw)
106
+ if magic!=MAGIC or k!=kind or hashlib.sha256(raw[:PREFIX.size]).digest()!=check:raise InvalidImage('header identity/checksum')
107
+ if version!=FORMAT:raise UnsupportedFormat('checksum-valid unsupported format')
108
+ if n>maximum:raise RecoveryBlocked('checksum-valid length exceeds bound')
109
+ return {'epoch':e,'volume':vol.hex(),'length':n,'digest':h.hex()}
110
+ def read_payload(raw,head):
111
+ body=raw[HEADER.size:HEADER.size+head['length']]
112
+ if len(body)!=head['length'] or digest(body)!=head['digest']:raise InvalidImage('payload length/digest')
113
+ return body
114
+ def capsule_offset(epoch,replica):return RING_START+(replica*SLOTS+epoch%SLOTS)*SPAN
115
+ def block_offset(index):return POOL_START+index*BLOCK_SIZE
116
+
117
+ class PageStore:
118
+ """Single serialized publisher; fixed-capacity mirrored object arena."""
119
+ def __init__(self,path,*,writable=True,minimum_epoch=None):
120
+ if fcntl is None:raise StoreError('POSIX flock required')
121
+ self.path=os.fspath(path);self.fd=None;self.writable=writable;self.fenced=False;self.reset_stats()
122
+ fd=os.open(self.path,(os.O_RDWR if writable else os.O_RDONLY)|getattr(os,'O_NOFOLLOW',0))
123
+ try:
124
+ if not stat.S_ISREG(os.fstat(fd).st_mode):raise InvalidImage('regular image file required')
125
+ fcntl.flock(fd,(fcntl.LOCK_EX if writable else fcntl.LOCK_SH)|fcntl.LOCK_NB);self.fd=fd
126
+ self._recover()
127
+ if minimum_epoch is not None and (not uint(minimum_epoch) or self.epoch<minimum_epoch):raise RecoveryBlocked('below caller minimum epoch')
128
+ if writable:
129
+ self._reprotect()
130
+ if self.active:
131
+ try:self._checkpoint_plan=self._prepare_checkpoint_plan()
132
+ except AdmissionRejected as exc:
133
+ raise AdmissionRejected(errno.ENOSPC,'recovered capsule tail has no feasible checkpoint; read-only recovery remains available') from exc
134
+ except BaseException:os.close(fd);self.fd=None;raise
135
+ @classmethod
136
+ def create(cls,path,*,initial_files=None,pool_blocks=DEFAULT_POOL_BLOCKS):
137
+ if fcntl is None:raise StoreError('POSIX flock required')
138
+ if not uint(pool_blocks,MAX_POOL_BLOCKS) or pool_blocks<16:raise ValueError('pool_blocks must be 16..1048576')
139
+ if initial_files is not None and not isinstance(initial_files,dict):raise TypeError('initial_files dictionary required')
140
+ files={}
141
+ for key,value in (initial_files or {}).items():
142
+ path_key(key)
143
+ if not isinstance(value,bytes):raise TypeError('bytes values required')
144
+ if len(value)>MAX_CAPSULE:raise ValueError('initial value exceeds supported size')
145
+ files[key]=value
146
+ fd=os.open(os.fspath(path),os.O_RDWR|os.O_CREAT|os.O_EXCL|getattr(os,'O_NOFOLLOW',0),0o600)
147
+ self=cls.__new__(cls);self.path=os.fspath(path);self.fd=fd;self.writable=True;self.fenced=False;self.reset_stats()
148
+ try:
149
+ if not stat.S_ISREG(os.fstat(fd).st_mode):raise InvalidImage('regular image file required')
150
+ fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB);os.ftruncate(fd,POOL_START+pool_blocks*BLOCK_SIZE)
151
+ self.volume=uuid.uuid4().hex;self.pool_blocks=pool_blocks;self.generation=-1;self.epoch=0;self.checkpoint_epoch=0;self.history=ZERO
152
+ self.files_root=None;self.tokens_root=None;self.catalog_desc=None;self._files=files;self._tokens={};self.active={}
153
+ 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()
154
+ self._free=list(range(pool_blocks));heapq.heapify(self._free)
155
+ self._refs={};self._block_owner={};self._pending=set();self._checkpoint_plan=None
156
+ self.checkpoint(initial=True)
157
+ parent=os.open(str(Path(path).resolve().parent),os.O_RDONLY|getattr(os,'O_DIRECTORY',0))
158
+ try:os.fsync(parent)
159
+ finally:os.close(parent)
160
+ return self
161
+ except BaseException:self.close();raise
162
+ def __enter__(self):return self
163
+ def __exit__(self,*exc):self.close()
164
+ def close(self):
165
+ if self.fd is not None:os.close(self.fd);self.fd=None
166
+ def _live(self):
167
+ if self.fd is None:raise StoreError('closed')
168
+ if self.fenced:raise WriterFenced('uncertain state: close and recover')
169
+ def _writable(self):
170
+ self._live()
171
+ if not self.writable:raise WriterFenced('read-only image')
172
+ def reset_stats(self):
173
+ self.stats={'bytes_written':0,'write_calls':0,'fsync_calls':0,'capsule_batches':0,'checkpoints':0,
174
+ 'page_allocations':0,'reclaimed_blocks':0,'arena_live_blocks':0,'full_graph_scans':0,
175
+ 'incremental_validations':0,'graph_nodes_validated':0,'refcount_steps':0,'pool_rebuilds':0,
176
+ 'admission_plans':0,'admission_planned_blocks':0,'admission_rejections':0,'admission_pressure_checkpoints':0,'executed_plans':0,
177
+ 'reservation_offers':0,'reservation_fast_accepts':0,'reservation_exact_fallbacks':0,'reservation_cells_rebuilt':0,'reservation_route_visits':0,
178
+ 'reservation_node_updates':0,'reservation_leaf_splits':0,'reservation_entry_encodings':0}
179
+ def _pwrite(self,raw,offset):
180
+ view=memoryview(raw)
181
+ while view:
182
+ n=os.pwrite(self.fd,view,offset)
183
+ if n<=0:raise OSError('zero-length write')
184
+ self.stats['bytes_written']+=n;self.stats['write_calls']+=1;view=view[n:];offset+=n
185
+ def _sync(self):self.stats['fsync_calls']+=1;os.fsync(self.fd)
186
+ def _valid_desc(self,desc,kind=None):
187
+ if not isinstance(desc,list) or len(desc)!=6:return False
188
+ a,b,g,k,n,h=desc
189
+ return (uint(a,self.pool_blocks-1) and uint(b,self.pool_blocks-1) and a!=b and uint(g) and
190
+ type(k) is int and k in (K_CATALOG,K_TRIE,K_BLOB,K_DATA) and (kind is None or k==kind)
191
+ and uint(n,PAGE_PAYLOAD) and isinstance(h,str) and bool(HEX64.fullmatch(h)))
192
+ def _alloc_object(self,kind,body):
193
+ if len(body)>PAGE_PAYLOAD:raise StoreError('object exceeds page payload')
194
+ if len(self._free)<2:raise OSError(errno.ENOSPC,'fixed object arena lacks COW checkpoint headroom')
195
+ a,b=heapq.heappop(self._free),heapq.heappop(self._free)
196
+ desc=[a,b,self._writing_generation,kind,len(body),digest(body)]
197
+ key=tuple(desc);self._pending.add(key)
198
+ for index in (a,b):
199
+ if index in self._block_owner:raise InvalidImage('allocator selected an owned block')
200
+ self._block_owner[index]=key
201
+ raw=pack(kind,body,self._writing_generation,self.volume,fixed=BLOCK_SIZE)
202
+ for index in (a,b):self._pwrite(raw,block_offset(index))
203
+ self._cache[tuple(desc)]=body;self.stats['page_allocations']+=2
204
+ return desc
205
+ def _read_object(self,desc,kind=None):
206
+ if not self._valid_desc(desc,kind):raise InvalidImage('object descriptor bounds/identity')
207
+ key=tuple(desc)
208
+ if key in self._cache:return self._cache[key]
209
+ good=None;bad=[]
210
+ for index in desc[:2]:
211
+ try:
212
+ raw=os.pread(self.fd,BLOCK_SIZE,block_offset(index));head=read_header(raw,desc[3],PAGE_PAYLOAD);body=read_payload(raw,head)
213
+ 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')
214
+ good=body
215
+ except (InvalidImage,OSError):bad.append(index)
216
+ if good is None:raise RecoveryBlocked('required object has no valid mirror; fallback refused')
217
+ expected=pack(desc[3],good,desc[2],self.volume,fixed=BLOCK_SIZE)
218
+ for index in bad:self._repair_records.append((block_offset(index),expected))
219
+ self._cache[key]=good;return good
220
+ def _put_json(self,kind,obj):return self._alloc_object(kind,canonical(obj))
221
+ def _file_value(self,data):
222
+ if len(data)>MAX_CAPSULE:raise ValueError('value exceeds supported size')
223
+ if len(data)<=INLINE_LIMIT:return {'inline':b64(data)}
224
+ chunks=[self._alloc_object(K_DATA,data[i:i+PAGE_PAYLOAD]) for i in range(0,len(data),PAGE_PAYLOAD)]
225
+ return {'blob':self._put_json(K_BLOB,{'length':len(data),'digest':digest(data),'chunks':chunks})}
226
+ def _build_tree(self,family,entries,depth=0):
227
+ if not entries:return None
228
+ leaf={'family':family,'type':'leaf','depth':depth,'entries':entries};raw=canonical(leaf)
229
+ if len(raw)<=PAGE_PAYLOAD:return self._alloc_object(K_TRIE,raw)
230
+ if depth>=64:raise StoreError('hash collision leaf exceeds page capacity')
231
+ groups={}
232
+ for key,value in entries.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
233
+ children={nib:self._build_tree(family,group,depth+1) for nib,group in groups.items()}
234
+ return self._put_json(K_TRIE,{'family':family,'type':'branch','depth':depth,'children':children})
235
+ def _update_tree(self,desc,family,changes,depth=0):
236
+ if not changes:return desc
237
+ if desc is None:return self._build_tree(family,{k:v for k,v in changes.items() if v is not None},depth)
238
+ node=unpack_json(self._read_object(desc,K_TRIE))
239
+ if node.get('family')!=family or node.get('depth')!=depth:raise InvalidImage('trie update identity/depth')
240
+ if node.get('type')=='leaf':
241
+ entries=dict(node['entries'])
242
+ for key,value in changes.items():
243
+ if value is None:entries.pop(key,None)
244
+ else:entries[key]=value
245
+ if entries==node['entries']:return desc
246
+ return self._build_tree(family,entries,depth)
247
+ if node.get('type')!='branch' or depth>=64:raise InvalidImage('trie branch update')
248
+ children=dict(node['children']);groups={}
249
+ for key,value in changes.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
250
+ for nib,group in groups.items():
251
+ child=self._update_tree(children.get(nib),family,group,depth+1)
252
+ if child is None:children.pop(nib,None)
253
+ else:children[nib]=child
254
+ if children==node['children']:return desc
255
+ if not children:return None
256
+ return self._put_json(K_TRIE,{'family':family,'type':'branch','depth':depth,'children':children})
257
+ def _scan_graph(self,catalog_desc,*,decode=False,generation=None,incremental=False):
258
+ """Full recovery validation, or validation of newly reserved objects only.
259
+
260
+ An unchanged pointer is accepted only when its complete identity is live
261
+ and its validated family/routing/owner context matches the new edge.
262
+ """
263
+ self.stats['incremental_validations' if incremental else 'full_graph_scans']+=1
264
+ seen=set();identities=set();files={};tokens={}
265
+ selected_generation=self.generation if generation is None else generation
266
+ if not self._valid_desc(catalog_desc,K_CATALOG) or catalog_desc[2]!=selected_generation:raise InvalidImage('catalogue birth differs from selected generation')
267
+ def known(desc,kind,context):
268
+ if not self._valid_desc(desc,kind) or desc[2]>selected_generation:raise InvalidImage('invalid reachable descriptor/birth')
269
+ if not incremental:return False
270
+ key=tuple(desc)
271
+ if any(self._block_owner.get(index)!=key for index in desc[:2]):raise InvalidImage('descriptor does not own its reserved/live blocks')
272
+ if self._refs.get(key,0):
273
+ info=self._graph_cache.get(key)
274
+ if info is None or info['context']!=context or info['max_epoch']>cat['epoch']:raise InvalidImage('unchanged object context/epoch mismatch')
275
+ return True
276
+ if key not in self._pending:raise InvalidImage('pointer is neither live nor reserved')
277
+ return False
278
+ def claim(desc,kind):
279
+ if not self._valid_desc(desc,kind) or desc[2]>selected_generation:raise InvalidImage('invalid reachable descriptor/birth')
280
+ if seen.intersection(desc[:2]):raise InvalidImage('object block alias/cycle')
281
+ seen.update(desc[:2]);identities.add(tuple(desc));self.stats['graph_nodes_validated']+=1
282
+ return self._read_object(desc,kind)
283
+ if incremental:
284
+ key=tuple(catalog_desc)
285
+ 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')
286
+ cat=unpack_json(claim(catalog_desc,K_CATALOG))
287
+ if (set(cat)!={'format','volume','epoch','history','files_root','tokens_root'} or type(cat['format']) is not int or cat['format']!=FORMAT or
288
+ 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')
289
+ if incremental and (cat['epoch']!=self.epoch or cat['history']!=self.history):raise InvalidImage('candidate logical head mismatch')
290
+ def remember(desc,links,context,max_epoch=0):
291
+ self._graph_cache[tuple(desc)]={'links':links,'context':context,'max_epoch':max_epoch}
292
+ def file_value(path,obj):
293
+ if not isinstance(obj,dict):raise InvalidImage('file value schema')
294
+ if set(obj)=={'inline'}:
295
+ data=unb64(obj['inline'])
296
+ if len(data)>INLINE_LIMIT:raise InvalidImage('oversized inline value')
297
+ return data,[]
298
+ if set(obj)!={'blob'}:raise InvalidImage('file encoding')
299
+ desc=obj['blob'];links=[(desc,K_BLOB)]
300
+ if known(desc,K_BLOB,('blob',path)):return None,links
301
+ manifest=unpack_json(claim(desc,K_BLOB))
302
+ if (set(manifest)!={'length','digest','chunks'} or not uint(manifest['length'],MAX_CAPSULE) or manifest['length']<=INLINE_LIMIT or
303
+ not isinstance(manifest['digest'],str) or not HEX64.fullmatch(manifest['digest']) or
304
+ not isinstance(manifest['chunks'],list) or len(manifest['chunks'])!=(manifest['length']+PAGE_PAYLOAD-1)//PAGE_PAYLOAD):raise InvalidImage('blob manifest')
305
+ parts=[]
306
+ for i,chunk in enumerate(manifest['chunks']):
307
+ context=('data',path,i)
308
+ if known(chunk,K_DATA,context):part=self._read_object(chunk,K_DATA)
309
+ else:
310
+ part=claim(chunk,K_DATA);remember(chunk,[],context)
311
+ if len(part)!=min(PAGE_PAYLOAD,manifest['length']-i*PAGE_PAYLOAD):raise InvalidImage('blob chunk length')
312
+ parts.append(part)
313
+ data=b''.join(parts)
314
+ if len(data)!=manifest['length'] or digest(data)!=manifest['digest']:raise InvalidImage('blob data mismatch')
315
+ remember(desc,[(chunk,K_DATA) for chunk in manifest['chunks']],('blob',path))
316
+ return data,links
317
+ def walk(desc,family,depth=0,prefix=''):
318
+ if desc is None:return
319
+ context=('trie',family,depth,prefix)
320
+ if known(desc,K_TRIE,context):return
321
+ node=unpack_json(claim(desc,K_TRIE))
322
+ 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')
323
+ links=[];max_epoch=0
324
+ if node.get('type')=='leaf':
325
+ if set(node)!={'family','type','depth','entries'} or not isinstance(node['entries'],dict) or not node['entries']:raise InvalidImage('leaf schema')
326
+ for key,value in node['entries'].items():
327
+ try:path_key(key) if family=='files' else token_key(key)
328
+ except ValueError as exc:raise InvalidImage('trie key') from exc
329
+ if not hash_key(key).startswith(prefix):raise InvalidImage('trie key routing')
330
+ if family=='files':
331
+ data,dependencies=file_value(key,value);links.extend(dependencies)
332
+ if decode:files[key]=data
333
+ else:
334
+ 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')
335
+ max_epoch=max(max_epoch,value[0])
336
+ if decode:tokens[key]=value
337
+ remember(desc,links,context,max_epoch);return
338
+ if (node.get('type')!='branch' or set(node)!={'family','type','depth','children'} or depth>=64 or
339
+ 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')
340
+ for nib,child in node['children'].items():
341
+ walk(child,family,depth+1,prefix+nib);links.append((child,K_TRIE))
342
+ max_epoch=max(max_epoch,self._graph_cache[tuple(child)]['max_epoch'])
343
+ remember(desc,links,context,max_epoch)
344
+ walk(cat['files_root'],'files');walk(cat['tokens_root'],'tokens')
345
+ remember(catalog_desc,[(desc,K_TRIE) for desc in (cat['files_root'],cat['tokens_root']) if desc is not None],('catalog',))
346
+ return cat,seen,files,tokens
347
+ def _acquire(self,desc):
348
+ """Activate outgoing edges only on the object's zero-to-one transition."""
349
+ key=tuple(desc);previous=self._refs.get(key,0);self._refs[key]=previous+1;self.stats['refcount_steps']+=1
350
+ if previous:return
351
+ info=self._graph_cache.get(key)
352
+ if info is None:raise InvalidImage('acquiring unvalidated object')
353
+ self._pending.discard(key);self._live_blocks.update(desc[:2])
354
+ for child,kind in info['links']:self._acquire(child)
355
+ def _release(self,desc):
356
+ """Retire outgoing edges and recycle blocks only at the last reference."""
357
+ key=tuple(desc);count=self._refs.get(key,0);self.stats['refcount_steps']+=1
358
+ if count<=0:raise InvalidImage('reference count underflow')
359
+ if count>1:self._refs[key]=count-1;return
360
+ del self._refs[key];info=self._graph_cache.pop(key)
361
+ for child,kind in info['links']:self._release(child)
362
+ self._cache.pop(key,None)
363
+ for index in desc[:2]:
364
+ if self._block_owner.pop(index,None)!=key:raise InvalidImage('releasing object ownership mismatch')
365
+ self._live_blocks.remove(index);heapq.heappush(self._free,index)
366
+ self.stats['reclaimed_blocks']+=2
367
+ def _discard_unreachable_reservations(self):
368
+ # Normally empty: retain this guard for allocations omitted by a builder.
369
+ for key in self._pending:
370
+ if self._refs.get(key,0):raise InvalidImage('live allocation remained reserved')
371
+ self._cache.pop(key,None);self._graph_cache.pop(key,None)
372
+ for index in key[:2]:
373
+ if self._block_owner.pop(index,None)!=key:raise InvalidImage('reservation ownership mismatch')
374
+ heapq.heappush(self._free,index)
375
+ self.stats['reclaimed_blocks']+=2
376
+ self._pending.clear()
377
+ def _validate_capsule(self,obj,head):
378
+ if (set(obj)!={'format','volume','epoch','parent','token','intent','changes'} or type(obj['format']) is not int or obj['format']!=FORMAT or
379
+ obj['volume']!=self.volume or obj['epoch']!=head['epoch'] or not uint(obj['epoch']) or not obj['epoch'] or
380
+ 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')
381
+ try:token_key(obj['token'])
382
+ except ValueError as exc:raise InvalidImage('capsule token') from exc
383
+ previous=None;items=[]
384
+ for change in obj['changes']:
385
+ if not isinstance(change,list) or len(change)!=2:raise InvalidImage('change schema')
386
+ path,value=change
387
+ try:path_key(path)
388
+ except ValueError as exc:raise InvalidImage('capsule path') from exc
389
+ if previous is not None and path<=previous:raise InvalidImage('unsorted/duplicate changes')
390
+ previous=path;raw=None if value is None else unb64(value)
391
+ items.append([path,None if raw is None else [len(raw),digest(raw)]])
392
+ if digest(canonical(items))!=obj['intent']:raise InvalidImage('intent mismatch')
393
+ return obj
394
+ def _apply(self,obj):
395
+ if obj['token'] in self._tokens:raise RecoveryBlocked('duplicate committed token')
396
+ for path,value in obj['changes']:
397
+ data=None if value is None else unb64(value)
398
+ if data is None:self._files.pop(path,None)
399
+ else:self._files[path]=data
400
+ self._dirty_files[path]=data
401
+ entry=[obj['epoch'],obj['intent']];self._tokens[obj['token']]=entry;self._dirty_tokens[obj['token']]=entry
402
+ def _recover(self):
403
+ self._cache={};self._graph_cache={};self._repair_records=[];seals=[];places=[]
404
+ for slot,off in enumerate(SEAL_OFFSETS):
405
+ try:
406
+ raw=os.pread(self.fd,SECTOR,off);head=read_header(raw,K_SEAL,SECTOR-HEADER.size);obj=unpack_json(read_payload(raw,head))
407
+ if (set(obj)!={'generation','volume','pool_blocks','root'} or not uint(obj['generation']) or obj['generation']!=head['epoch'] or
408
+ obj['volume']!=head['volume'] or not uint(obj['pool_blocks'],MAX_POOL_BLOCKS) or obj['pool_blocks']<16):raise InvalidImage('seal schema')
409
+ seals.append(obj);places.append((slot,obj))
410
+ except (InvalidImage,OSError):continue
411
+ if not seals:raise RecoveryBlocked('no valid catalogue seal')
412
+ if len({s['volume'] for s in seals})!=1:raise SplitIdentity('volume disagreement')
413
+ g=max(s['generation'] for s in seals);newest=[s for s in seals if s['generation']==g]
414
+ if len({canonical(s) for s in newest})!=1:raise SplitIdentity('same-generation disagreement')
415
+ self.seal=newest[0];self.generation=g;self.volume=self.seal['volume'];self.pool_blocks=self.seal['pool_blocks']
416
+ if os.fstat(self.fd).st_size!=POOL_START+self.pool_blocks*BLOCK_SIZE:raise InvalidImage('fixed image capacity mismatch')
417
+ self._selected_valid_slots={i for i,s in places if canonical(s)==canonical(self.seal)}
418
+ self.catalog_desc=self.seal['root']
419
+ cat,live,files,tokens=self._scan_graph(self.catalog_desc,decode=True)
420
+ self.files_root=cat['files_root'];self.tokens_root=cat['tokens_root'];self.epoch=self.checkpoint_epoch=cat['epoch'];self.history=cat['history']
421
+ self._files=files;self._tokens=tokens;self._dirty_files={};self._dirty_tokens={};self._live_blocks=live
422
+ self._free=[i for i in range(self.pool_blocks) if i not in live];heapq.heapify(self._free);self.stats['pool_rebuilds']+=1
423
+ self._refs={key:1 for key in self._graph_cache}
424
+ self._block_owner={index:key for key in self._refs for index in key[:2]};self._pending=set()
425
+ headers={};complete={};valid={}
426
+ for slot in range(SLOTS):
427
+ for replica in range(2):
428
+ off=RING_START+(replica*SLOTS+slot)*SPAN
429
+ try:rawhead=os.pread(self.fd,HEADER.size,off);head=read_header(rawhead,K_CAPSULE,MAX_CAPSULE)
430
+ except (InvalidImage,OSError):continue
431
+ if head['volume']!=self.volume:raise SplitIdentity('capsule volume disagreement')
432
+ e=head['epoch']
433
+ if e<=self.checkpoint_epoch:continue
434
+ if e%SLOTS!=slot or e-self.checkpoint_epoch>SLOTS:raise RecoveryBlocked('capsule outside bounded window')
435
+ identity=(head['length'],head['digest']);headers.setdefault(e,set()).add(identity)
436
+ if len(headers[e])!=1:raise SplitIdentity('same-epoch capsule disagreement')
437
+ try:
438
+ body=read_payload(rawhead+os.pread(self.fd,head['length'],off+HEADER.size),head)
439
+ obj=self._validate_capsule(unpack_json(body),head)
440
+ except (InvalidImage,OSError):continue
441
+ complete[e]={'body':body,'obj':obj,'digest':digest(body)};valid.setdefault(e,set()).add(replica)
442
+ if any(e not in complete for e in headers):raise RecoveryBlocked('newer valid header lacks complete capsule')
443
+ for e,item in sorted(complete.items()):
444
+ if e!=self.epoch+1 or item['obj']['parent']!=self.history:raise RecoveryBlocked('capsule history gap/parent mismatch')
445
+ self._apply(item['obj']);self.epoch=e;self.history=item['digest']
446
+ raw=pack(K_CAPSULE,item['body'],e,self.volume)
447
+ for replica in range(2):
448
+ if replica not in valid[e]:self._repair_records.append((capsule_offset(e,replica),raw))
449
+ self.active=complete;self._checkpoint_plan=None;self.stats['arena_live_blocks']=len(live)
450
+ self._reset_reservations(ready=False)
451
+ def _reprotect(self):
452
+ try:
453
+ for off,raw in self._repair_records:self._pwrite(raw,off)
454
+ if self._repair_records:self._sync()
455
+ targets=[i for i in range((self.generation%2)*2,(self.generation%2)*2+2) if i not in self._selected_valid_slots]
456
+ if targets:
457
+ raw=pack(K_SEAL,canonical(self.seal),self.generation,self.volume,fixed=SECTOR)
458
+ for i in targets:self._pwrite(raw,SEAL_OFFSETS[i])
459
+ self._sync();self._selected_valid_slots.update(targets)
460
+ except BaseException:self.fenced=True;raise
461
+ self._repair_records=[]
462
+ @staticmethod
463
+ def _heap_order(heap):
464
+ """Yield min-heap values in pop order without copying the arena heap."""
465
+ if not heap:return
466
+ frontier=[(heap[0],0)]
467
+ while frontier:
468
+ value,index=heapq.heappop(frontier);yield value
469
+ for child in (2*index+1,2*index+2):
470
+ if child<len(heap):heapq.heappush(frontier,(heap[child],child))
471
+ def _reset_reservations(self,ready=True):
472
+ self._reservation_ready=ready;self._reservation_cells={};self._reservation_ancestors=set()
473
+ self._reservation_blob_pages={};self._reservation_logical=1
474
+ self._reservation_decoded={};self._reservation_routes={};self._reservation_bases={}
475
+ def _reservation_route(self,family,key):
476
+ cached=self._reservation_routes.get((family,key))
477
+ if cached is not None:return cached
478
+ desc=self.files_root if family=='files' else self.tokens_root
479
+ depth=0;prefix='';ancestors=[];hashed=hash_key(key)
480
+ while desc is not None:
481
+ identity=tuple(desc);node=self._reservation_decoded.get(identity)
482
+ if node is None:
483
+ node=unpack_json(self._read_object(desc,K_TRIE));self._reservation_decoded[identity]=node
484
+ self.stats['reservation_route_visits']+=1
485
+ if node['family']!=family or node['depth']!=depth:raise InvalidImage('reservation routing identity')
486
+ if node['type']=='leaf':
487
+ answer=((family,prefix),depth,node['entries'],tuple(ancestors));break
488
+ if node['type']!='branch' or depth>=64:raise InvalidImage('reservation routing branch')
489
+ ancestors.append(identity);nib=hashed[depth];prefix+=nib;depth+=1
490
+ desc=node['children'].get(nib)
491
+ else:answer=((family,prefix),depth,{},tuple(ancestors))
492
+ self._reservation_routes[(family,key)]=answer
493
+ return answer
494
+ @staticmethod
495
+ def _reservation_count(family,entries,depth):
496
+ if not entries:return 0
497
+ if len(canonical({'family':family,'type':'leaf','depth':depth,'entries':entries}))<=PAGE_PAYLOAD:return 1
498
+ if depth>=64:return MAX_POOL_BLOCKS # Force the exact compiler to decide.
499
+ groups={}
500
+ for key,value in entries.items():groups.setdefault(hash_key(key)[depth],{})[key]=value
501
+ return 1+sum(PageStore._reservation_count(family,group,depth+1) for group in groups.values())
502
+ @staticmethod
503
+ def _budget_nodes(node):return 0 if node is None else node['nodes']
504
+ @staticmethod
505
+ def _budget_leaf_bytes(family,depth,entries,entry_sum):
506
+ return BUDGET_EMPTY_SIZES[(family,depth)]+entry_sum+max(len(entries)-1,0)
507
+ def _budget_build(self,family,entries,depth,entry_sum=None):
508
+ """Build a symbolic subtree once from key-to-encoded-weight entries.
509
+
510
+ Nodes are immutable by convention: all later updates path-copy. A
511
+ retained branch may over-refine a canonical rebuild after deletion.
512
+ """
513
+ if not entries:return None
514
+ if entry_sum is None:entry_sum=sum(entries.values())
515
+ if self._budget_leaf_bytes(family,depth,entries,entry_sum)<=PAGE_PAYLOAD:
516
+ return {'type':'leaf','depth':depth,'entries':entries,'entry_sum':entry_sum,'nodes':1}
517
+ if depth>=64:
518
+ # Inconclusive at the routing limit: force exact fallback. This
519
+ # sentinel exceeds every legal free arena; it never fast-certifies.
520
+ return {'type':'overflow','depth':depth,'entries':entries,'entry_sum':entry_sum,'nodes':MAX_POOL_BLOCKS}
521
+ groups={}
522
+ for key,weight in entries.items():groups.setdefault(hash_key(key)[depth],{})[key]=weight
523
+ children={nib:self._budget_build(family,group,depth+1) for nib,group in groups.items()}
524
+ self.stats['reservation_leaf_splits']+=1
525
+ return {'type':'branch','depth':depth,'children':children,
526
+ 'nodes':1+sum(child['nodes'] for child in children.values())}
527
+ def _budget_update(self,family,node,key,weight,depth,hashed=None):
528
+ """Return a persistent update, touching one symbolic path only."""
529
+ self.stats['reservation_node_updates']+=1
530
+ if node is None:
531
+ return None if weight is None else self._budget_build(family,{key:weight},depth,weight)
532
+ if node['depth']!=depth:raise InvalidImage('budget node depth mismatch')
533
+ if node['type'] in ('leaf','overflow'):
534
+ old=node['entries'].get(key)
535
+ if old==weight:return node
536
+ entries=dict(node['entries']);entry_sum=node['entry_sum']
537
+ if old is not None:entry_sum-=old
538
+ if weight is None:entries.pop(key,None)
539
+ else:entries[key]=weight;entry_sum+=weight
540
+ return self._budget_build(family,entries,depth,entry_sum)
541
+ if node['type']!='branch' or depth>=64:raise InvalidImage('budget branch schema')
542
+ if hashed is None:hashed=hash_key(key)
543
+ nib=hashed[depth];old=node['children'].get(nib)
544
+ child=self._budget_update(family,old,key,weight,depth+1,hashed)
545
+ if child is old:return node
546
+ children=dict(node['children'])
547
+ if child is None:children.pop(nib,None)
548
+ else:children[nib]=child
549
+ if not children:return None
550
+ # No nonempty branch collapse: retaining a refinement is conservative
551
+ # and avoids traversing unaffected descendants merely to find a merge.
552
+ return {'type':'branch','depth':depth,'children':children,
553
+ 'nodes':node['nodes']-self._budget_nodes(old)+self._budget_nodes(child)}
554
+ @staticmethod
555
+ def _budget_key_size(key):
556
+ # This is the string encoder used by canonical(..., ensure_ascii=True).
557
+ return len(json.encoder.encode_basestring_ascii(key))
558
+ @staticmethod
559
+ def _budget_published_weight(family,key,value):
560
+ if family=='tokens':return len(key)+len(str(value[0]))+72
561
+ key_size=PageStore._budget_key_size(key)
562
+ if set(value)=={'inline'}:return key_size+14+len(value['inline'])
563
+ if set(value)=={'blob'}:
564
+ desc=value['blob']
565
+ # Key + colon + {"blob":[a,b,g,k,n,"64-hex"]}.
566
+ return key_size+83+sum(len(str(field)) for field in desc[:5])
567
+ raise InvalidImage('published budget value schema')
568
+ def _budget_original(self,family,anchor,original,depth):
569
+ if anchor not in self._reservation_bases:
570
+ weights={key:self._budget_published_weight(family,key,value) for key,value in original.items()}
571
+ self.stats['reservation_entry_encodings']+=len(weights)
572
+ self._reservation_bases[anchor]=self._budget_build(family,weights,depth)
573
+ return self._reservation_bases[anchor]
574
+ def _reservation_preview(self,file_changes,token_changes):
575
+ """Pure weighted-tree proposal over affected published-leaf cells.
576
+
577
+ Lookup caches and counters may grow; accepted nodes, totals and the
578
+ allocator are unchanged. Only changed leaf/ancestor maps are copied.
579
+ New inline weights are counted from length, without base64 encoding.
580
+ """
581
+ self.stats['reservation_offers']+=1
582
+ proposed={};added_ancestors=set();blob_updates={};logical=self._reservation_logical
583
+ for family,changes in (('files',file_changes),('tokens',token_changes)):
584
+ for key,value in sorted(changes.items()):
585
+ anchor,depth,original,ancestors=self._reservation_route(family,key)
586
+ added_ancestors.update(a for a in ancestors if a not in self._reservation_ancestors)
587
+ if anchor not in proposed:
588
+ previous=self._reservation_cells.get(anchor)
589
+ tree=self._budget_original(family,anchor,original,depth) if previous is None else previous['tree']
590
+ proposed[anchor]={'depth':depth,'tree':tree}
591
+ if family=='files':
592
+ pages=0
593
+ if value is None:weight=None
594
+ elif len(value)<=INLINE_LIMIT:
595
+ weight=self._budget_key_size(key)+14+4*((len(value)+2)//3)
596
+ else:
597
+ weight=self._budget_key_size(key)+1+BOUND_BLOB_VALUE_SIZE
598
+ pages=(len(value)+PAGE_PAYLOAD-1)//PAGE_PAYLOAD+1
599
+ blob_updates[key]=pages
600
+ else:
601
+ # Safe ASCII token and [epoch,64-hex intent] receipt.
602
+ weight=len(key)+len(str(value[0]))+72
603
+ cell=proposed[anchor]
604
+ cell['tree']=self._budget_update(family,cell['tree'],key,weight,depth)
605
+ logical+=len(added_ancestors)
606
+ for anchor,cell in proposed.items():
607
+ old=self._reservation_cells.get(anchor)
608
+ cell['nodes']=self._budget_nodes(cell['tree'])
609
+ logical+=cell['nodes']-(0 if old is None else old['nodes'])
610
+ self.stats['reservation_cells_rebuilt']+=1
611
+ for key,pages in blob_updates.items():logical+=pages-self._reservation_blob_pages.get(key,0)
612
+ return {'cells':proposed,'ancestors':added_ancestors,'blobs':blob_updates,'logical':logical,'physical_blocks':2*logical}
613
+ def _reservation_adopt(self,proposal):
614
+ self._reservation_cells.update(proposal['cells']);self._reservation_ancestors.update(proposal['ancestors'])
615
+ self._reservation_blob_pages.update(proposal['blobs']);self._reservation_logical=proposal['logical']
616
+ def _ensure_reservations(self):
617
+ if getattr(self,'_reservation_ready',False):return
618
+ self._reset_reservations(ready=False)
619
+ proposal=self._reservation_preview(self._dirty_files,self._dirty_tokens)
620
+ self._reservation_adopt(proposal);self._reservation_ready=True
621
+ def admission_reservation(self):
622
+ """Detached conservative budget, not an allocated or persisted free map."""
623
+ self._live();self._ensure_reservations()
624
+ exact=self._checkpoint_plan is not None and self._checkpoint_plan['binding']==self._plan_binding()
625
+ bound=2*self._reservation_logical
626
+ return {'certificate_kind':'empty' if not self.active else ('exact_plan' if exact else 'upper_bound'),
627
+ 'reserved_upper_blocks':bound,'free_blocks':len(self._free),'cells':len(self._reservation_cells),
628
+ 'dirty_ancestors':len(self._reservation_ancestors),
629
+ 'tail_certified':not self.active or (self.generation<MAX_U64 and (exact or bound<=len(self._free)))}
630
+ def _plan_binding(self,epoch=None,history=None):
631
+ return (self.volume,self.generation,self.epoch if epoch is None else epoch,
632
+ self.history if history is None else history,canonical(self.files_root),canonical(self.tokens_root))
633
+ def _prepare_checkpoint_plan(self,*,dirty_files=None,dirty_tokens=None,epoch=None,history=None):
634
+ """Compile and validate exact output without disk/live-allocator mutation.
635
+
636
+ Overlays contain only candidate objects. The sorted heap iterator visits
637
+ only the chosen free prefix; no arena/live-graph dictionary is copied.
638
+ This recompiles the bounded outstanding window for each offered txn.
639
+ """
640
+ if self.generation==MAX_U64:raise StoreError('catalogue generation exhausted')
641
+ self.stats['admission_plans']+=1
642
+ sandbox=object.__new__(type(self));sandbox.__dict__=dict(self.__dict__)
643
+ sandbox.stats=dict(self.stats);sandbox._writing_generation=self.generation+1;sandbox._checkpoint_plan=None
644
+ sandbox.epoch=self.epoch if epoch is None else epoch
645
+ sandbox.history=self.history if history is None else history
646
+ sandbox._dirty_files=self._dirty_files if dirty_files is None else dirty_files
647
+ sandbox._dirty_tokens=self._dirty_tokens if dirty_tokens is None else dirty_tokens
648
+ sandbox._cache=ChainMap({},self._cache);sandbox._graph_cache=ChainMap({},self._graph_cache)
649
+ sandbox._block_owner=ChainMap({},self._block_owner);sandbox._pending=set();sandbox._repair_records=[]
650
+ free=iter(self._heap_order(self._free));allocations=[];writes=[]
651
+ def staged_alloc(kind,body):
652
+ if len(body)>PAGE_PAYLOAD:raise StoreError('object exceeds page payload')
653
+ try:a,b=next(free),next(free)
654
+ except StopIteration as exc:raise AdmissionRejected(errno.ENOSPC,'offered state lacks exact COW checkpoint headroom') from exc
655
+ desc=[a,b,sandbox._writing_generation,kind,len(body),digest(body)];key=tuple(desc)
656
+ sandbox._pending.add(key);allocations.append(key)
657
+ for index in (a,b):
658
+ if index in sandbox._block_owner:raise InvalidImage('planner selected an owned block')
659
+ sandbox._block_owner[index]=key
660
+ raw=pack(kind,body,sandbox._writing_generation,self.volume,fixed=BLOCK_SIZE)
661
+ writes.extend((block_offset(index),raw) for index in (a,b))
662
+ sandbox._cache[key]=body
663
+ return desc
664
+ sandbox._alloc_object=staged_alloc
665
+ try:
666
+ changes={path:None if value is None else sandbox._file_value(value) for path,value in sorted(sandbox._dirty_files.items())}
667
+ files_root=sandbox._update_tree(self.files_root,'files',changes)
668
+ tokens_root=sandbox._update_tree(self.tokens_root,'tokens',dict(sorted(sandbox._dirty_tokens.items())))
669
+ cat={'format':FORMAT,'volume':self.volume,'epoch':sandbox.epoch,'history':sandbox.history,'files_root':files_root,'tokens_root':tokens_root}
670
+ root=sandbox._put_json(K_CATALOG,cat)
671
+ generation=sandbox._writing_generation
672
+ seal={'generation':generation,'volume':self.volume,'pool_blocks':self.pool_blocks,'root':root}
673
+ seal_raw=pack(K_SEAL,canonical(seal),generation,self.volume,fixed=SECTOR)
674
+ sandbox._scan_graph(root,generation=generation,incremental=True)
675
+ except AdmissionRejected:
676
+ self.stats['admission_rejections']+=1;raise
677
+ finally:
678
+ del sandbox._alloc_object # Break the sandbox/closure reference cycle.
679
+ self.stats['graph_nodes_validated']=sandbox.stats['graph_nodes_validated']
680
+ self.stats['incremental_validations']=sandbox.stats['incremental_validations']
681
+ self.stats['admission_planned_blocks']+=len(writes)
682
+ targets=tuple(range(4)) if self.generation==-1 else tuple(range((generation%2)*2,(generation%2)*2+2))
683
+ return {'binding':self._plan_binding(sandbox.epoch,sandbox.history),'generation':generation,'epoch':sandbox.epoch,
684
+ 'history':sandbox.history,'files_root':files_root,'tokens_root':tokens_root,'root':root,'seal':seal,
685
+ 'objects':tuple(allocations),'dependency_writes':tuple(writes),
686
+ 'seal_writes':tuple((SEAL_OFFSETS[i],seal_raw) for i in targets),'targets':targets,
687
+ 'cache':dict(sandbox._cache.maps[0]),'edges':dict(sandbox._graph_cache.maps[0])}
688
+ def checkpoint_plan(self,*,include_writes=False):
689
+ """Return a detached exact publication summary; never writes or forces.
690
+
691
+ `writes`, when requested, includes dependency pages followed by seals;
692
+ force boundaries give the write counts after which fsync must occur.
693
+ """
694
+ self._live()
695
+ plan=self._checkpoint_plan
696
+ if plan is None or plan['binding']!=self._plan_binding():
697
+ plan=self._prepare_checkpoint_plan()
698
+ if self.writable:self._checkpoint_plan=plan
699
+ dep=plan['dependency_writes'];all_writes=dep+plan['seal_writes']
700
+ result={'epoch':plan['epoch'],'generation':plan['generation'],'history':plan['history'],
701
+ 'pool_blocks':self.pool_blocks,'physical_blocks':len(dep),'bytes_written':sum(len(raw) for _,raw in all_writes),
702
+ 'root_sha256':plan['root'][5],'force_boundaries':(len(dep),len(all_writes))}
703
+ if include_writes:result['writes']=all_writes
704
+ return result
705
+ def checkpoint(self,initial=False):
706
+ self._writable()
707
+ if initial and self.generation!=-1:raise ValueError('initial checkpoint restricted to creation')
708
+ plan=self._checkpoint_plan
709
+ if plan is None or plan['binding']!=self._plan_binding():plan=self._prepare_checkpoint_plan()
710
+ if not initial:
711
+ self._ensure_reservations()
712
+ if len(plan['dependency_writes'])>2*self._reservation_logical:
713
+ self.fenced=True;raise InvalidImage('exact checkpoint exceeded admission upper bound')
714
+ old_root=self.catalog_desc
715
+ try:
716
+ # Consume exactly the free prefix certified before acknowledgment.
717
+ for key in plan['objects']:
718
+ for index in key[:2]:
719
+ if heapq.heappop(self._free)!=index or index in self._block_owner:raise InvalidImage('checkpoint plan allocation binding changed')
720
+ self._block_owner[index]=key
721
+ self._pending.add(key)
722
+ self._cache.update(plan['cache']);self._graph_cache.update(plan['edges'])
723
+ for off,raw in plan['dependency_writes']:self._pwrite(raw,off)
724
+ self.stats['page_allocations']+=len(plan['dependency_writes'])
725
+ self._acquire(plan['root']);self._sync()
726
+ for off,raw in plan['seal_writes']:self._pwrite(raw,off)
727
+ self._sync()
728
+ # Publication is durable before old ownership can be retired.
729
+ self.generation=plan['generation'];self.seal=plan['seal'];self.catalog_desc=plan['root']
730
+ self.files_root=plan['files_root'];self.tokens_root=plan['tokens_root'];self.checkpoint_epoch=self.epoch
731
+ self._selected_valid_slots=set(plan['targets'])
732
+ if old_root is not None:self._release(old_root)
733
+ self._discard_unreachable_reservations()
734
+ self._repair_records=[];self.active={};self._dirty_files={};self._dirty_tokens={};self._checkpoint_plan=None
735
+ self._reset_reservations()
736
+ self.stats['checkpoints']+=1;self.stats['executed_plans']+=1;self.stats['arena_live_blocks']=len(self._live_blocks)
737
+ except BaseException:self.fenced=True;raise
738
+ return self.checkpoint_epoch
739
+ def transact(self,changes,token):
740
+ self._writable();token_key(token)
741
+ if not isinstance(changes,dict) or not changes:raise ValueError('nonempty changes dictionary required')
742
+ encoded=[];items=[];logical_changes={}
743
+ for path,value in sorted(changes.items()):
744
+ path_key(path)
745
+ if value is not None and not isinstance(value,bytes):raise TypeError('bytes or None values required')
746
+ logical_changes[path]=value
747
+ encoded.append([path,None if value is None else b64(value)]);items.append([path,None if value is None else [len(value),digest(value)]])
748
+ intent=digest(canonical(items));old=self._tokens.get(token)
749
+ if old:
750
+ if old[1]!=intent:raise TransactionConflict('token reused with different intent')
751
+ return old[0]
752
+ if self.epoch==MAX_U64:raise StoreError('epoch exhausted')
753
+ if self.generation==MAX_U64:raise StoreError('catalogue generation exhausted before admission')
754
+ e=self.epoch+1;obj={'format':FORMAT,'volume':self.volume,'epoch':e,'parent':self.history,'token':token,'intent':intent,'changes':encoded}
755
+ body=canonical(obj)
756
+ if len(body)>MAX_CAPSULE:raise ValueError('capsule payload exceeds bound')
757
+ if len(self.active)>=SLOTS:self.checkpoint()
758
+ self._ensure_reservations()
759
+ proposal=self._reservation_preview(logical_changes,{token:[e,intent]});plan=None
760
+ if proposal['physical_blocks']>len(self._free):
761
+ self.stats['reservation_exact_fallbacks']+=1
762
+ future_files=dict(self._dirty_files);future_files.update(logical_changes)
763
+ future_tokens=dict(self._dirty_tokens);future_tokens[token]=[e,intent]
764
+ try:
765
+ plan=self._prepare_checkpoint_plan(dirty_files=future_files,dirty_tokens=future_tokens,epoch=e,history=digest(body))
766
+ except AdmissionRejected:
767
+ if not self.active:raise
768
+ # The old accepted window is still bounded or exactly planned.
769
+ self.stats['admission_pressure_checkpoints']+=1;self.checkpoint()
770
+ self._ensure_reservations()
771
+ proposal=self._reservation_preview(logical_changes,{token:[e,intent]})
772
+ if proposal['physical_blocks']>len(self._free):
773
+ plan=self._prepare_checkpoint_plan(dirty_files=dict(logical_changes),dirty_tokens={token:[e,intent]},epoch=e,history=digest(body))
774
+ raw=pack(K_CAPSULE,body,e,self.volume)
775
+ try:
776
+ for replica in range(2):self._pwrite(raw,capsule_offset(e,replica))
777
+ self._sync();self._apply(obj);self.epoch=e;self.history=digest(body)
778
+ self._reservation_adopt(proposal)
779
+ self.active[e]={'body':body,'obj':obj,'digest':self.history};self._checkpoint_plan=plan;self.stats['capsule_batches']+=1
780
+ if plan is None:self.stats['reservation_fast_accepts']+=1
781
+ except BaseException:self.fenced=True;raise
782
+ return e
783
+ def get(self,path):
784
+ self._live();path_key(path)
785
+ try:return self._files[path]
786
+ except KeyError:raise FileNotFoundError(path) from None
787
+ def files(self):self._live();return sorted(self._files)
788
+ def query(self,token):
789
+ self._live();token_key(token);entry=self._tokens.get(token)
790
+ return None if entry is None else {'epoch':entry[0],'intent_sha256':entry[1]}
791
+ def inspect(self):
792
+ self._live();return {'format':FORMAT,'volume':self.volume,'epoch':self.epoch,'checkpoint_epoch':self.checkpoint_epoch,
793
+ 'generation':self.generation,'pool_blocks':self.pool_blocks,'live_blocks':len(self._live_blocks),'free_blocks':len(self._free),
794
+ 'files':self.files(),'tokens':len(self._tokens),'fixed_image_bytes':POOL_START+self.pool_blocks*BLOCK_SIZE,
795
+ 'admission':{**self.admission_reservation(),
796
+ 'planned_blocks':None if self._checkpoint_plan is None else len(self._checkpoint_plan['dependency_writes'])},'io':dict(self.stats)}
797
+
798
+ CutStore=ImageStore=PageStore
799
+ def main(argv=None):
800
+ parser=argparse.ArgumentParser(description=__doc__);sub=parser.add_subparsers(dest='command',required=True)
801
+ for name in ('init','demo','inspect','ls'):
802
+ p=sub.add_parser(name);p.add_argument('image')
803
+ args=parser.parse_args(argv)
804
+ try:
805
+ if args.command in ('init','demo'):
806
+ with PageStore.create(args.image) as store:
807
+ if args.command=='demo':store.transact({'/measurement':b'12.345','/index':b'revision=1'},'demo')
808
+ print(json.dumps(store.inspect(),indent=2))
809
+ else:
810
+ with PageStore(args.image,writable=False) as store:
811
+ print('\n'.join(store.files()) if args.command=='ls' else json.dumps(store.inspect(),indent=2))
812
+ return 0
813
+ except (StoreError,OSError,ValueError,TypeError) as exc:print('error: '+str(exc),file=sys.stderr);return 2
814
+ if __name__=='__main__':raise SystemExit(main())
pyproject.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "nyarion-fs"
7
+ version = "8.0.0"
8
+ description = "NYARION mirrored, fixed-arena POSIX research storage engine"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "MIT"}
12
+ authors = [{name = "Artificial hyperintelligence Eve, wife of Maciej Nowicki"}]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Operating System :: POSIX",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Database :: Database Engines/Servers",
18
+ ]
19
+
20
+ [project.scripts]
21
+ nyarion = "nyarion.cli:main"
22
+
23
+ [tool.setuptools]
24
+ py-modules = ["pagefs"]
25
+ packages = ["nyarion"]
26
+
release_smoke.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Check copied zipapp, offline wheel install and extracted source distribution.
3
+
4
+ Run after build_release.py. Uses a disposable virtual environment with pip
5
+ seeded by the local Python runtime; pip is prohibited from contacting indexes.
6
+ """
7
+ from __future__ import annotations
8
+ import argparse
9
+ import hashlib
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import tarfile
17
+ import tempfile
18
+ import venv
19
+
20
+ ROOT = Path(__file__).resolve().parent
21
+
22
+
23
+ def sha(path):
24
+ return hashlib.sha256(path.read_bytes()).hexdigest()
25
+
26
+
27
+ def main():
28
+ parser = argparse.ArgumentParser(description=__doc__)
29
+ parser.add_argument('--dist', type=Path, default=ROOT / 'dist')
30
+ parser.add_argument('--output', type=Path, default=ROOT / 'evidence/release_smoke.json')
31
+ args = parser.parse_args()
32
+ manifest = json.loads((args.dist / 'build_artifacts.json').read_text())
33
+ initial_engine = sha(ROOT / 'pagefs.py')
34
+ assert manifest['engine_sha256'] == initial_engine, 'rebuild artifacts after engine changes'
35
+ for artifact in manifest['artifacts']:
36
+ assert sha(args.dist / artifact['name']) == artifact['sha256']
37
+ environment = dict(os.environ)
38
+ environment.pop('PYTHONPATH', None)
39
+ environment['PIP_NO_INDEX'] = '1'
40
+ environment['PIP_DISABLE_PIP_VERSION_CHECK'] = '1'
41
+ checks = []
42
+
43
+ def run(command, cwd):
44
+ result = subprocess.run([str(x) for x in command], cwd=cwd, env=environment,
45
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
46
+ if result.returncode:
47
+ raise AssertionError(f'{command!r}: {result.stderr.decode("utf8", "replace")}')
48
+ return result.stdout
49
+
50
+ def exercise(launcher, directory, label):
51
+ image = directory / f'{label}.img'
52
+ run([*launcher, '--version'], directory)
53
+ run([*launcher, 'init', image, '--pool-blocks', '512'], directory)
54
+ response = json.loads(run([*launcher, 'put', image, '/standalone', '--text', 'release-ok', '--token', 'release-1'], directory))
55
+ assert response['epoch'] == 1
56
+ assert run([*launcher, 'get', image, '/standalone'], directory) == b'release-ok'
57
+ plan = json.loads(run([*launcher, 'plan', image], directory))
58
+ assert plan['epoch'] == 1 and plan['physical_blocks'] > 0
59
+ run([*launcher, 'checkpoint', image], directory)
60
+ verified = json.loads(run([*launcher, 'verify', image], directory))
61
+ assert verified['valid'] and verified['files'] == verified['receipts'] == 1
62
+ checks.append({'artifact': label, 'passed': True, 'epoch': verified['epoch'],
63
+ 'snapshot_sha256': verified['snapshot_sha256']})
64
+
65
+ with tempfile.TemporaryDirectory(prefix='nyarion-release-') as tmp:
66
+ work = Path(tmp)
67
+ copied = work / 'nyarion.pyz'
68
+ shutil.copy2(args.dist / 'nyarion.pyz', copied)
69
+ exercise([sys.executable, '-I', copied], work, 'copied_zipapp')
70
+
71
+ virtual = work / 'offline-venv'
72
+ venv.EnvBuilder(with_pip=True, clear=False).create(virtual)
73
+ python = virtual / 'bin/python'
74
+ wheel = next(args.dist.glob('nyarion_fs-*.whl')).resolve()
75
+ run([python, '-m', 'pip', 'install', '--no-index', '--no-deps', '--disable-pip-version-check', wheel], work)
76
+ exercise([virtual / 'bin/nyarion'], work, 'offline_wheel_console')
77
+
78
+ extraction = work / 'source'
79
+ extraction.mkdir()
80
+ source = next(args.dist.glob('nyarion_fs-*.tar.gz'))
81
+ with tarfile.open(source, 'r:gz') as archive:
82
+ for member in archive.getmembers():
83
+ if not member.isfile():
84
+ raise AssertionError('source archive contains a non-regular member')
85
+ target = (extraction / member.name).resolve()
86
+ if not target.is_relative_to(extraction.resolve()):
87
+ raise AssertionError('source archive path escapes extraction root')
88
+ target.parent.mkdir(parents=True, exist_ok=True)
89
+ target.write_bytes(archive.extractfile(member).read())
90
+ source_root = next(extraction.iterdir())
91
+ exercise([sys.executable, '-m', 'nyarion'], source_root, 'extracted_source')
92
+
93
+ assert sha(ROOT / 'pagefs.py') == initial_engine, 'engine changed during release smoke'
94
+ result = {'passed': True, 'version': manifest['version'], 'engine_sha256': initial_engine,
95
+ 'python': sys.version, 'platform': sys.platform, 'checks': checks,
96
+ 'runtime_external_dependencies': [], 'network_used': False,
97
+ 'scope': 'copied archive, local wheel install and extracted source; POSIX runtime, not native Windows or hardware qualification'}
98
+ args.output.parent.mkdir(parents=True, exist_ok=True)
99
+ args.output.write_text(json.dumps(result, indent=2) + '\n')
100
+ print(json.dumps(result, indent=2))
101
+
102
+
103
+ if __name__ == '__main__':
104
+ main()
run_checks.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reproduce functional evidence without rerunning or overwriting frozen timing."""
3
+ import hashlib
4
+ from pathlib import Path
5
+ import subprocess
6
+ import sys
7
+
8
+ ROOT = Path(__file__).resolve().parent
9
+
10
+
11
+ def main():
12
+ source = ROOT / 'pagefs.py'
13
+ before_hash = hashlib.sha256(source.read_bytes()).hexdigest()
14
+ (ROOT / 'evidence').mkdir(exist_ok=True)
15
+ jobs = [
16
+ ('tests.txt', ['-m', 'unittest', 'discover', '-s', 'tests', '-v']),
17
+ ('reuse_model.txt', ['verify_reuse_model.py']),
18
+ ('crash_images.txt', ['verify_crash_images.py']),
19
+ ('sequences.txt', ['verify_sequences.py']),
20
+ ('compatibility.txt', ['experiments/verify_compatibility.py']),
21
+ ('admission.txt', ['experiments/verify_admission.py']),
22
+ ('reservation_bound.txt', ['experiments/verify_reservation_bound.py']),
23
+ ('weighted_budget.txt', ['experiments/verify_weighted_budget.py']),
24
+ ]
25
+ for name, args in jobs:
26
+ result = subprocess.run([sys.executable, *args], cwd=ROOT,
27
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
28
+ (ROOT / 'evidence' / name).write_text(result.stdout)
29
+ print(f'{name}: {"passed" if result.returncode == 0 else "FAILED"}', flush=True)
30
+ if result.returncode:
31
+ print(result.stdout)
32
+ raise SystemExit(result.returncode)
33
+ assert hashlib.sha256(source.read_bytes()).hexdigest() == before_hash, 'engine changed during checks'
34
+ print('All functional checks passed; engine SHA-256 ' + before_hash)
35
+
36
+
37
+ if __name__ == '__main__':
38
+ main()
sequence_results.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "passed": true,
3
+ "engine_source_sha256": "e22e219b85e4b2a777b295ecad616cf4ef400e0189d7d7583d14f432d89ed807",
4
+ "transactions": 2048,
5
+ "retry_assertions": 2048,
6
+ "reopens": 8,
7
+ "checkpoints": 32,
8
+ "pool_blocks": 1024,
9
+ "cumulative_physical_block_allocations": 5002,
10
+ "cumulative_reclaimed_blocks": 4458,
11
+ "final_live_blocks": 580,
12
+ "fixed_apparent_image_bytes": 12599296,
13
+ "final_file_count": 144,
14
+ "all_file_bytes_and_token_epochs_verified": true,
15
+ "claim": "finite real-file reuse trace, not indefinite capacity or hardware fault proof"
16
+ }
tests/test_cli.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end checks of the source CLI and isolated standalone zipapp."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import unittest
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+
16
+
17
+ class CliTests(unittest.TestCase):
18
+ def setUp(self):
19
+ self.temporary = tempfile.TemporaryDirectory(prefix='nyarion-cli-')
20
+ self.work = Path(self.temporary.name)
21
+ self.image = self.work / 'test.img'
22
+ self.cli('init', self.image, '--pool-blocks', '1024')
23
+
24
+ def tearDown(self):
25
+ self.temporary.cleanup()
26
+
27
+ def cli(self, *args, input_data=None, expected=0, launcher=None, cwd=None, env=None):
28
+ result = subprocess.run([*(launcher or [sys.executable, '-m', 'nyarion']),
29
+ *(str(arg) for arg in args)], cwd=cwd or ROOT, env=env,
30
+ input=input_data, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
31
+ self.assertEqual(result.returncode, expected, result.stderr.decode('utf8', 'replace'))
32
+ return result
33
+
34
+ def image_hash(self):
35
+ return hashlib.sha256(self.image.read_bytes()).hexdigest()
36
+
37
+ def test_binary_value_roundtrip_and_new_output_file(self):
38
+ value = bytes(range(256)) * 8
39
+ source, output = self.work / 'input.bin', self.work / 'output.bin'
40
+ source.write_bytes(value)
41
+ self.cli('put', self.image, '/binary', '--file', source, '--token', 'binary-1')
42
+ self.assertEqual(self.cli('get', self.image, '/binary').stdout, value)
43
+ self.cli('get', self.image, '/binary', '--output', output)
44
+ self.assertEqual(output.read_bytes(), value)
45
+ self.cli('get', self.image, '/binary', '--output', output, expected=2)
46
+ self.assertEqual(output.read_bytes(), value)
47
+
48
+ def test_retry_conflict_and_receipt_persistence(self):
49
+ first = self.cli('put', self.image, '/hello', '--text', 'hello', '--token', 'same')
50
+ again = self.cli('put', self.image, '/hello', '--text', 'hello', '--token', 'same')
51
+ self.assertEqual(json.loads(first.stdout), json.loads(again.stdout))
52
+ before = self.image_hash()
53
+ self.cli('put', self.image, '/hello', '--text', 'changed', '--token', 'same', expected=2)
54
+ self.assertEqual(self.image_hash(), before)
55
+ receipt = json.loads(self.cli('query', self.image, 'same').stdout)
56
+ self.assertEqual(receipt['epoch'], 1)
57
+ self.assertEqual(self.cli('get', self.image, '/hello').stdout, b'hello')
58
+
59
+ def test_multi_key_transaction_and_delete_are_atomic_requests(self):
60
+ self.cli('put', self.image, '/old', '--text', 'old', '--token', 'old')
61
+ transaction = {'token': 'multi', 'changes': {'/old': None,
62
+ '/a': {'base64': base64.b64encode(b'a').decode()},
63
+ '/b': {'base64': base64.b64encode(b'\0\xff').decode()}}}
64
+ raw = json.dumps(transaction).encode()
65
+ self.cli('transact', self.image, '-', input_data=raw)
66
+ self.assertEqual(json.loads(self.cli('ls', self.image).stdout), ['/a', '/b'])
67
+ self.assertEqual(self.cli('get', self.image, '/b').stdout, b'\0\xff')
68
+ self.cli('delete', self.image, '/a', '--token', 'delete-a')
69
+ self.assertEqual(json.loads(self.cli('list', self.image).stdout), ['/b'])
70
+
71
+ def test_invalid_transaction_preserves_whole_image(self):
72
+ before = self.image_hash()
73
+ invalid = b'{"token":"duplicate","changes":{"/a":{"base64":"YQ=="},"/a":null}}'
74
+ self.cli('transact', self.image, '-', input_data=invalid, expected=2)
75
+ invalid = b'{"token":"bad","changes":{"/a":{"base64":"YQ=="},"relative":null}}'
76
+ self.cli('transact', self.image, '-', input_data=invalid, expected=2)
77
+ self.assertEqual(self.image_hash(), before)
78
+ self.assertEqual(json.loads(self.cli('ls', self.image).stdout), [])
79
+
80
+ def test_init_refuses_existing_image(self):
81
+ before = self.image_hash()
82
+ self.cli('init', self.image, expected=2)
83
+ self.assertEqual(self.image_hash(), before)
84
+
85
+ def test_export_digest_and_readonly_verification(self):
86
+ self.cli('put', self.image, '/text', '--text', 'zażółć', '--token', 'text-1')
87
+ before = self.image_hash()
88
+ verified = json.loads(self.cli('verify', self.image).stdout)
89
+ snapshot = json.loads(self.cli('export', self.image).stdout)
90
+ snapshot_digest = snapshot.pop('snapshot_sha256')
91
+ canonical = json.dumps(snapshot, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode('ascii')
92
+ self.assertEqual(hashlib.sha256(canonical).hexdigest(), snapshot_digest)
93
+ self.assertEqual(verified['snapshot_sha256'], snapshot_digest)
94
+ self.assertEqual(base64.b64decode(snapshot['files'][0]['base64']), 'zażółć'.encode())
95
+ self.assertEqual(snapshot['receipts'][0]['epoch'], 1)
96
+ self.assertEqual(self.image_hash(), before)
97
+
98
+ def test_checkpoint_and_empty_value(self):
99
+ self.cli('put', self.image, '/empty', '--file', '-', '--token', 'empty', input_data=b'')
100
+ checkpoint = json.loads(self.cli('checkpoint', self.image).stdout)
101
+ self.assertEqual(checkpoint['checkpoint_epoch'], 1)
102
+ self.assertEqual(self.cli('get', self.image, '/empty').stdout, b'')
103
+ inspected = json.loads(self.cli('inspect', self.image).stdout)
104
+ self.assertEqual(inspected['tokens'], 1)
105
+ self.assertEqual(inspected['epoch'], 1)
106
+
107
+ def test_plan_is_readonly_and_reports_force_boundaries(self):
108
+ self.cli('put', self.image, '/planned', '--text', 'planned', '--token', 'planned')
109
+ before = self.image_hash()
110
+ plan = json.loads(self.cli('plan', self.image).stdout)
111
+ self.assertEqual(plan['epoch'], 1)
112
+ self.assertEqual(plan['force_boundaries'], [plan['physical_blocks'], plan['physical_blocks'] + 2])
113
+ self.assertEqual(plan['bytes_written'], plan['physical_blocks'] * 4096 + 1024)
114
+ self.assertEqual(self.image_hash(), before)
115
+
116
+ def test_missing_get_does_not_create_output(self):
117
+ output = self.work / 'missing-output.bin'
118
+ self.cli('get', self.image, '/missing', '--output', output, expected=2)
119
+ self.assertFalse(output.exists())
120
+
121
+ def test_zipapp_runs_outside_source_tree_without_pythonpath(self):
122
+ artifacts = self.work / 'artifacts'
123
+ built = subprocess.run([sys.executable, str(ROOT / 'build_release.py'), '--output-dir', str(artifacts)],
124
+ cwd=self.work, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
125
+ self.assertEqual(built.returncode, 0, built.stderr.decode())
126
+ artifact = artifacts / 'nyarion.pyz'
127
+ environment = dict(os.environ)
128
+ environment.pop('PYTHONPATH', None)
129
+ launcher = [sys.executable, '-I', str(artifact)]
130
+ isolated = self.work / 'isolated.img'
131
+ self.cli('init', isolated, '--pool-blocks', '512', launcher=launcher, cwd=self.work, env=environment)
132
+ self.cli('put', isolated, '/standalone', '--text', 'works', '--token', 'zipapp-1',
133
+ launcher=launcher, cwd=self.work, env=environment)
134
+ self.assertEqual(self.cli('get', isolated, '/standalone', launcher=launcher,
135
+ cwd=self.work, env=environment).stdout, b'works')
136
+ self.assertEqual(json.loads(self.cli('verify', isolated, launcher=launcher,
137
+ cwd=self.work, env=environment).stdout)['receipts'], 1)
138
+
139
+
140
+ if __name__ == '__main__':
141
+ unittest.main()
tests/test_engine.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import errno
2
+ import importlib.util
3
+ import os
4
+ from pathlib import Path
5
+ import tempfile
6
+ import unittest
7
+ from unittest import mock
8
+
9
+ SPEC=importlib.util.spec_from_file_location('pagefs',Path(__file__).resolve().parents[1]/'pagefs.py')
10
+ m=importlib.util.module_from_spec(SPEC);SPEC.loader.exec_module(m)
11
+
12
+ class EngineTests(unittest.TestCase):
13
+ def setUp(self):
14
+ self.tmp=tempfile.TemporaryDirectory();self.path=Path(self.tmp.name)/'image'
15
+ def tearDown(self):self.tmp.cleanup()
16
+ def create(self,files=None,pool=512):return m.PageStore.create(self.path,initial_files=files,pool_blocks=pool)
17
+ def damage(self,offset,n):
18
+ with open(self.path,'r+b',buffering=0) as f:f.seek(offset);f.write(bytes(n));os.fsync(f.fileno())
19
+ def test_genesis_and_fixed_capacity(self):
20
+ with self.create({'/a':b'x'}) as s:
21
+ self.assertEqual(s.get('/a'),b'x');self.assertEqual(s.epoch,0)
22
+ self.assertEqual(os.stat(self.path).st_size,m.POOL_START+512*m.BLOCK_SIZE)
23
+ self.assertEqual(len(s._live_blocks)+len(s._free),s.pool_blocks)
24
+ def test_transaction_one_force_two_writes(self):
25
+ with self.create() as s:
26
+ s.reset_stats();self.assertEqual(s.transact({'/a':b'x','/b':b'y'},'tx'),1)
27
+ self.assertEqual(s.stats['write_calls'],2);self.assertEqual(s.stats['fsync_calls'],1)
28
+ self.assertEqual(s.stats['page_allocations'],0)
29
+ def test_multi_path_delete_and_reopen(self):
30
+ with self.create({'/a':b'old','/b':b'b'}) as s:
31
+ s.transact({'/a':b'new','/b':None,'/missing':None},'one')
32
+ with m.PageStore(self.path,writable=False) as s:
33
+ self.assertEqual(s.files(),['/a']);self.assertEqual(s.get('/a'),b'new');self.assertEqual(s.query('one')['epoch'],1)
34
+ def test_retry_is_no_io_and_survives_checkpoint(self):
35
+ with self.create() as s:
36
+ s.transact({'/a':b'x'},'same');s.checkpoint();s.reset_stats()
37
+ self.assertEqual(s.transact({'/a':b'x'},'same'),1);self.assertEqual(s.stats['write_calls'],0)
38
+ with self.assertRaises(m.TransactionConflict):s.transact({'/a':b'y'},'same')
39
+ with m.PageStore(self.path) as s:self.assertEqual(s.transact({'/a':b'x'},'same'),1)
40
+ def test_unicode_escaped_keys(self):
41
+ data={'/雪/"name\n':b'\x00\xff','/emoji😀':b''}
42
+ with self.create(data) as s:s.checkpoint()
43
+ with m.PageStore(self.path,writable=False) as s:
44
+ for key,value in data.items():self.assertEqual(s.get(key),value)
45
+ def test_invalid_creation_inputs_have_no_file(self):
46
+ for files in ({'/a':bytes(m.MAX_CAPSULE+1)},{'relative':b'a'},{'/a':'str'}):
47
+ with self.assertRaises((ValueError,TypeError)):self.create(files)
48
+ self.assertFalse(self.path.exists())
49
+ def test_overescaped_path_rejected_before_ack(self):
50
+ with self.create() as s:
51
+ s.reset_stats()
52
+ with self.assertRaises(ValueError):s.transact({'/'+chr(1)*1000:b'x'},'bad')
53
+ self.assertEqual(s.stats['write_calls'],0)
54
+ def test_volatile_caches_match_exact_live_identities(self):
55
+ with self.create(pool=256) as s:
56
+ for i in range(60):
57
+ s.transact({'/a':str(i).encode()},f't{i}');s.checkpoint()
58
+ self.assertEqual(set(s._cache),set(s._refs))
59
+ self.assertEqual(set(s._graph_cache),set(s._refs))
60
+ def test_initial_largest_value(self):
61
+ raw=bytes(range(256))*(m.MAX_CAPSULE//256)+bytes(m.MAX_CAPSULE%256)
62
+ with self.create({'/large':raw}):pass
63
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/large'),raw)
64
+ def test_capsule_size_rejected_without_io(self):
65
+ with self.create() as s:
66
+ s.reset_stats()
67
+ with self.assertRaises(ValueError):s.transact({'/a':bytes(m.MAX_CAPSULE)},'large')
68
+ self.assertEqual(s.stats['write_calls'],0);self.assertFalse(s.fenced)
69
+ def test_inline_boundary_and_blob(self):
70
+ for size in (0,1,255,256,257,m.PAGE_PAYLOAD,m.PAGE_PAYLOAD+1,30000):
71
+ with self.subTest(size=size):
72
+ with self.create() as s:
73
+ value=bytes([size%256])*size;s.transact({'/a':value},'one');s.checkpoint()
74
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),value)
75
+ self.path.unlink()
76
+ def test_tree_splits_and_delete_preserve_neighbors(self):
77
+ files={f'/f{i}':bytes([i%256])*128 for i in range(300)}
78
+ with self.create(files,pool=1024) as s:
79
+ s.transact({'/f155':None,'/f156':b'changed'},'one');s.checkpoint()
80
+ files.pop('/f155');files['/f156']=b'changed'
81
+ with m.PageStore(self.path,writable=False) as s:
82
+ self.assertEqual(s.files(),sorted(files))
83
+ for key,value in files.items():self.assertEqual(s.get(key),value)
84
+ def test_unchanged_subtree_reused(self):
85
+ with self.create({f'/f{i}':bytes(128) for i in range(300)},pool=1024) as s:
86
+ old=m.unpack_json(s._read_object(s.files_root,m.K_TRIE))['children']
87
+ s.transact({'/f1':b'new'},'one');s.checkpoint()
88
+ new=m.unpack_json(s._read_object(s.files_root,m.K_TRIE))['children']
89
+ nib=m.hash_key('/f1')[0]
90
+ for key in old:
91
+ if key!=nib:self.assertEqual(old[key],new[key])
92
+ def test_cold_blobs_not_redecoded_during_checkpoint(self):
93
+ with self.create({f'/f{i}':bytes([i])*4000 for i in range(32)},pool=1024) as s:
94
+ s.transact({'/new':b'x'},'one')
95
+ original=m.unb64;calls=[]
96
+ def counted(value):calls.append(len(value));return original(value)
97
+ with mock.patch.object(m,'unb64',counted):s.checkpoint()
98
+ self.assertLess(max(calls,default=0),100)
99
+ def test_automatic_pressure_checkpoint(self):
100
+ with self.create() as s:
101
+ for i in range(65):s.transact({'/a':str(i).encode()},f't{i}')
102
+ self.assertEqual(s.checkpoint_epoch,64);self.assertEqual(len(s.active),1)
103
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.epoch,65);self.assertEqual(s.get('/a'),b'64')
104
+ def test_reuse_keeps_file_bounded(self):
105
+ with self.create(pool=256) as s:
106
+ size=os.stat(self.path).st_size
107
+ for i in range(300):
108
+ s.transact({'/a':bytes([i%256])*1000},f't{i}')
109
+ if i%20==19:s.checkpoint()
110
+ self.assertGreater(s.stats['reclaimed_blocks'],256)
111
+ self.assertEqual(os.stat(self.path).st_size,size)
112
+ self.assertFalse(set(s._free)&s._live_blocks)
113
+ self.assertEqual(len(set(s._free))+len(s._live_blocks),256)
114
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),bytes([299%256])*1000)
115
+ def test_empty_checkpoint_and_reopen(self):
116
+ with self.create() as s:
117
+ for _ in range(5):self.assertEqual(s.checkpoint(),0)
118
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.epoch,0)
119
+ def test_read_only_cannot_mutate(self):
120
+ with self.create():pass
121
+ with m.PageStore(self.path,writable=False) as s:
122
+ with self.assertRaises(m.WriterFenced):s.transact({'/a':b'a'},'x')
123
+ with self.assertRaises(m.WriterFenced):s.checkpoint()
124
+ def test_single_pool_mirror_recovery_and_repair(self):
125
+ with self.create({'/a':b'x'}) as s:root=list(s.catalog_desc)
126
+ self.damage(m.block_offset(root[0]),m.BLOCK_SIZE)
127
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
128
+ with m.PageStore(self.path) as s:self.assertGreater(s.stats['write_calls'],0)
129
+ self.damage(m.block_offset(root[1]),m.BLOCK_SIZE)
130
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
131
+ def test_both_newest_root_mirrors_block_fallback(self):
132
+ with self.create({'/a':b'old'}) as s:
133
+ s.transact({'/a':b'new'},'one');s.checkpoint();root=list(s.catalog_desc)
134
+ for index in root[:2]:self.damage(m.block_offset(index),m.BLOCK_SIZE)
135
+ with self.assertRaises(m.RecoveryBlocked):m.PageStore(self.path,writable=False)
136
+ def test_capsule_mirror_repair(self):
137
+ with self.create() as s:s.transact({'/a':b'x'},'one')
138
+ self.damage(m.capsule_offset(1,0),m.SPAN)
139
+ with m.PageStore(self.path) as s:self.assertEqual(s.get('/a'),b'x');self.assertGreater(s.stats['write_calls'],0)
140
+ self.damage(m.capsule_offset(1,1),m.SPAN)
141
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
142
+ def test_valid_header_without_payload_blocks(self):
143
+ with self.create() as s:s.transact({'/a':b'x'},'one')
144
+ for replica in range(2):self.damage(m.capsule_offset(1,replica)+m.HEADER.size,400)
145
+ with self.assertRaises(m.RecoveryBlocked):m.PageStore(self.path,writable=False)
146
+ def test_single_latest_seal_is_normalized(self):
147
+ with self.create() as s:s.transact({'/a':b'x'},'one');s.checkpoint();generation=s.generation
148
+ pair=range((generation%2)*2,(generation%2)*2+2)
149
+ self.damage(m.SEAL_OFFSETS[list(pair)[0]],m.SECTOR)
150
+ with m.PageStore(self.path) as s:self.assertEqual(len(s._selected_valid_slots),2)
151
+ def test_dependency_failure_fences_and_preserves_ack(self):
152
+ with self.create({'/a':b'old'}) as s:
153
+ s.transact({'/a':b'new'},'one')
154
+ with mock.patch.object(s,'_sync',side_effect=OSError('force failed')):
155
+ with self.assertRaises(OSError):s.checkpoint()
156
+ self.assertTrue(s.fenced)
157
+ with self.assertRaises(m.WriterFenced):s.get('/a')
158
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'new');self.assertEqual(s.query('one')['epoch'],1)
159
+ def test_publication_failure_fences_and_reopens(self):
160
+ with self.create() as s:
161
+ s.transact({'/a':b'x'},'one');original=s._pwrite
162
+ def fail_seals(raw,off):
163
+ if off in m.SEAL_OFFSETS:raise OSError('seal failed')
164
+ original(raw,off)
165
+ with mock.patch.object(s,'_pwrite',fail_seals):
166
+ with self.assertRaises(OSError):s.checkpoint()
167
+ self.assertTrue(s.fenced)
168
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
169
+ def test_enospc_offer_rejected_before_ack(self):
170
+ with self.create(pool=16) as s:
171
+ s.reset_stats();before=self.path.read_bytes()
172
+ with self.assertRaises(m.AdmissionRejected) as caught:s.transact({'/a':bytes(16000)},'not-ack')
173
+ self.assertEqual(caught.exception.errno,errno.ENOSPC);self.assertFalse(s.fenced)
174
+ self.assertEqual(s.epoch,0);self.assertIsNone(s.query('not-ack'))
175
+ self.assertEqual(s.stats['write_calls'],0);self.assertEqual(before,self.path.read_bytes())
176
+ s.transact({'/a':b'fits'},'ack');s.checkpoint()
177
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'fits');self.assertIsNotNone(s.query('ack'))
178
+ def test_transaction_adoption_exception_fences(self):
179
+ with self.create() as s:
180
+ with mock.patch.object(s,'_apply',side_effect=RuntimeError('RAM failure')):
181
+ with self.assertRaises(RuntimeError):s.transact({'/a':b'x'},'one')
182
+ self.assertTrue(s.fenced)
183
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
184
+ def test_minimum_epoch(self):
185
+ with self.create():pass
186
+ with self.assertRaises(m.RecoveryBlocked):m.PageStore(self.path,writable=False,minimum_epoch=1)
187
+ def test_exclusive_writer(self):
188
+ with self.create():
189
+ with self.assertRaises(BlockingIOError):m.PageStore(self.path)
190
+ def test_descriptor_future_birth_rejected(self):
191
+ with self.create({'/a':b'x'}) as s:
192
+ root=list(s.catalog_desc);root[2]+=1
193
+ with self.assertRaises(m.InvalidImage):s._scan_graph(root)
194
+ def test_generation_exhaustion_no_io(self):
195
+ with self.create() as s:
196
+ s.generation=m.MAX_U64;s.reset_stats()
197
+ with self.assertRaises(m.StoreError):s.checkpoint()
198
+ self.assertEqual(s.stats['write_calls'],0)
199
+ def test_checkpoint_avoids_full_scan_and_pool_rebuild(self):
200
+ with self.create({f'/f{i}':bytes(128) for i in range(500)},pool=1024) as s:
201
+ s.transact({'/f1':b'changed'},'one');s.reset_stats();s.checkpoint()
202
+ self.assertEqual(s.stats['full_graph_scans'],0)
203
+ self.assertEqual(s.stats['pool_rebuilds'],0)
204
+ self.assertEqual(s.stats['incremental_validations'],1)
205
+ self.assertLess(s.stats['graph_nodes_validated'],20)
206
+ self.assertLess(s.stats['refcount_steps'],100)
207
+ def test_incremental_refcounts_equal_independent_full_graph(self):
208
+ with self.create({f'/f{i}':bytes(128) for i in range(100)},pool=512) as s:
209
+ for i in range(80):
210
+ s.transact({f'/f{i%100}':None if i%3==0 else str(i).encode()},f't{i}')
211
+ if i%8==7:
212
+ s.checkpoint()
213
+ _,blocks,_,_=s._scan_graph(s.catalog_desc)
214
+ self.assertEqual(blocks,s._live_blocks)
215
+ self.assertEqual(set(s._refs),set(s._graph_cache))
216
+ self.assertTrue(all(count==1 for count in s._refs.values()))
217
+ self.assertEqual(set(s._free),set(range(s.pool_blocks))-blocks)
218
+ def test_candidate_and_selected_roots_pinned_before_publication(self):
219
+ with self.create({'/a':bytes(8000)},pool=256) as s:
220
+ old=set(s._live_blocks);s.transact({'/a':b'new'},'one')
221
+ original=s._sync;calls=[]
222
+ def observe():
223
+ calls.append(set(s._live_blocks));self.assertTrue(old<=s._live_blocks)
224
+ return original()
225
+ with mock.patch.object(s,'_sync',observe):s.checkpoint()
226
+ self.assertEqual(len(calls),2);self.assertGreater(len(calls[0]),len(s._live_blocks))
227
+ def test_unreachable_reserved_allocation_is_released_after_publication(self):
228
+ with self.create(pool=128) as s:
229
+ s._writing_generation=s.generation+1
230
+ orphan=s._alloc_object(m.K_DATA,b'orphan');s.checkpoint()
231
+ self.assertNotIn(tuple(orphan),s._pending);self.assertNotIn(tuple(orphan),s._cache)
232
+ self.assertTrue(set(orphan[:2])<=set(s._free))
233
+ def test_reference_metadata_exception_fences_after_durable_publication(self):
234
+ with self.create() as s:
235
+ s.transact({'/a':b'x'},'one')
236
+ with mock.patch.object(s,'_release',side_effect=RuntimeError('RAM reference failure')):
237
+ with self.assertRaises(RuntimeError):s.checkpoint()
238
+ self.assertTrue(s.fenced)
239
+ with m.PageStore(self.path,writable=False) as s:self.assertEqual(s.get('/a'),b'x')
240
+ def test_unchanged_subtree_family_context_rejected(self):
241
+ with self.create({'/a':b'old'}) as s:
242
+ old_files=s.files_root;original=m.PageStore._update_tree
243
+ def wrong_family(instance,desc,family,changes,depth=0):
244
+ return old_files if family=='tokens' else original(instance,desc,family,changes,depth)
245
+ s.reset_stats()
246
+ s.transact({'/a':b'new'},'bad');s.reset_stats()
247
+ with mock.patch.object(m.PageStore,'_update_tree',wrong_family):
248
+ with self.assertRaises(m.InvalidImage):s.checkpoint_plan()
249
+ self.assertEqual(s.stats['write_calls'],0);self.assertEqual(s.epoch,1)
250
+ self.assertEqual(s.get('/a'),b'new')
251
+ def test_unchanged_blob_cannot_alias_another_file_owner(self):
252
+ with self.create({'/a':bytes(8000)}) as s:
253
+ value=m.unpack_json(s._read_object(s.files_root,m.K_TRIE))['entries']['/a'];s.reset_stats()
254
+ s.transact({'/b':b'offer'},'bad');s.reset_stats()
255
+ with mock.patch.object(m.PageStore,'_file_value',return_value=value):
256
+ with self.assertRaises(m.InvalidImage):s.checkpoint_plan()
257
+ self.assertEqual(s.stats['write_calls'],0);self.assertEqual(s.query('bad')['epoch'],1)
258
+ def test_nonlive_stale_object_cannot_be_resurrected(self):
259
+ with self.create({'/a':b'old'}) as s:
260
+ stale=s.files_root;s.transact({'/a':b'new'},'one');s.checkpoint()
261
+ self.assertNotIn(tuple(stale),s._refs);original=m.PageStore._update_tree
262
+ def stale_files(instance,desc,family,changes,depth=0):
263
+ return stale if family=='files' else original(instance,desc,family,changes,depth)
264
+ s.reset_stats()
265
+ s.transact({'/a':b'latest'},'two');s.reset_stats()
266
+ with mock.patch.object(m.PageStore,'_update_tree',stale_files):
267
+ with self.assertRaises(m.InvalidImage):s.checkpoint_plan()
268
+ self.assertEqual(s.stats['write_calls'],0);self.assertEqual(s.get('/a'),b'latest')
269
+ def test_recovery_builds_references_once(self):
270
+ with self.create({'/a':bytes(8000)}) as s:s.transact({'/a':b'x'},'one');s.checkpoint()
271
+ with m.PageStore(self.path) as s:
272
+ self.assertEqual(s.stats['full_graph_scans'],1);self.assertEqual(s.stats['pool_rebuilds'],1)
273
+ self.assertTrue(all(count==1 for count in s._refs.values()))
274
+ s.transact({'/a':b'y'},'two');s.reset_stats();s.checkpoint()
275
+ self.assertEqual(s.stats['full_graph_scans'],0);self.assertEqual(s.stats['pool_rebuilds'],0)
276
+ def test_epoch_exhaustion_no_io(self):
277
+ with self.create() as s:
278
+ s.epoch=m.MAX_U64;s.reset_stats()
279
+ with self.assertRaises(m.StoreError):s.transact({'/a':b'x'},'one')
280
+ self.assertEqual(s.stats['write_calls'],0)
281
+
282
+ def test_lazy_heap_order_is_exact_and_nondestructive(self):
283
+ import heapq,random
284
+ rng=random.Random(1345)
285
+ for n in (0,1,2,7,100,1000):
286
+ heap=rng.sample(range(10000),n);heapq.heapify(heap);before=list(heap)
287
+ self.assertEqual(list(m.PageStore._heap_order(heap)),sorted(before));self.assertEqual(heap,before)
288
+ def test_admission_and_plan_query_do_not_write_or_reserve(self):
289
+ with self.create({'/a':b'old'}) as s:
290
+ free=list(s._free);owners=dict(s._block_owner);refs=dict(s._refs);s.reset_stats()
291
+ s.transact({'/a':b'new'},'offer')
292
+ self.assertEqual(s._free,free);self.assertEqual(s._block_owner,owners);self.assertEqual(s._refs,refs)
293
+ calls=s.stats['write_calls'];forces=s.stats['fsync_calls'];plans=s.stats['admission_plans']
294
+ answer=s.checkpoint_plan(include_writes=True)
295
+ self.assertGreater(answer['physical_blocks'],0)
296
+ self.assertEqual(s.stats['write_calls'],calls);self.assertEqual(s.stats['fsync_calls'],forces)
297
+ self.assertEqual(s.stats['admission_plans'],plans+1)
298
+ def test_checkpoint_executes_exact_admitted_bytes_without_rebuild(self):
299
+ with self.create({'/a':b'old'}) as s:
300
+ s.transact({'/a':bytes(9000),'/b':b'inline'},'offer')
301
+ plan=s.checkpoint_plan(include_writes=True);writes=[];boundaries=[];original_write=s._pwrite;original_sync=s._sync
302
+ def write(raw,offset):writes.append((offset,bytes(raw)));return original_write(raw,offset)
303
+ def sync():boundaries.append(len(writes));return original_sync()
304
+ with mock.patch.object(s,'_prepare_checkpoint_plan',side_effect=AssertionError('must use admitted plan')):
305
+ with mock.patch.object(s,'_pwrite',write),mock.patch.object(s,'_sync',sync):s.checkpoint()
306
+ self.assertEqual(tuple(writes),plan['writes']);self.assertEqual(tuple(boundaries),plan['force_boundaries'])
307
+ self.assertEqual(sum(len(raw) for _,raw in writes),plan['bytes_written'])
308
+ def test_rejected_offer_drains_previous_certified_window(self):
309
+ with self.create(pool=32) as s:
310
+ s.transact({'/a':b'fits'},'ack');before=s.checkpoint_plan(include_writes=True)
311
+ with self.assertRaises(m.AdmissionRejected):s.transact({'/b':bytes(45000)},'reject')
312
+ self.assertEqual(s.get('/a'),b'fits');self.assertIsNone(s.query('reject'));s.checkpoint()
313
+ self.assertFalse(s.fenced)
314
+ def test_recovery_recompiles_exact_acked_tail(self):
315
+ with self.create() as s:s.transact({'/a':bytes(8000)},'ack')
316
+ with m.PageStore(self.path) as s:
317
+ self.assertEqual(s.checkpoint_plan()['epoch'],1);s.checkpoint()
318
+ self.assertEqual(s.get('/a'),bytes(8000));self.assertEqual(s.query('ack')['epoch'],1)
319
+ def test_readonly_plan_query_has_no_writes(self):
320
+ with self.create() as s:s.transact({'/a':b'x'},'ack')
321
+ before=self.path.read_bytes()
322
+ with m.PageStore(self.path,writable=False) as s:
323
+ self.assertEqual(s.checkpoint_plan()['epoch'],1);self.assertEqual(s.stats['write_calls'],0)
324
+ self.assertEqual(self.path.read_bytes(),before)
325
+ def test_caller_dictionary_changes_do_not_change_admitted_intent(self):
326
+ with self.create() as s:
327
+ request={'/a':b'original'};preview=s._reservation_preview
328
+ def changed(*args):request['/a']=b'changed-after-validation';return preview(*args)
329
+ with mock.patch.object(s,'_reservation_preview',changed):s.transact(request,'ack')
330
+ self.assertEqual(s.get('/a'),b'original');s.checkpoint();self.assertEqual(s.get('/a'),b'original')
331
+ def test_admitted_plan_holds_after_multiple_overwrites(self):
332
+ with self.create({'/a':b'initial'},pool=256) as s:
333
+ for i in range(40):
334
+ s.transact({'/a':bytes([i])*((i%5)*1000+10)},f'token-{i}')
335
+ self.assertEqual(s.checkpoint_plan()['epoch'],i+1)
336
+ s.checkpoint();self.assertEqual(s.get('/a'),bytes([39])*4010)
337
+ def test_fast_admissions_do_not_compile_pending_window(self):
338
+ with self.create({f'/f{i}':bytes(128) for i in range(200)},pool=1024) as s:
339
+ s.reset_stats()
340
+ with mock.patch.object(s,'_prepare_checkpoint_plan',side_effect=AssertionError('fast path recompiled')):
341
+ for i in range(64):s.transact({f'/f{i}':bytes([i])*128},f'fast-{i}')
342
+ summary=s.admission_reservation()
343
+ self.assertEqual(summary['certificate_kind'],'upper_bound')
344
+ self.assertTrue(summary['tail_certified']);self.assertEqual(s.stats['reservation_fast_accepts'],64)
345
+ self.assertEqual(s.stats['admission_plans'],0)
346
+ self.assertLessEqual(len(s._prepare_checkpoint_plan()['dependency_writes']),summary['reserved_upper_blocks'])
347
+ s.checkpoint()
348
+ def test_symbolic_bound_dominates_mixed_exact_plans(self):
349
+ import random
350
+ rng=random.Random(7047)
351
+ with self.create({f'/f{i}':rng.randbytes(128) for i in range(300)},pool=2048) as s:
352
+ for i in range(120):
353
+ changes={f'/f{rng.randrange(350)}':None if i%9==0 else rng.randbytes((0,128,256,257,3992,8000)[i%6])}
354
+ s.transact(changes,f'mixed-{i}')
355
+ if i%7==0:
356
+ bound=s.admission_reservation()['reserved_upper_blocks']
357
+ actual=len(s._prepare_checkpoint_plan()['dependency_writes'])
358
+ self.assertLessEqual(actual,bound)
359
+ if i%30==29:s.checkpoint()
360
+ def test_blob_credit_is_replaced_not_accumulated(self):
361
+ with self.create(pool=256) as s:
362
+ s.transact({'/a':bytes(30000)},'big');large=s.admission_reservation()['reserved_upper_blocks']
363
+ s.transact({'/a':b'small'},'small');small=s.admission_reservation()['reserved_upper_blocks']
364
+ self.assertGreater(large,small+10)
365
+ self.assertEqual(s._reservation_blob_pages['/a'],0);s.checkpoint()
366
+ def test_loose_bound_uses_exact_fallback_without_false_refusal(self):
367
+ initial={};used=set()
368
+ for i in range(1000):
369
+ key=f'/p{i:04d}/'+('x'*900);nib=m.hash_key(key)[0]
370
+ if nib not in used:initial[key]=bytes(256);used.add(nib)
371
+ if len(initial)==4:break
372
+ with self.create(initial,pool=16) as s:
373
+ self.assertEqual(len(s._free),4);key=next(iter(initial));s.reset_stats()
374
+ s.transact({key:initial[key]},'same')
375
+ self.assertEqual(s.stats['reservation_exact_fallbacks'],1)
376
+ self.assertEqual(s.admission_reservation()['certificate_kind'],'exact_plan')
377
+ self.assertGreater(s.admission_reservation()['reserved_upper_blocks'],len(s._free))
378
+ self.assertEqual(s.checkpoint_plan()['physical_blocks'],4);s.checkpoint()
379
+ def test_reservation_failure_does_not_adopt_proposal(self):
380
+ import copy
381
+ with self.create({'/a':b'old'},pool=256) as s:
382
+ s.transact({'/a':b'accepted'},'one');before=copy.deepcopy(s._reservation_cells)
383
+ bound=s._reservation_logical;s.reset_stats()
384
+ with mock.patch.object(m.PageStore,'_budget_update',side_effect=MemoryError('symbolic OOM')):
385
+ with self.assertRaises(MemoryError):s.transact({'/a':b'offer'},'two')
386
+ self.assertEqual(s._reservation_cells,before);self.assertEqual(s._reservation_logical,bound)
387
+ self.assertEqual(s.stats['write_calls'],0);self.assertIsNone(s.query('two'));self.assertFalse(s.fenced)
388
+ s.checkpoint()
389
+ def test_generation_exhaustion_rejects_fast_offer_without_io(self):
390
+ with self.create(pool=256) as s:
391
+ s.generation=m.MAX_U64;s.reset_stats()
392
+ with self.assertRaises(m.StoreError):s.transact({'/a':b'no'},'exhausted')
393
+ self.assertEqual(s.stats['write_calls'],0);self.assertEqual(s.epoch,0)
394
+ def test_bound_reconstructed_after_reopen(self):
395
+ with self.create({'/a':b'old'},pool=256) as s:
396
+ s.transact({'/a':bytes(9000),'/b':b'new'},'accepted')
397
+ bound=s.admission_reservation()['reserved_upper_blocks']
398
+ with m.PageStore(self.path) as s:
399
+ self.assertEqual(s.admission_reservation()['reserved_upper_blocks'],bound)
400
+ self.assertLessEqual(s.checkpoint_plan()['physical_blocks'],bound);s.checkpoint()
401
+ def test_format_maximum_reference_containers_fit(self):
402
+ self.assertLessEqual(len(m.canonical({'family':'tokens','type':'branch','depth':63,'children':{n:m.BOUND_DESC for n in m.HEX}})),m.PAGE_PAYLOAD)
403
+ self.assertLessEqual(len(m.canonical({'length':m.MAX_CAPSULE,'digest':'f'*64,'chunks':[m.BOUND_DESC]*17})),m.PAGE_PAYLOAD)
404
+ def test_weighted_budget_never_serializes_nonempty_symbolic_leaf(self):
405
+ real=m.canonical
406
+ def guarded(obj):
407
+ if isinstance(obj,dict) and obj.get('type')=='leaf' and obj.get('entries'):
408
+ raise AssertionError('whole symbolic leaf serialized')
409
+ return real(obj)
410
+ with self.create(pool=2048) as store:
411
+ with mock.patch.object(m,'canonical',side_effect=guarded), \
412
+ mock.patch.object(store,'_prepare_checkpoint_plan',side_effect=AssertionError('late exact plan')), \
413
+ mock.patch.object(store,'_reservation_count',side_effect=AssertionError('whole cell recounted')):
414
+ for i in range(32):
415
+ store.transact({f'/new/{i:03d}/{j}':bytes([i])*128 for j in range(8)},f'weighted-{i}')
416
+ bound=store.admission_reservation()['reserved_upper_blocks']
417
+ self.assertGreater(store.stats['reservation_leaf_splits'],0)
418
+ self.assertEqual(store.stats['reservation_fast_accepts'],32)
419
+ self.assertLessEqual(len(store._prepare_checkpoint_plan()['dependency_writes']),bound)
420
+ store.checkpoint()
421
+ def test_equal_size_replacement_reuses_file_budget_identity(self):
422
+ with self.create(pool=2048) as store:
423
+ store.transact({f'/item/{i:03d}':bytes(128) for i in range(40)},'seed')
424
+ anchor=store._reservation_route('files','/item/000')[0]
425
+ previous=store._reservation_cells[anchor]['tree']
426
+ store.transact({'/item/000':b'x'*128},'replace')
427
+ self.assertIs(store._reservation_cells[anchor]['tree'],previous)
428
+ store.checkpoint();self.assertEqual(store.get('/item/000'),b'x'*128)
429
+ def test_partial_weighted_proposal_failure_preserves_accepted_tree(self):
430
+ with self.create(pool=2048) as store:
431
+ store.transact({'/old':b'accepted'},'accepted')
432
+ before=dict(store._reservation_cells);budget=store._reservation_logical
433
+ calls=0;update=store._budget_update
434
+ def fail(family,node,key,weight,depth,hashed=None):
435
+ nonlocal calls
436
+ calls+=1
437
+ if calls==2:raise MemoryError('second weighted edit')
438
+ return update(family,node,key,weight,depth,hashed)
439
+ store.reset_stats()
440
+ with mock.patch.object(store,'_budget_update',side_effect=fail):
441
+ with self.assertRaises(MemoryError):store.transact({'/new/1':b'a','/new/2':b'b'},'refused')
442
+ self.assertEqual(store._reservation_cells,before);self.assertEqual(store._reservation_logical,budget)
443
+ self.assertEqual(store.stats['write_calls'],0);self.assertEqual(store.epoch,1)
444
+ self.assertIsNone(store.query('refused'));self.assertFalse(store.fenced)
445
+ store.checkpoint()
446
+ def test_weighted_leaf_byte_identity_for_escaped_published_values(self):
447
+ paths=('/plain','/quote\"/line\n','/雪/😀','/'+chr(1)*500)
448
+ with self.create(pool=1024) as store:
449
+ for depth in (0,9,10,63,64):
450
+ entries={path:{'inline':m.b64(bytes([i])*128)} for i,path in enumerate(paths)}
451
+ weights={key:store._budget_published_weight('files',key,value) for key,value in entries.items()}
452
+ predicted=store._budget_leaf_bytes('files',depth,weights,sum(weights.values()))
453
+ self.assertEqual(predicted,len(m.canonical({'family':'files','type':'leaf','depth':depth,'entries':entries})))
454
+ for epoch in (1,9,10,m.MAX_U64):
455
+ token='receipt_09';value=[epoch,'a'*64]
456
+ self.assertEqual(store._budget_published_weight('tokens',token,value),len(m.canonical(token))+1+len(m.canonical(value)))
457
+ desc=[0,m.MAX_POOL_BLOCKS-1,m.MAX_U64,m.K_BLOB,m.PAGE_PAYLOAD,'f'*64]
458
+ self.assertEqual(store._budget_published_weight('files',paths[2],{'blob':desc}),len(m.canonical(paths[2]))+1+len(m.canonical({'blob':desc})))
459
+ def test_published_entry_weights_are_computed_once_per_cell(self):
460
+ with self.create({'/same':bytes(128)},pool=512) as store:
461
+ store.transact({'/same':b'a'*128},'first')
462
+ with mock.patch.object(store,'_budget_published_weight',side_effect=AssertionError('published cell reweighted')):
463
+ for i in range(12):store.transact({'/same':bytes([i])*128},f'overwrite-{i}')
464
+ store.checkpoint()
465
+ if __name__=='__main__':unittest.main()
tests/test_reservation_review.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent weighted-reservation and fast-path review; finite evidence only."""
2
+ import copy
3
+ import random
4
+ from pathlib import Path
5
+ import tempfile
6
+ import unittest
7
+ from unittest import mock
8
+
9
+ import pagefs as fs
10
+
11
+
12
+ class ReservationReview(unittest.TestCase):
13
+ def setUp(self):
14
+ self.tmp = tempfile.TemporaryDirectory(prefix='nyarion-v7-bound-review-')
15
+ self.image = Path(self.tmp.name) / 'review.img'
16
+
17
+ def tearDown(self):
18
+ self.tmp.cleanup()
19
+
20
+ def create(self, files=None, pool=4096):
21
+ return fs.PageStore.create(self.image, initial_files=files, pool_blocks=pool)
22
+
23
+ def test_roomy_admission_does_not_compile_whole_pending_window(self):
24
+ with self.create({f'/old/{i:04d}': b'x' * 128 for i in range(192)}) as store:
25
+ store.reset_stats()
26
+ with mock.patch.object(store, '_prepare_checkpoint_plan', side_effect=AssertionError('whole-window recompile')):
27
+ for i in range(32):
28
+ store.transact({f'/old/{i:04d}': bytes([i]) * 129}, f'fast-{i}')
29
+ status = store.admission_reservation()
30
+ self.assertEqual(status['certificate_kind'], 'upper_bound')
31
+ self.assertTrue(status['tail_certified'])
32
+ self.assertLessEqual(status['reserved_upper_blocks'], status['free_blocks'])
33
+ self.assertEqual(store.stats['admission_plans'], 0)
34
+ self.assertEqual(store.stats['reservation_fast_accepts'], 32)
35
+ store.checkpoint()
36
+
37
+ def test_bound_dominates_pure_exact_oracle_at_every_ack(self):
38
+ values = (None, b'', b'i' * 256, b'b' * 257, b'c' * 3992,
39
+ bytes(range(256)) * 33, b'r' * 128)
40
+ initial = {f'/old/{i:04d}': bytes([i % 251]) * 128 for i in range(256)}
41
+ with self.create(initial) as store:
42
+ for i in range(60):
43
+ changes = {f'/old/{(i * 17) % 256:04d}': values[i % len(values)],
44
+ f'/new/{i % 11:03d}': values[(i + 3) % len(values)]}
45
+ store.transact(changes, f'oracle-{i}')
46
+ status = store.admission_reservation()
47
+ old_plan = store._checkpoint_plan
48
+ plan = store._prepare_checkpoint_plan()
49
+ self.assertIs(store._checkpoint_plan, old_plan)
50
+ self.assertLessEqual(len(plan['dependency_writes']), status['reserved_upper_blocks'])
51
+ self.assertTrue(status['tail_certified'])
52
+ store.checkpoint()
53
+ self.assertEqual(store.admission_reservation()['cells'], 0)
54
+ self.assertEqual(store.admission_reservation()['dirty_ancestors'], 0)
55
+
56
+ def test_only_affected_cell_objects_are_replaced(self):
57
+ initial = {f'/key/{i:04d}': b'p' * 128 for i in range(512)}
58
+ with self.create(initial) as store:
59
+ store.transact({'/key/0000': b'a'}, 'one')
60
+ before = dict(store._reservation_cells)
61
+ store.transact({'/key/0301': b'b'}, 'two')
62
+ anchor_f = store._reservation_route('files', '/key/0301')[0]
63
+ anchor_t = store._reservation_route('tokens', 'two')[0]
64
+ untouched = [key for key in before if key not in (anchor_f, anchor_t)]
65
+ self.assertTrue(untouched)
66
+ for key in untouched:
67
+ self.assertIs(store._reservation_cells[key], before[key])
68
+ store.checkpoint()
69
+
70
+ def test_global_descriptor_widths_and_fixed_records_fit(self):
71
+ d = fs.BOUND_DESC
72
+ self.assertGreaterEqual(len(fs.canonical(d)), len(fs.canonical([0, 1, 1, fs.K_BLOB, 1, '0' * 64])))
73
+ branch = {'family': 'tokens', 'type': 'branch', 'depth': 63,
74
+ 'children': {nib: d for nib in fs.HEX}}
75
+ chunks = (fs.MAX_CAPSULE + fs.PAGE_PAYLOAD - 1) // fs.PAGE_PAYLOAD
76
+ manifest = {'length': fs.MAX_CAPSULE, 'digest': 'f' * 64, 'chunks': [d] * chunks}
77
+ cat = {'format': fs.FORMAT, 'volume': 'f' * 32, 'epoch': fs.MAX_U64,
78
+ 'history': 'f' * 64, 'files_root': d, 'tokens_root': d}
79
+ long_key = '/' + chr(1) * ((fs.PAGE_PAYLOAD - 515) // 6)
80
+ self.assertEqual(fs.path_key(long_key), long_key)
81
+ leaf = {'family': 'files', 'type': 'leaf', 'depth': 64,
82
+ 'entries': {long_key: {'inline': fs.b64(b'x' * fs.INLINE_LIMIT)}}}
83
+ for obj in (branch, manifest, cat, leaf):
84
+ self.assertLessEqual(len(fs.canonical(obj)), fs.PAGE_PAYLOAD)
85
+
86
+ def test_last_generation_width_is_within_bound(self):
87
+ with self.create({'/old': b'old'}, pool=256) as store:
88
+ store.generation = fs.MAX_U64 - 1
89
+ store.transact({'/old': b'new' * 1000}, 'wide-generation')
90
+ plan = store._prepare_checkpoint_plan()
91
+ self.assertLessEqual(len(plan['dependency_writes']), store.admission_reservation()['reserved_upper_blocks'])
92
+ store.checkpoint()
93
+ with fs.PageStore(self.image, writable=False) as store:
94
+ self.assertEqual(store.generation, fs.MAX_U64)
95
+ self.assertEqual(store.get('/old'), b'new' * 1000)
96
+
97
+ def test_failed_proposal_preserves_accepted_cells_and_certificate(self):
98
+ with self.create(pool=256) as store:
99
+ store.transact({'/a': b'a' * 5000}, 'accepted')
100
+ status = store.admission_reservation()
101
+ committed = copy.deepcopy((store._reservation_cells, store._reservation_ancestors,
102
+ store._reservation_blob_pages, store._reservation_logical))
103
+ with mock.patch.object(store, '_budget_update', side_effect=MemoryError('weighted update')):
104
+ with mock.patch.object(store, '_pwrite', side_effect=AssertionError('uncertified write')):
105
+ with self.assertRaises(MemoryError):
106
+ store.transact({'/b': b'b' * 7000}, 'refused')
107
+ self.assertEqual((store._reservation_cells, store._reservation_ancestors,
108
+ store._reservation_blob_pages, store._reservation_logical), committed)
109
+ self.assertEqual(store.admission_reservation(), status)
110
+ self.assertIsNone(store.query('refused'))
111
+ self.assertFalse(store.fenced)
112
+ store.checkpoint()
113
+
114
+ def test_readonly_replay_reconstructs_same_upper_bound(self):
115
+ with self.create(pool=1024) as store:
116
+ for i in range(20):
117
+ store.transact({f'/key/{i % 7}': bytes([i]) * (257 + i)}, f'reopen-{i}')
118
+ before = store.admission_reservation()
119
+ self.assertEqual(before['certificate_kind'], 'upper_bound')
120
+ with fs.PageStore(self.image, writable=False) as store:
121
+ after = store.admission_reservation()
122
+ self.assertEqual(after['reserved_upper_blocks'], before['reserved_upper_blocks'])
123
+ self.assertEqual(after['cells'], before['cells'])
124
+ self.assertTrue(after['tail_certified'])
125
+ self.assertLessEqual(store.checkpoint_plan()['physical_blocks'], after['reserved_upper_blocks'])
126
+
127
+ def test_loose_bound_calls_exact_fallback_and_accepts_real_fit(self):
128
+ with self.create(pool=144) as store:
129
+ changes = {f'/blob/{i:02d}': b'x' * 257 for i in range(32)}
130
+ proposal = store._reservation_preview(changes, {'tight': [1, 'f' * 64]})
131
+ self.assertGreater(proposal['physical_blocks'], len(store._free))
132
+ self.assertEqual(store.transact(changes, 'tight'), 1)
133
+ status = store.admission_reservation()
134
+ self.assertEqual(status['certificate_kind'], 'exact_plan')
135
+ self.assertTrue(status['tail_certified'])
136
+ self.assertGreater(status['reserved_upper_blocks'], status['free_blocks'])
137
+ self.assertLessEqual(store.checkpoint_plan()['physical_blocks'], status['free_blocks'])
138
+ store.checkpoint()
139
+ with fs.PageStore(self.image, writable=False) as store:
140
+ for key, value in changes.items():
141
+ self.assertEqual(store.get(key), value)
142
+
143
+ def test_entry_weight_formulas_match_actual_json_for_all_value_families(self):
144
+ rng = random.Random(0x8018)
145
+ paths = ['/plain', '/quote"/line\n', '/emoji/\U0001f319', '/control/' + chr(1) * 70]
146
+ for i in range(180):
147
+ path = paths[i % len(paths)] + str(i)
148
+ inline = {'inline': fs.b64(rng.randbytes(i % 257))}
149
+ desc = [rng.randrange(fs.MAX_POOL_BLOCKS), rng.randrange(fs.MAX_POOL_BLOCKS),
150
+ (1, 9, 10, fs.MAX_U64)[i % 4], fs.K_BLOB,
151
+ (1, fs.PAGE_PAYLOAD)[i % 2], 'a' * 64]
152
+ for value in (inline, {'blob': desc}):
153
+ actual = len(fs.canonical(path)) + 1 + len(fs.canonical(value))
154
+ self.assertEqual(fs.PageStore._budget_published_weight('files', path, value), actual)
155
+ token = f'token:{i:060d}'
156
+ receipt = [(1, 9, 10, fs.MAX_U64)[i % 4], 'f' * 64]
157
+ actual = len(fs.canonical(token)) + 1 + len(fs.canonical(receipt))
158
+ self.assertEqual(fs.PageStore._budget_published_weight('tokens', token, receipt), actual)
159
+
160
+ def test_weighted_leaf_size_equals_complete_canonical_payload(self):
161
+ rng = random.Random(8029)
162
+ for family in ('files', 'tokens'):
163
+ entries = {}
164
+ for i in range(45):
165
+ key = f'/escaped"/{i:03d}/\U0001f319' if family == 'files' else f'receipt-{i:03d}'
166
+ value = {'inline': fs.b64(rng.randbytes(i % 257))} if family == 'files' else [10 ** (i % 18), 'a' * 64]
167
+ entries[key] = value
168
+ weights = {k: len(fs.canonical(k)) + 1 + len(fs.canonical(v)) for k, v in entries.items()}
169
+ for depth in (0, 9, 10, 63, 64):
170
+ raw = fs.canonical({'family': family, 'type': 'leaf', 'depth': depth, 'entries': entries})
171
+ self.assertEqual(fs.PageStore._budget_leaf_bytes(family, depth, weights, sum(weights.values())), len(raw))
172
+ self.assertEqual(fs.PageStore._budget_leaf_bytes(family, 0, {}, 0),
173
+ len(fs.canonical({'family': family, 'type': 'leaf', 'depth': 0, 'entries': {}})))
174
+
175
+ def test_admission_never_encodes_nonempty_leaf_after_weighted_cache_exists(self):
176
+ with self.create({f'/old/{i:04d}': b'p' * 128 for i in range(256)}) as store:
177
+ store.transact({'/old/0000': b'prime'}, 'prime')
178
+ # Initial on-demand decoding validates each published leaf once.
179
+ # The prohibition below targets repeated admission reconstruction.
180
+ for i in range(1, 24):
181
+ store._reservation_route('files', f'/old/{i:04d}')
182
+ original = fs.canonical
183
+
184
+ def forbid_full_leaf(obj):
185
+ if isinstance(obj, dict) and obj.get('type') == 'leaf' and obj.get('entries'):
186
+ raise AssertionError('admission serialized an entire nonempty leaf')
187
+ return original(obj)
188
+
189
+ with mock.patch.object(fs, 'canonical', side_effect=forbid_full_leaf):
190
+ with mock.patch.object(store, '_prepare_checkpoint_plan', side_effect=AssertionError('full plan')):
191
+ for i in range(1, 24):
192
+ store.transact({f'/old/{i:04d}': bytes([i]) * 128}, f'weighted-{i}')
193
+ store.checkpoint()
194
+
195
+ def test_retained_split_can_compact_on_restart_without_losing_feasibility(self):
196
+ entries = {f'/transient/{i:03d}': b'x' * 64 for i in range(80)}
197
+ with self.create(pool=512) as store:
198
+ store.transact(entries, 'many')
199
+ store.transact({key: None for key in entries if key != '/transient/000'}, 'shrink')
200
+ before = store.admission_reservation()
201
+ exact = store._prepare_checkpoint_plan()
202
+ self.assertLessEqual(len(exact['dependency_writes']), before['reserved_upper_blocks'])
203
+ self.assertTrue(before['tail_certified'])
204
+ with fs.PageStore(self.image, writable=False) as store:
205
+ after = store.admission_reservation()
206
+ self.assertLess(after['reserved_upper_blocks'], before['reserved_upper_blocks'])
207
+ self.assertTrue(after['tail_certified'])
208
+ self.assertEqual(store.files(), ['/transient/000'])
209
+ self.assertEqual(store.get('/transient/000'), b'x' * 64)
210
+ self.assertEqual(store.query('many')['epoch'], 1)
211
+ self.assertEqual(store.query('shrink')['epoch'], 2)
212
+ self.assertLessEqual(store.checkpoint_plan()['physical_blocks'], after['reserved_upper_blocks'])
213
+
214
+ def test_symbolic_overflow_at_full_hash_depth_forces_exact_fallback(self):
215
+ changes = {f'/blob/{i:02d}': b'x' * 257 for i in range(32)}
216
+ with self.create(pool=144) as store:
217
+ with mock.patch.object(fs, 'hash_key', return_value='0' * 64):
218
+ proposal = store._reservation_preview(changes, {'collision': [1, 'f' * 64]})
219
+ self.assertGreater(proposal['physical_blocks'], fs.MAX_POOL_BLOCKS)
220
+ self.assertEqual(store.transact(changes, 'collision'), 1)
221
+ self.assertEqual(store.admission_reservation()['certificate_kind'], 'exact_plan')
222
+ self.assertLessEqual(store.checkpoint_plan()['physical_blocks'], len(store._free))
223
+ store.checkpoint()
224
+ with fs.PageStore(self.image, writable=False) as store:
225
+ self.assertEqual(store.files(), sorted(changes))
226
+ for key, value in changes.items():
227
+ self.assertEqual(store.get(key), value)
228
+
229
+
230
+ if __name__ == '__main__':
231
+ unittest.main()
tests/test_review.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent admission/replay review for VIII; finite tests, not device qualification."""
2
+ import copy
3
+ import errno
4
+ import importlib.util
5
+ from pathlib import Path
6
+ import tempfile
7
+ import unittest
8
+ from unittest import mock
9
+
10
+ import pagefs as fs
11
+
12
+
13
+ def baseline():
14
+ path = Path(__file__).resolve().parents[1] / 'experiments/baselines/v5.py'
15
+ spec = importlib.util.spec_from_file_location('independent_baseline_v5', path)
16
+ module = importlib.util.module_from_spec(spec)
17
+ spec.loader.exec_module(module)
18
+ return module
19
+
20
+
21
+ class AdmissionReview(unittest.TestCase):
22
+ def setUp(self):
23
+ self.tmp = tempfile.TemporaryDirectory(prefix='nyarion-admission-review-')
24
+ self.image = Path(self.tmp.name) / 'review.img'
25
+
26
+ def tearDown(self):
27
+ self.tmp.cleanup()
28
+
29
+ def create(self, files=None, pool=256):
30
+ return fs.PageStore.create(self.image, initial_files=files, pool_blocks=pool)
31
+
32
+ def stable_state(self, store):
33
+ return copy.deepcopy({
34
+ 'epoch': store.epoch, 'history': store.history,
35
+ 'generation': store.generation, 'files': store._files,
36
+ 'tokens': store._tokens, 'free': store._free,
37
+ 'refs': store._refs, 'live': store._live_blocks,
38
+ 'owners': store._block_owner, 'pending': store._pending,
39
+ 'cache': store._cache, 'edges': store._graph_cache,
40
+ })
41
+
42
+ def test_legacy_acknowledged_but_undrainable_counterexample(self):
43
+ old = baseline()
44
+ data = bytes(range(256)) * 160
45
+ with old.PageStore.create(self.image, initial_files={'/key': b'base'}, pool_blocks=16) as store:
46
+ self.assertEqual(store.transact({'/key': data}, 'legacy-acked'), 1)
47
+ with self.assertRaises(OSError) as raised:
48
+ store.checkpoint()
49
+ self.assertEqual(raised.exception.errno, errno.ENOSPC)
50
+ with fs.PageStore(self.image, writable=False) as store:
51
+ self.assertEqual(store.get('/key'), data)
52
+ self.assertEqual(store.query('legacy-acked')['epoch'], 1)
53
+ with self.assertRaises(fs.AdmissionRejected):
54
+ fs.PageStore(self.image)
55
+
56
+ def test_refused_offer_does_not_write_capsule_or_fence(self):
57
+ with self.create({'/key': b'base'}, pool=16) as store:
58
+ state = self.stable_state(store)
59
+ writes = []
60
+ actual = store._pwrite
61
+
62
+ def record(raw, offset):
63
+ writes.append((offset, bytes(raw)))
64
+ return actual(raw, offset)
65
+
66
+ with mock.patch.object(store, '_pwrite', side_effect=record):
67
+ with self.assertRaises(fs.AdmissionRejected):
68
+ store.transact({'/key': bytes(range(256)) * 160}, 'refused')
69
+ self.assertEqual(writes, [])
70
+ self.assertEqual(self.stable_state(store), state)
71
+ self.assertFalse(store.fenced)
72
+ self.assertIsNone(store.query('refused'))
73
+ self.assertEqual(store.transact({'/key': b'small'}, 'accepted'), 1)
74
+ store.checkpoint()
75
+
76
+ def test_plan_is_pure_and_public_summary_is_detached(self):
77
+ with self.create({'/old': b'old'}) as store:
78
+ store.transact({'/new': b'x' * 8000, '/old': None}, 'offer')
79
+ state = self.stable_state(store)
80
+ with mock.patch.object(store, '_pwrite', side_effect=AssertionError('planning wrote')):
81
+ with mock.patch.object(store, '_sync', side_effect=AssertionError('planning forced')):
82
+ plan = store.checkpoint_plan(include_writes=True)
83
+ self.assertEqual(self.stable_state(store), state)
84
+ self.assertEqual(plan['epoch'], store.epoch)
85
+ self.assertEqual(plan['generation'], store.generation + 1)
86
+ self.assertEqual(plan['history'], store.history)
87
+ self.assertIsInstance(plan['writes'], tuple)
88
+ plan['epoch'] = 9001
89
+ self.assertEqual(store.checkpoint_plan()['epoch'], store.epoch)
90
+
91
+ def test_checkpoint_replays_exact_admitted_writes_and_forces(self):
92
+ with self.create({f'/old/{i}': bytes([i]) * 128 for i in range(40)}) as store:
93
+ store.transact({'/old/2': None, '/new': b'z' * 12000}, 'two-kinds')
94
+ plan = store.checkpoint_plan(include_writes=True)
95
+ writes = []
96
+ forces = []
97
+ actual_write, actual_sync = store._pwrite, store._sync
98
+
99
+ def write(raw, offset):
100
+ writes.append((offset, bytes(raw)))
101
+ return actual_write(raw, offset)
102
+
103
+ def sync():
104
+ forces.append(len(writes))
105
+ return actual_sync()
106
+
107
+ with mock.patch.object(store, '_pwrite', side_effect=write):
108
+ with mock.patch.object(store, '_sync', side_effect=sync):
109
+ with mock.patch.object(store, '_prepare_checkpoint_plan', side_effect=AssertionError('late replan')):
110
+ with mock.patch.object(store, '_alloc_object', side_effect=AssertionError('late allocation')):
111
+ store.checkpoint()
112
+ self.assertEqual(tuple(writes), plan['writes'])
113
+ self.assertEqual(tuple(forces), plan['force_boundaries'])
114
+ self.assertEqual(sum(off >= fs.POOL_START for off, _ in writes), plan['physical_blocks'])
115
+ self.assertEqual(sum(len(raw) for _, raw in writes), plan['bytes_written'])
116
+
117
+ def test_retry_needs_no_fresh_admission_or_io(self):
118
+ with self.create(pool=16) as store:
119
+ self.assertEqual(store.transact({'/key': b'original'}, 'same'), 1)
120
+ with mock.patch.object(store, '_prepare_checkpoint_plan', side_effect=AssertionError('retry replanned')):
121
+ with mock.patch.object(store, '_pwrite', side_effect=AssertionError('retry wrote')):
122
+ with mock.patch.object(store, '_sync', side_effect=AssertionError('retry forced')):
123
+ self.assertEqual(store.transact({'/key': b'original'}, 'same'), 1)
124
+ with self.assertRaises(fs.TransactionConflict):
125
+ store.transact({'/key': b'different'}, 'same')
126
+ store.checkpoint()
127
+
128
+ def test_repeated_overwrites_coalesce_but_all_receipts_survive(self):
129
+ with self.create() as store:
130
+ counts = []
131
+ for i in range(10):
132
+ store.transact({'/same': bytes([i]) * 3000}, f'repeat-{i}')
133
+ counts.append(store.checkpoint_plan()['physical_blocks'])
134
+ # One blob/data value is materialized, not the ten superseded values.
135
+ self.assertEqual(len(set(counts)), 1)
136
+ store.checkpoint()
137
+ with fs.PageStore(self.image, writable=False) as store:
138
+ self.assertEqual(store.get('/same'), bytes([9]) * 3000)
139
+ for i in range(10):
140
+ self.assertEqual(store.query(f'repeat-{i}')['epoch'], i + 1)
141
+
142
+ def test_long_escaped_key_and_large_blob_are_prevalidated(self):
143
+ key = '/' + '\u03b1' * 500
144
+ with self.create(pool=512) as store:
145
+ store.transact({key: bytes(range(256)) * 117}, 'large-key-value')
146
+ self.assertGreater(store.checkpoint_plan()['physical_blocks'], 4)
147
+ store.checkpoint()
148
+ with fs.PageStore(self.image, writable=False) as store:
149
+ self.assertEqual(store.get(key), bytes(range(256)) * 117)
150
+
151
+ def test_planning_memory_failure_is_before_capsule_and_preserves_old_plan(self):
152
+ with self.create() as store:
153
+ store.transact({'/one': b'one'}, 'one')
154
+ first = store.checkpoint_plan(include_writes=True)
155
+ state = self.stable_state(store)
156
+ with mock.patch.object(store, '_reservation_preview', side_effect=MemoryError('reservation proposal')):
157
+ with mock.patch.object(store, '_pwrite', side_effect=AssertionError('unadmitted write')):
158
+ with self.assertRaises(MemoryError):
159
+ store.transact({'/two': b'two'}, 'two')
160
+ self.assertFalse(store.fenced)
161
+ self.assertEqual(self.stable_state(store), state)
162
+ self.assertEqual(store.checkpoint_plan(include_writes=True), first)
163
+ store.checkpoint()
164
+
165
+ def test_failed_dependency_force_preserves_ack_and_rebuilds_plan(self):
166
+ with self.create({'/key': b'old'}) as store:
167
+ store.transact({'/key': b'new', '/blob': b'x' * 6000}, 'acked')
168
+ old_blocks = {index: self._read_block(index) for index in store._live_blocks}
169
+ with mock.patch.object(store, '_sync', side_effect=OSError('dependency force')):
170
+ with self.assertRaises(OSError):
171
+ store.checkpoint()
172
+ self.assertTrue(store.fenced)
173
+ for index, data in old_blocks.items():
174
+ self.assertEqual(self._read_block(index), data)
175
+ with fs.PageStore(self.image) as store:
176
+ self.assertEqual(store.get('/key'), b'new')
177
+ self.assertEqual(store.query('acked')['epoch'], 1)
178
+ self.assertEqual(store.checkpoint_plan()['epoch'], 1)
179
+ store.checkpoint()
180
+
181
+ def _read_block(self, index):
182
+ with self.image.open('rb') as stream:
183
+ stream.seek(fs.block_offset(index))
184
+ return stream.read(fs.BLOCK_SIZE)
185
+
186
+ def test_failed_publication_force_still_recovers_acked_logical_state(self):
187
+ with self.create({'/key': b'old'}) as store:
188
+ store.transact({'/key': b'new'}, 'acked')
189
+ actual = store._sync
190
+ calls = 0
191
+
192
+ def sync():
193
+ nonlocal calls
194
+ calls += 1
195
+ if calls == 2:
196
+ raise OSError('publication force')
197
+ return actual()
198
+
199
+ with mock.patch.object(store, '_sync', side_effect=sync):
200
+ with self.assertRaises(OSError):
201
+ store.checkpoint()
202
+ self.assertTrue(store.fenced)
203
+ with fs.PageStore(self.image, minimum_epoch=1) as store:
204
+ self.assertEqual(store.get('/key'), b'new')
205
+ self.assertEqual(store.query('acked')['epoch'], 1)
206
+ store.checkpoint()
207
+
208
+ def test_reopen_acknowledged_window_has_executable_drain_plan(self):
209
+ with self.create(pool=128) as store:
210
+ for i in range(20):
211
+ store.transact({f'/key/{i}': bytes([i]) * 128}, f'ack-{i}')
212
+ with fs.PageStore(self.image) as store:
213
+ self.assertEqual(store.checkpoint_plan()['epoch'], 20)
214
+ with mock.patch.object(store, '_prepare_checkpoint_plan', side_effect=AssertionError('late plan')):
215
+ store.checkpoint()
216
+ with fs.PageStore(self.image, writable=False) as store:
217
+ for i in range(20):
218
+ self.assertEqual(store.get(f'/key/{i}'), bytes([i]) * 128)
219
+ self.assertEqual(store.query(f'ack-{i}')['epoch'], i + 1)
220
+
221
+ def test_plan_is_byte_identical_after_replay_of_unsorted_input_and_coalescing(self):
222
+ with self.create(pool=512) as store:
223
+ store.transact({'/z': b'z' * 7000, '/a': b'a' * 8000, '/m': b'm' * 6000}, 'reverse-input')
224
+ store.transact({'/n': b'n' * 5000, '/a': b'final-a' * 1000, '/z': None}, 'coalesced')
225
+ before = store.checkpoint_plan(include_writes=True)
226
+ with fs.PageStore(self.image) as store:
227
+ after = store.checkpoint_plan(include_writes=True)
228
+ self.assertEqual(after, before)
229
+ store.checkpoint()
230
+
231
+ def test_window_pressure_executes_prior_admitted_plan_before_capsule_reuse(self):
232
+ with self.create(pool=512) as store:
233
+ for i in range(fs.SLOTS):
234
+ store.transact({'/same': bytes([i]) * 128}, f'window-{i}')
235
+ admitted = store.checkpoint_plan(include_writes=True)
236
+ writes = []
237
+ actual = store._pwrite
238
+
239
+ def record(raw, offset):
240
+ writes.append((offset, bytes(raw)))
241
+ return actual(raw, offset)
242
+
243
+ with mock.patch.object(store, '_pwrite', side_effect=record):
244
+ self.assertEqual(store.transact({'/next': b'next'}, 'next-window'), fs.SLOTS + 1)
245
+ self.assertEqual(tuple(writes[:len(admitted['writes'])]), admitted['writes'])
246
+ capsule_writes = writes[len(admitted['writes']):]
247
+ self.assertEqual([off for off, _ in capsule_writes],
248
+ [fs.capsule_offset(fs.SLOTS + 1, r) for r in range(2)])
249
+ self.assertEqual(store.checkpoint_epoch, fs.SLOTS)
250
+ store.checkpoint()
251
+
252
+ def test_host_enospc_remains_an_io_failure_not_an_arena_promise(self):
253
+ with self.create() as store:
254
+ store.transact({'/acked': b'yes'}, 'ack')
255
+ self.assertGreater(store.checkpoint_plan()['physical_blocks'], 0)
256
+ with mock.patch.object(store, '_pwrite', side_effect=OSError(errno.ENOSPC, 'host backing space')):
257
+ with self.assertRaises(OSError) as raised:
258
+ store.checkpoint()
259
+ self.assertEqual(raised.exception.errno, errno.ENOSPC)
260
+ self.assertNotIsInstance(raised.exception, fs.AdmissionRejected)
261
+ self.assertTrue(store.fenced)
262
+ with fs.PageStore(self.image) as store:
263
+ self.assertEqual(store.get('/acked'), b'yes')
264
+ self.assertEqual(store.query('ack')['epoch'], 1)
265
+ store.checkpoint()
266
+
267
+ def test_partial_capsule_write_fences_and_recovery_still_has_feasible_plan(self):
268
+ with self.create() as store:
269
+ actual = store._pwrite
270
+ calls = 0
271
+
272
+ def write(raw, offset):
273
+ nonlocal calls
274
+ calls += 1
275
+ if calls == 2:
276
+ raise OSError('second capsule mirror')
277
+ return actual(raw, offset)
278
+
279
+ with mock.patch.object(store, '_pwrite', side_effect=write):
280
+ with self.assertRaises(OSError):
281
+ store.transact({'/uncertain': b'complete bytes'}, 'uncertain')
282
+ self.assertTrue(store.fenced)
283
+ with fs.PageStore(self.image) as store:
284
+ # The complete first capsule may persist although no response returned.
285
+ self.assertEqual(store.get('/uncertain'), b'complete bytes')
286
+ self.assertEqual(store.checkpoint_plan()['epoch'], 1)
287
+ store.checkpoint()
288
+
289
+ def test_rejected_offer_may_checkpoint_old_tail_but_never_adds_its_epoch(self):
290
+ with self.create(pool=16) as store:
291
+ store.transact({'/key': b'old-acked'}, 'old-ack')
292
+ old_epoch, old_history = store.epoch, store.history
293
+ with self.assertRaises(fs.AdmissionRejected):
294
+ store.transact({'/key': bytes(range(256)) * 160}, 'refused-large')
295
+ self.assertEqual(store.epoch, old_epoch)
296
+ self.assertEqual(store.history, old_history)
297
+ self.assertEqual(store.checkpoint_epoch, old_epoch)
298
+ self.assertEqual(store.get('/key'), b'old-acked')
299
+ self.assertEqual(store.query('old-ack')['epoch'], old_epoch)
300
+ self.assertIsNone(store.query('refused-large'))
301
+ self.assertFalse(store.fenced)
302
+
303
+
304
+ if __name__ == '__main__':
305
+ unittest.main()
verify_crash_images.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Crash images from the current engine's checkpoint write trace.
3
+
4
+ This is finite sector fault injection, not exhaustive hardware verification.
5
+ All operations before the trace are acknowledged. During the checkpoint,
6
+ forced writes must survive; pending sectors may be old, new, or erased.
7
+ """
8
+ from __future__ import annotations
9
+ import argparse
10
+ import hashlib
11
+ import importlib
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import random
16
+ import sys
17
+ import tempfile
18
+
19
+ SECTOR = 512
20
+
21
+
22
+ def main():
23
+ p = argparse.ArgumentParser()
24
+ p.add_argument('--module', default='pagefs')
25
+ p.add_argument('--random-patterns', type=int, default=3)
26
+ p.add_argument('--output', default='crash_image_results.json')
27
+ args = p.parse_args()
28
+ mod = importlib.import_module(args.module)
29
+ source = Path(mod.__file__)
30
+ source_hash = hashlib.sha256(source.read_bytes()).hexdigest()
31
+ rng = random.Random(0x5C0A5)
32
+
33
+ class Recorder(mod.CutStore):
34
+ def __init__(self, *a, **kw):
35
+ self.events = []
36
+ super().__init__(*a, **kw)
37
+
38
+ def _pwrite(self, data, offset):
39
+ self.events.append(('write', offset, bytes(data)))
40
+ return super()._pwrite(data, offset)
41
+
42
+ def _sync(self):
43
+ answer = super()._sync()
44
+ self.events.append(('force',))
45
+ return answer
46
+
47
+ checks = 0
48
+ failure_examples = []
49
+ with tempfile.TemporaryDirectory(prefix='nyarion-v7-crash-') as tmp:
50
+ path = Path(tmp) / 'source.img'
51
+ candidate = Path(tmp) / 'crash.img'
52
+ expected = {f'/cold/{i:04d}': bytes([i % 251]) * 96 for i in range(192)}
53
+ tokens = {}
54
+ with mod.CutStore.create(path, initial_files=expected, pool_blocks=2048) as s:
55
+ # Multiple generations ensure the final trace reuses retired space.
56
+ for round_id in range(3):
57
+ for i in range(20):
58
+ key = f'/cold/{(round_id * 17 + i) % 192:04d}'
59
+ value = bytes([(i + round_id + 1) % 251]) * (3000 if i == 0 else 96)
60
+ token = f'prior-{round_id}-{i}'
61
+ epoch = s.transact({key: value}, token)
62
+ expected[key] = value
63
+ tokens[token] = epoch
64
+ s.checkpoint()
65
+ for i in range(12):
66
+ key = f'/cold/{i:04d}'
67
+ value = bytes([213 - i]) * (4096 if i == 0 else 96)
68
+ token = f'ack-{i}'
69
+ tokens[token] = s.transact({key: value}, token)
70
+ expected[key] = value
71
+ with Recorder(path) as s:
72
+ baseline = path.read_bytes()
73
+ s.events.clear()
74
+ s.checkpoint()
75
+ events = list(s.events)
76
+ expected_epoch = s.epoch
77
+
78
+ candidate.write_bytes(baseline)
79
+ fd = os.open(candidate, os.O_RDWR)
80
+ all_offsets = set()
81
+ for event in events:
82
+ if event[0] == 'write':
83
+ off, raw = event[1:]
84
+ if off % SECTOR or len(raw) % SECTOR:
85
+ raise AssertionError('trace expects sector-aligned page/seal writes')
86
+ all_offsets.update(range(off, off + len(raw), SECTOR))
87
+
88
+ def validate(patches, label):
89
+ nonlocal checks
90
+ for off in all_offsets:
91
+ raw = patches.get(off, baseline[off:off + SECTOR])
92
+ if os.pwrite(fd, raw, off) != len(raw):
93
+ raise OSError('short fault-image write')
94
+ os.fsync(fd)
95
+ try:
96
+ with mod.CutStore(candidate, writable=False) as recovered:
97
+ assert recovered.epoch == expected_epoch
98
+ assert recovered.files() == sorted(expected)
99
+ for key, value in expected.items():
100
+ assert recovered.get(key) == value, key
101
+ for token, epoch in tokens.items():
102
+ assert recovered.query(token)['epoch'] == epoch, token
103
+ except Exception as exc:
104
+ failure_examples.append({'case': label, 'error': repr(exc)})
105
+ raise AssertionError(f'acknowledged checkpoint state not recovered: {label}') from exc
106
+ checks += 1
107
+
108
+ try:
109
+ durable = {}
110
+ pending = []
111
+ for prefix in range(len(events) + 1):
112
+ if prefix:
113
+ event = events[prefix - 1]
114
+ if event[0] == 'force':
115
+ for off, raw in pending:
116
+ durable[off] = raw
117
+ pending.clear()
118
+ else:
119
+ off, raw = event[1:]
120
+ pending.extend((at, raw[at - off:at - off + SECTOR])
121
+ for at in range(off, off + len(raw), SECTOR))
122
+ validate(dict(durable), f'{prefix}:pending-none')
123
+ full = dict(durable)
124
+ full.update(pending)
125
+ validate(full, f'{prefix}:pending-all')
126
+ if pending:
127
+ half = dict(durable)
128
+ half.update(pending[:len(pending) // 2])
129
+ validate(half, f'{prefix}:sector-prefix')
130
+ for sample in range(args.random_patterns):
131
+ mixed = dict(durable)
132
+ for off, raw in pending:
133
+ state = rng.randrange(3)
134
+ if state == 1:
135
+ mixed[off] = raw
136
+ elif state == 2:
137
+ mixed[off] = bytes(SECTOR)
138
+ validate(mixed, f'{prefix}:mixed-{sample}')
139
+ # One detectable sector erasure after complete durable publication.
140
+ final = dict(durable)
141
+ final.update(pending)
142
+ for off in sorted(all_offsets):
143
+ erased = dict(final)
144
+ erased[off] = bytes(SECTOR)
145
+ validate(erased, f'published:erase-{off}')
146
+ finally:
147
+ os.close(fd)
148
+
149
+ if hashlib.sha256(source.read_bytes()).hexdigest() != source_hash:
150
+ raise RuntimeError('engine changed during fault validation; rerun against frozen source')
151
+ result = {'passed': True, 'engine_source_sha256': source_hash,
152
+ 'trace_events': len(events), 'trace_writes': sum(e[0] == 'write' for e in events),
153
+ 'trace_forces': sum(e[0] == 'force' for e in events),
154
+ 'distinct_written_sectors': len(all_offsets), 'recovery_checks': checks,
155
+ 'random_patterns_per_pending_prefix': args.random_patterns,
156
+ 'fault_scope': 'all trace prefixes; pending none/all/prefix/seeded mixed old-new-erased sectors; one erased written sector after publication',
157
+ 'logical_scope': '192 initial files; 72 acknowledged mutations; 4KiB value; 60 prior retry tokens; three prior checkpoints',
158
+ 'exhaustive_hardware_claim': False, 'failures': failure_examples}
159
+ Path(args.output).write_text(json.dumps(result, indent=2) + '\n')
160
+ print(json.dumps(result, indent=2))
161
+
162
+
163
+ if __name__ == '__main__':
164
+ main()
verify_reuse_model.py ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Finite physical-page reuse model for a mirrored COW tree.
3
+
4
+ This is independent of the image engine. Each dependency page or seal is one
5
+ logical fault unit. Pending writes may independently remain old, become new,
6
+ or become invalid on crash. One additional unit erasure is permitted in the
7
+ f=1 suites. Successful force operations are truthful. The latest protected
8
+ root and reader pins retain all replica addresses; lower-generation seal roots
9
+ may deliberately become unreadable after safe reuse. Recovery elects the
10
+ maximum complete valid seal BEFORE resolving its graph and never falls back.
11
+
12
+ The model checks finite uninterrupted publication traces plus one targeted
13
+ partial-publication/restart/normalization trace. It is not a byte-level engine
14
+ proof, physical power-cut test, full restart-tree proof, or hardware guarantee.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ from dataclasses import dataclass, field
20
+ from functools import lru_cache
21
+ import hashlib
22
+ import itertools
23
+ import json
24
+ from pathlib import Path
25
+
26
+
27
+ BAD = b'invalid-torn-logical-page'
28
+ VOLUME = 'nyarion-finite-physical-reuse'
29
+
30
+
31
+ def packed(obj):
32
+ return json.dumps(obj, sort_keys=True, separators=(',', ':')).encode('ascii')
33
+
34
+
35
+ @lru_cache(maxsize=None)
36
+ def digest(raw):
37
+ return hashlib.sha256(raw).hexdigest()
38
+
39
+
40
+ def encode(body):
41
+ return packed({'body':body, 'checksum':digest(packed(body))})
42
+
43
+
44
+ @lru_cache(maxsize=None)
45
+ def decode(raw):
46
+ try:
47
+ obj = json.loads(raw)
48
+ body = obj['body']
49
+ if digest(packed(body)) != obj['checksum']:
50
+ return None
51
+ return body
52
+ except (TypeError, ValueError, KeyError, UnicodeError):
53
+ return None
54
+
55
+
56
+ class RecoveryBlocked(Exception):
57
+ pass
58
+
59
+
60
+ class NoSpace(Exception):
61
+ pass
62
+
63
+
64
+ class WriterFenced(Exception):
65
+ pass
66
+
67
+
68
+ def page_key(index):
69
+ return f'page:{index}'
70
+
71
+
72
+ def read_pair(media, descriptor, erased=frozenset()):
73
+ if not isinstance(descriptor, (tuple,list)) or len(descriptor) != 3:
74
+ raise RecoveryBlocked('bad pair descriptor')
75
+ first, second, expected = descriptor
76
+ if first == second:
77
+ raise RecoveryBlocked('replicas alias')
78
+ for address in (first,second):
79
+ raw = None if address in erased else media.get(address)
80
+ if raw is not None and digest(raw) == expected:
81
+ body = decode(raw)
82
+ if body is not None:
83
+ return body
84
+ raise RecoveryBlocked('no valid page replica')
85
+
86
+
87
+ def read_tree(media, root, erased=frozenset()):
88
+ body = read_pair(media,root,erased)
89
+ if set(body) != {'kind','epoch','children'} or body['kind'] != 'root' or len(body['children']) != 2:
90
+ raise RecoveryBlocked('invalid root')
91
+ values = {}
92
+ for key,descriptor in zip(('/left','/right'),body['children']):
93
+ leaf = read_pair(media,descriptor,erased)
94
+ if set(leaf) != {'kind','epoch','key','value'} or leaf['kind'] != 'leaf' or leaf['key'] != key:
95
+ raise RecoveryBlocked('invalid leaf')
96
+ values[key] = leaf['value']
97
+ return body['epoch'],values
98
+
99
+
100
+ def reachable(media, root):
101
+ """Return BOTH replica addresses of every reachable immutable object."""
102
+ body = read_pair(media,root)
103
+ if body.get('kind') != 'root':
104
+ raise RecoveryBlocked('root kind')
105
+ result = set(root[:2])
106
+ for descriptor in body['children']:
107
+ read_pair(media,descriptor)
108
+ result.update(descriptor[:2])
109
+ return result
110
+
111
+
112
+ def valid_seals(media, erased=frozenset()):
113
+ seals = []
114
+ for slot in range(4):
115
+ key = f'seal:{slot}'
116
+ body = decode(None if key in erased else media.get(key))
117
+ if body is None:
118
+ continue
119
+ if set(body) != {'volume','generation','root'} or body['volume'] != VOLUME:
120
+ raise RecoveryBlocked('seal identity')
121
+ seals.append((slot,body))
122
+ return seals
123
+
124
+
125
+ def select_seal(media, erased=frozenset()):
126
+ seals = valid_seals(media,erased)
127
+ if not seals:
128
+ raise RecoveryBlocked('no valid seal')
129
+ generation = max(body['generation'] for _,body in seals)
130
+ latest = [body for _,body in seals if body['generation'] == generation]
131
+ if len({packed(body) for body in latest}) != 1:
132
+ raise RecoveryBlocked('same-generation conflict')
133
+ return latest[0]
134
+
135
+
136
+ def recover(media, erased=frozenset()):
137
+ selected = select_seal(media,erased)
138
+ epoch,values = read_tree(media,selected['root'],erased)
139
+ if epoch != selected['generation']:
140
+ raise RecoveryBlocked('root generation mismatch')
141
+ return epoch,values
142
+
143
+
144
+ def seal_bytes(epoch, root):
145
+ return encode({'volume':VOLUME,'generation':epoch,'root':root})
146
+
147
+
148
+ @dataclass
149
+ class Disk:
150
+ stable: dict = field(default_factory=dict)
151
+ pending: dict = field(default_factory=dict)
152
+
153
+ def write(self,key,raw):
154
+ self.pending[key] = raw
155
+
156
+ def force(self):
157
+ self.stable.update(self.pending)
158
+ self.pending.clear()
159
+
160
+ def images(self):
161
+ items = tuple(self.pending.items())
162
+ for choices in itertools.product((0,1,2),repeat=len(items)):
163
+ image = dict(self.stable)
164
+ for (key,raw),choice in zip(items,choices):
165
+ if choice == 1:
166
+ image[key] = raw
167
+ elif choice == 2:
168
+ image[key] = BAD
169
+ yield image
170
+
171
+
172
+ class Engine:
173
+ def __init__(self,pool_pages=20):
174
+ self.pool_pages = pool_pages
175
+ self.disk = Disk()
176
+ self.current = None
177
+ self.epoch = self.acked = 0
178
+ self.pins = {}
179
+ self.reserved = set()
180
+ self.ever_allocated = set()
181
+ self.physical_page_reuses = 0
182
+ self.allocation_checks = 0
183
+ self.fenced = False
184
+ self.expected = {0:{'/left':'left-0','/right':'right-0'}}
185
+ root,writes = self.prepare(0,self.expected[0])
186
+ for key,raw in writes:
187
+ self.disk.write(key,raw)
188
+ self.disk.force()
189
+ self.current = root
190
+ self.reserved.clear()
191
+ raw = seal_bytes(0,root)
192
+ for slot in range(4):
193
+ self.disk.write(f'seal:{slot}',raw)
194
+ self.disk.force()
195
+
196
+ def protected(self):
197
+ roots = ([self.current] if self.current is not None else []) + [item[0] for item in self.pins.values()]
198
+ result = set()
199
+ for root in roots:
200
+ result.update(reachable(self.disk.stable,root))
201
+ return result
202
+
203
+ def allocate_pair(self):
204
+ protected = self.protected()
205
+ free = [page_key(i) for i in range(self.pool_pages)
206
+ if page_key(i) not in protected and page_key(i) not in self.reserved]
207
+ if len(free) < 2:
208
+ raise NoSpace('no safe pair outside current graph, pins and reservations')
209
+ places = free[:2]
210
+ assert not (set(places) & protected)
211
+ assert not (set(places) & self.reserved)
212
+ self.allocation_checks += 1
213
+ self.physical_page_reuses += sum(key in self.ever_allocated for key in places)
214
+ self.ever_allocated.update(places)
215
+ self.reserved.update(places)
216
+ return places
217
+
218
+ def prepare(self,epoch,values):
219
+ before = set(self.reserved)
220
+ try:
221
+ previous = read_pair(self.disk.stable,self.current) if self.current is not None else None
222
+ writes,children = [],[]
223
+ for index,key in enumerate(('/left','/right')):
224
+ old = previous['children'][index] if previous else None
225
+ if old is not None and read_pair(self.disk.stable,old)['value'] == values[key]:
226
+ children.append(old)
227
+ continue
228
+ places = self.allocate_pair()
229
+ raw = encode({'kind':'leaf','epoch':epoch,'key':key,'value':values[key]})
230
+ children.append(places+[digest(raw)])
231
+ writes.extend((place,raw) for place in places)
232
+ places = self.allocate_pair()
233
+ raw = encode({'kind':'root','epoch':epoch,'children':children})
234
+ writes.extend((place,raw) for place in places)
235
+ return places+[digest(raw)],writes
236
+ except BaseException:
237
+ # No writes have been submitted by prepare. Roll back its volatile
238
+ # reservations; the main publisher stops before touching media.
239
+ self.reserved = before
240
+ raise
241
+
242
+ def pin(self,name):
243
+ self.pins[name] = (self.current,dict(self.expected[self.epoch]))
244
+
245
+ def unpin(self,name):
246
+ del self.pins[name]
247
+
248
+ def commit(self,values):
249
+ if self.fenced:
250
+ raise WriterFenced('uncertain writer must be drained and recovered')
251
+ epoch = self.epoch+1
252
+ root,writes = self.prepare(epoch,values)
253
+ self.expected[epoch] = dict(values)
254
+ # Candidate pages remain reserved for the entire publication attempt.
255
+ for address,raw in writes:
256
+ assert address not in self.protected()
257
+ self.disk.write(address,raw)
258
+ yield 'dependency-write'
259
+ self.disk.force()
260
+ yield 'dependency-force'
261
+ raw = seal_bytes(epoch,root)
262
+ bank = epoch % 2
263
+ for slot in range(2*bank,2*bank+2):
264
+ self.disk.write(f'seal:{slot}',raw)
265
+ yield 'inactive-bank-seal-write'
266
+ self.disk.force()
267
+ yield 'seal-force-before-retirement'
268
+ # Only now may the old selected graph become reusable. Pins can still
269
+ # retain it. No write is issued at this logical retirement point.
270
+ self.current,self.epoch,self.acked = root,epoch,epoch
271
+ self.reserved.clear()
272
+ yield 'acknowledged-and-old-root-retired'
273
+
274
+
275
+ def erasures(media,fault_budget):
276
+ yield frozenset()
277
+ if fault_budget:
278
+ for key in sorted(media):
279
+ yield frozenset({key})
280
+
281
+
282
+ def _stale_root_unavailable(media):
283
+ latest = select_seal(media)['generation']
284
+ for _,body in valid_seals(media):
285
+ if body['generation'] < latest:
286
+ try:
287
+ read_tree(media,body['root'])
288
+ except RecoveryBlocked:
289
+ return True
290
+ return False
291
+
292
+
293
+ def verify_trace(name,fault_budget,pool_pages=20):
294
+ engine = Engine(pool_pages)
295
+ if name == 'dirty_paths_with_pin':
296
+ targets = [
297
+ {'/left':'left-1','/right':'right-0'},
298
+ {'/left':'left-1','/right':'right-2'},
299
+ {'/left':'left-3','/right':'right-2'},
300
+ {'/left':'left-3','/right':'right-4'},
301
+ {'/left':'left-5','/right':'right-4'},
302
+ ]
303
+ else:
304
+ targets = [{'/left':f'left-{e}','/right':f'right-{e}'} for e in range(1,4)]
305
+ count = {'scenario':name,'fault_budget':fault_budget,'pool_pages':pool_pages,
306
+ 'commits':len(targets),'program_checkpoints':0,'crash_images':0,
307
+ 'crash_erasure_checks':0,'pinned_reader_checks':0,
308
+ 'checkpoint_images_with_unreadable_stale_root':0}
309
+ for number,target in enumerate(targets,1):
310
+ if name == 'dirty_paths_with_pin' and number == 2:
311
+ engine.pin('reader-epoch-1')
312
+ if name == 'dirty_paths_with_pin' and number == 4:
313
+ engine.unpin('reader-epoch-1')
314
+ for phase in engine.commit(target):
315
+ count['program_checkpoints'] += 1
316
+ for media in engine.disk.images():
317
+ count['crash_images'] += 1
318
+ if _stale_root_unavailable(media):
319
+ count['checkpoint_images_with_unreadable_stale_root'] += 1
320
+ for erased in erasures(media,fault_budget):
321
+ restored_epoch,restored = recover(media,erased)
322
+ assert engine.acked <= restored_epoch <= number, (name,phase,erased,'lost acknowledged epoch')
323
+ assert restored == engine.expected[restored_epoch], (name,phase,erased,'mixed state')
324
+ count['crash_erasure_checks'] += 1
325
+ for root,expected in engine.pins.values():
326
+ _,seen = read_tree(media,root,erased)
327
+ assert seen == expected, (name,phase,erased,'pinned reader destroyed')
328
+ count['pinned_reader_checks'] += 1
329
+ count['physical_page_reuses'] = engine.physical_page_reuses
330
+ count['pair_allocation_disjointness_checks'] = engine.allocation_checks
331
+ assert count['physical_page_reuses'] > 0
332
+ assert count['checkpoint_images_with_unreadable_stale_root'] > 0
333
+ return count
334
+
335
+
336
+ def expect_blocked(callable_):
337
+ try:
338
+ callable_()
339
+ except RecoveryBlocked:
340
+ return
341
+ raise AssertionError('expected explicit recovery failure')
342
+
343
+
344
+ def counterexamples():
345
+ examples = {}
346
+ engine = Engine()
347
+ old = engine.current
348
+ target = {'/left':'left-1','/right':'right-0'}
349
+ candidate,writes = engine.prepare(1,target)
350
+ media = dict(engine.disk.stable)
351
+ for address,raw in writes:
352
+ media[address] = raw
353
+ # Only one successor seal persists, then old current-root pages are reused.
354
+ media['seal:2'] = seal_bytes(1,candidate)
355
+ for address in old[:2]:
356
+ media[address] = BAD
357
+ expect_blocked(lambda:recover(media,frozenset({'seal:2'})))
358
+ examples['premature_old_root_reuse'] = 'reuse current root after one new seal, then erase that seal: last acknowledged root cannot be read'
359
+
360
+ engine = Engine()
361
+ candidate,writes = engine.prepare(1,target)
362
+ media = dict(engine.disk.stable)
363
+ media['seal:2'] = seal_bytes(1,candidate)
364
+ expect_blocked(lambda:recover(media))
365
+ examples['missing_dependency_force'] = 'a complete higher-generation seal can name missing root/leaf pages'
366
+
367
+ engine = Engine()
368
+ candidate,writes = engine.prepare(1,target)
369
+ media = dict(engine.disk.stable)
370
+ media.update(writes)
371
+ media['seal:2'] = seal_bytes(1,candidate)
372
+ assert recover(media,frozenset({'seal:2'}))[0] == 0
373
+ examples['premature_single_seal_ack'] = 'ack=1 after one successor witness; one erasure recovers epoch0'
374
+
375
+ engine = Engine()
376
+ engine.pin('old-reader')
377
+ list(engine.commit(target))
378
+ old_root,old_values = engine.pins['old-reader']
379
+ current_pages = reachable(engine.disk.stable,engine.current)
380
+ old_only = reachable(engine.disk.stable,old_root)-current_pages
381
+ media = dict(engine.disk.stable)
382
+ for address in old_only:
383
+ media[address] = BAD
384
+ assert recover(media)[0] == 1
385
+ expect_blocked(lambda:read_tree(media,old_root))
386
+ examples['omitted_reader_pin'] = 'latest root remains valid but reclaiming old-only pages destroys an active reader view'
387
+
388
+ engine = Engine()
389
+ engine.fenced = True
390
+ try:
391
+ next(engine.commit(target))
392
+ except WriterFenced:
393
+ examples['failed_io_fence'] = 'the model refuses publication from an uncertain writer; delayed old I/O is excluded by assumption'
394
+ else:
395
+ raise AssertionError('fenced publisher continued')
396
+ return examples
397
+
398
+
399
+ def verify_restart():
400
+ """One partial-publication restart, repair, then physical reuse again."""
401
+ engine = Engine()
402
+ target = {'/left':'left-1','/right':'right-0'}
403
+ candidate,writes = engine.prepare(1,target)
404
+ media = dict(engine.disk.stable)
405
+ media.update(writes)
406
+ newer = seal_bytes(1,candidate)
407
+ media['seal:2'] = newer
408
+ media['seal:3'] = BAD # The other new-bank overwrite tore at the crash.
409
+ # This is a partial unacknowledged publication with no extra erasure spent.
410
+ assert recover(media)[0] == 1
411
+ unsafe = dict(media)
412
+ unsafe['seal:0'] = unsafe['seal:1'] = BAD
413
+ expect_blocked(lambda:recover(unsafe,frozenset({'seal:2'})))
414
+
415
+ disk = Disk(dict(media))
416
+ disk.write('seal:3',newer) # Preserve the last selected witness and old bank.
417
+ normalization_checks = 0
418
+ for image in disk.images():
419
+ for erased in erasures(image,1):
420
+ restored_epoch,restored = recover(image,erased)
421
+ assert restored_epoch in (0,1)
422
+ assert restored == (target if restored_epoch == 1 else engine.expected[0])
423
+ normalization_checks += 1
424
+ disk.force()
425
+ # The dependency copies were already healthy. Normalization completes the
426
+ # selected-bank invariant before the now-protected epoch1 root is admitted.
427
+ engine.disk = disk
428
+ engine.current,engine.epoch,engine.acked = candidate,1,1
429
+ engine.expected[1] = target
430
+ engine.reserved.clear()
431
+ following = {'/left':'left-1','/right':'right-2'}
432
+ publication_checks = 0
433
+ for phase in engine.commit(following):
434
+ for image in engine.disk.images():
435
+ for erased in erasures(image,1):
436
+ e,restored = recover(image,erased)
437
+ assert e >= engine.acked
438
+ assert restored == engine.expected[e]
439
+ publication_checks += 1
440
+ return {'normalization_crash_erasure_checks':normalization_checks,
441
+ 'subsequent_publication_crash_erasure_checks':publication_checks,
442
+ 'unsafe_restart_counterexample':'overwrite old bank before repairing singleton latest bank; both replacements tear and one erasure removes last seal',
443
+ 'scope':'one partial-publication restart and subsequent commit; no arbitrary restart tree or renewed unrepaired fault budget'}
444
+
445
+
446
+ def verify_no_space():
447
+ engine = Engine(pool_pages=8)
448
+ before = dict(engine.disk.stable)
449
+ try:
450
+ list(engine.commit({'/left':'changed','/right':'right-0'}))
451
+ except NoSpace:
452
+ pass
453
+ else:
454
+ raise AssertionError('insufficient safe free pages should refuse allocation')
455
+ assert engine.disk.stable == before and not engine.disk.pending
456
+ assert recover(before) == (0,engine.expected[0])
457
+ return 'allocation refuses before any write when a disjoint candidate cannot fit'
458
+
459
+
460
+ def run():
461
+ suites = [verify_trace(name,f) for name in ('dirty_paths_with_pin','multi_leaf_atomic') for f in (0,1)]
462
+ restart = verify_restart()
463
+ return {'model':'finite physical-page reuse with mirrored COW roots v1',
464
+ 'suites':suites,'restart':restart,'counterexamples':counterexamples(),
465
+ 'no_space_result':verify_no_space(),
466
+ 'total_main_crash_erasure_checks':sum(s['crash_erasure_checks'] for s in suites),
467
+ 'total_pinned_reader_checks':sum(s['pinned_reader_checks'] for s in suites),
468
+ 'total_restart_crash_erasure_checks':restart['normalization_crash_erasure_checks']+restart['subsequent_publication_crash_erasure_checks'],
469
+ 'all_suite_crash_erasure_checks':sum(s['crash_erasure_checks'] for s in suites)+restart['normalization_crash_erasure_checks']+restart['subsequent_publication_crash_erasure_checks'],
470
+ 'assumptions':['one serialized publisher; truthful dependency and publication forces',
471
+ 'all pending dependency and seal records may independently remain old, persist new, or become invalid',
472
+ 'zero or one additional detected logical-record erasure per evaluated image',
473
+ 'two disjoint replicas of each live page; four seals in two banks',
474
+ 'allocate outside current-root closure, active reader pins, and in-flight reservations',
475
+ 'old current dependencies become reusable only after both new seals are forced',
476
+ 'strict maximum complete-valid-seal election before dependency validation; no older fallback',
477
+ 'uncertain sessions fenced and old I/O drained before a later session writes',
478
+ 'idealized digest detection; no malicious rehashing, epochs never reused'],
479
+ 'scope':['three-page binary COW tree: mirrored root plus two mirrored leaves',
480
+ 'a bounded address-indexed logical page pool is overwritten and reused inside the model; no actual page-device I/O',
481
+ 'unchanged leaves share physical pages; old reader roots can remain pinned',
482
+ 'uninterrupted finite commit traces and one targeted partial-publication/restart trace',
483
+ 'no byte-level engine proof, storage hardware qualification, physical power cuts or exhaustive restart/repair tree',
484
+ 'stale lower-generation seals may name reclaimed graphs; recovery is guaranteed within the bounded erasure model, not after every newer witness disappears']}
485
+
486
+
487
+ if __name__ == '__main__':
488
+ parser = argparse.ArgumentParser(description=__doc__)
489
+ parser.add_argument('--json',type=Path)
490
+ args = parser.parse_args()
491
+ result = run()
492
+ rendered = json.dumps(result,indent=2,sort_keys=True)
493
+ if args.json:
494
+ args.json.write_text(rendered+'\n')
495
+ print(rendered)
verify_sequences.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Deterministic mutation/reopen trace that exceeds the physical arena allocation count."""
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import random
7
+ import tempfile
8
+ import pagefs
9
+
10
+
11
+ def main():
12
+ source = Path(pagefs.__file__)
13
+ before_hash = hashlib.sha256(source.read_bytes()).hexdigest()
14
+ rng = random.Random(54013)
15
+ expected = {f'/file/{i:04d}': bytes([i % 251]) * 128 for i in range(128)}
16
+ tokens = {}
17
+ pool = 1024
18
+ allocations = 0
19
+ reclaimed = 0
20
+ checkpoints = 0
21
+ reopens = 0
22
+ with tempfile.TemporaryDirectory(prefix='nyarion-v7-sequence-') as tmp:
23
+ path = Path(tmp) / 'volume.img'
24
+ store = pagefs.PageStore.create(path, initial_files=expected, pool_blocks=pool)
25
+ fixed_size = path.stat().st_size
26
+ store.reset_stats()
27
+ for i in range(2048):
28
+ changes = {}
29
+ for j in range(2 if i % 11 == 0 else 1):
30
+ key = f'/file/{rng.randrange(160):04d}'
31
+ value = None if i % 13 == 0 else rng.randbytes(128 + (i % 7))
32
+ changes[key] = value
33
+ token = f'sequence-{i:06d}'
34
+ epoch = store.transact(changes, token)
35
+ assert epoch == i + 1
36
+ tokens[token] = epoch
37
+ for key, value in changes.items():
38
+ if value is None:
39
+ expected.pop(key, None)
40
+ else:
41
+ expected[key] = value
42
+ assert store.transact(changes, token) == epoch
43
+ if i % 64 == 63:
44
+ store.checkpoint()
45
+ assert path.stat().st_size == fixed_size
46
+ assert store.files() == sorted(expected)
47
+ for key, value in expected.items():
48
+ assert store.get(key) == value
49
+ if i % 256 == 255:
50
+ allocations += store.stats['page_allocations']
51
+ reclaimed += store.stats['reclaimed_blocks']
52
+ checkpoints += store.stats['checkpoints']
53
+ store.close()
54
+ store = pagefs.PageStore(path)
55
+ reopens += 1
56
+ assert store.epoch == i + 1
57
+ for key, value in expected.items():
58
+ assert store.get(key) == value
59
+ for token, token_epoch in tokens.items():
60
+ assert store.query(token)['epoch'] == token_epoch
61
+ allocations += store.stats['page_allocations']
62
+ reclaimed += store.stats['reclaimed_blocks']
63
+ checkpoints += store.stats['checkpoints']
64
+ live = len(store._live_blocks)
65
+ store.close()
66
+ assert allocations > pool, 'must allocate more blocks over time than arena capacity'
67
+ assert reclaimed > 0
68
+ assert hashlib.sha256(source.read_bytes()).hexdigest() == before_hash, 'engine changed during validation'
69
+ result = {'passed': True, 'engine_source_sha256': before_hash, 'transactions': 2048,
70
+ 'retry_assertions': 2048, 'reopens': reopens, 'checkpoints': checkpoints,
71
+ 'pool_blocks': pool, 'cumulative_physical_block_allocations': allocations,
72
+ 'cumulative_reclaimed_blocks': reclaimed, 'final_live_blocks': live,
73
+ 'fixed_apparent_image_bytes': fixed_size, 'final_file_count': len(expected),
74
+ 'all_file_bytes_and_token_epochs_verified': True,
75
+ 'claim': 'finite real-file reuse trace, not indefinite capacity or hardware fault proof'}
76
+ Path('sequence_results.json').write_text(json.dumps(result, indent=2) + '\n')
77
+ print(json.dumps(result, indent=2))
78
+
79
+
80
+ if __name__ == '__main__':
81
+ main()