From ab747bfa47c980bb2f7d47e716d8a9c2d92a98e8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 14:59:23 -0800 Subject: [PATCH] change: cut over to the content-named store and delete the legacy store The runtime stores each volume in one content-named layout on the filer: immutable chunks, segments and roots are ordinary filer files, and one HEAD entry per volume carries every conditional commit. A holder claims HEAD under its granted epoch and claim id, cuts in its own session, commits by HEAD generation and position, and is fenced when its identity moves. Catalog, restore, snapshot, retention, cleaning, verify and volume delete run through the layout kernel; the master mints the layout identity, reads HEAD proofs and holds the delete reservation and lease barrier. The legacy store, its intents and its compatibility paths are removed; existing stores are recreated, not converted. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/README.md | 1 - .../blockmaster/cluster_volume_cli_test.go | 6 +- .../cmd/blockmaster/layout_create.go | 73 + .../cmd/blockmaster/layout_create_test.go | 125 + seaweed-block/cmd/blockmaster/main.go | 31 +- .../blockmaster/workspace_layout_head_test.go | 63 + .../cmd/blockvolume/chunk_maintenance.go | 84 +- .../cmd/blockvolume/chunk_maintenance_test.go | 249 +- seaweed-block/cmd/blockvolume/chunk_remote.go | 129 +- .../cmd/blockvolume/chunk_remote_test.go | 155 +- .../cutover_end_to_end_integration_test.go | 72 + .../existing_geometry_compat_test.go | 11 +- .../cmd/blockvolume/layout_identity_test.go | 24 + .../blockvolume/layout_master_fixture_test.go | 68 + seaweed-block/cmd/blockvolume/main.go | 108 +- .../nvme_witness_integration_test.go | 160 ++ .../planned_handoff_checks_test.go | 45 + .../planned_handoff_integration_test.go | 71 +- ...ure_plain_detach_crash_integration_test.go | 7 +- .../process_exit_authority_test.go | 385 ++-- .../cmd/blockvolume/start_any_test.go | 7 + .../startup_nvme_integration_test.go | 145 -- .../startup_systemd_integration_test.go | 44 +- .../workspace_layout_move_integration_test.go | 299 +++ .../workspace_layout_proof_test.go | 74 + .../cmd/blockvolume/workspace_lease.go | 29 +- .../workspace_lease_binary_test.go | 34 +- .../cmd/blockvolume/workspace_proof_test.go | 69 - .../workspace_weed_integration_test.go | 14 +- seaweed-block/cmd/sw-block/chunk.go | 182 +- seaweed-block/cmd/sw-block/chunk_b.go | 401 ++++ seaweed-block/cmd/sw-block/chunk_b_test.go | 431 ++++ .../chunk_delete_authority_guard_test.go | 53 + seaweed-block/cmd/sw-block/chunk_gc.go | 109 - .../cmd/sw-block/chunk_gc_integration_test.go | 379 --- .../cmd/sw-block/chunk_gc_master_test.go | 14 - seaweed-block/cmd/sw-block/chunk_gc_test.go | 284 --- .../sw-block/chunk_manifest_fixture_test.go | 23 - .../cmd/sw-block/chunk_output_test.go | 18 +- seaweed-block/cmd/sw-block/chunk_restore.go | 92 - .../cmd/sw-block/chunk_restore_test.go | 164 -- seaweed-block/cmd/sw-block/chunk_retain.go | 127 - .../cmd/sw-block/chunk_retain_partial_test.go | 99 - .../cmd/sw-block/chunk_retain_test.go | 91 - seaweed-block/cmd/sw-block/chunk_show_test.go | 66 - .../cmd/sw-block/chunk_start_check_test.go | 81 +- seaweed-block/cmd/sw-block/chunk_test.go | 75 +- seaweed-block/cmd/sw-block/chunk_verify.go | 78 +- .../cmd/sw-block/chunk_verify_test.go | 134 +- .../cmd/sw-block/chunk_volume_delete.go | 144 +- .../chunk_volume_delete_schedule_test.go | 95 + .../cmd/sw-block/chunk_volume_delete_test.go | 158 -- seaweed-block/cmd/sw-block/main.go | 6 +- .../cmd/sw-block/master_helpers_test.go | 56 + seaweed-block/cmd/sw-block/start_any_test.go | 7 + .../cmd/sw-block/workspace_master_test.go | 7 + seaweed-block/core/authority/authority.go | 10 + .../layout_granted_epoch_guard_test.go | 136 ++ seaweed-block/core/authority/workspace.go | 30 +- .../workspace_clean_metadata_test.go | 174 ++ .../authority/workspace_delete_guard_test.go | 95 + .../authority/workspace_delete_reservation.go | 92 + .../workspace_delete_reservation_test.go | 272 +++ .../core/authority/workspace_expiry_test.go | 2 +- .../authority/workspace_issue_publish_test.go | 2 +- .../authority/workspace_lease_horizon_test.go | 4 +- .../core/authority/workspace_lease_view.go | 17 +- .../authority/workspace_lost_range_test.go | 2 +- .../workspace_regrant_storage_test.go | 90 +- .../core/authority/workspace_regrant_test.go | 2 +- .../workspace_same_host_clean_test.go | 13 +- .../workspace_same_host_forced_test.go | 50 + .../core/authority/workspace_test.go | 8 +- .../workspace_unclaimed_grant_test.go | 4 +- .../core/authority/workspace_validity_test.go | 2 +- seaweed-block/core/frontend/chunkstore/api.go | 91 +- .../chunkstore/attach_lookup_error_test.go | 85 - .../core/frontend/chunkstore/catalog.go | 1498 ------------ .../core/frontend/chunkstore/catalog_b.go | 333 +++ .../frontend/chunkstore/catalog_b_test.go | 202 ++ .../chunkstore/catalog_crash_snapshot_test.go | 233 -- .../chunkstore/catalog_deadline_test.go | 193 -- .../chunkstore/catalog_held_create_test.go | 289 --- .../chunkstore/catalog_interleave_test.go | 139 -- .../catalog_replay_deleting_test.go | 128 -- .../chunkstore/catalog_settle_test.go | 243 -- .../core/frontend/chunkstore/catalog_test.go | 677 ------ .../chunkstore/catalog_tombstone_test.go | 63 - .../core/frontend/chunkstore/chunk_remote.go | 645 ------ .../chunk_remote_integration_test.go | 308 --- .../chunkstore/chunk_remote_intent_test.go | 82 - .../chunkstore/chunk_remote_keydomain_test.go | 56 - .../chunkstore/chunk_remote_qualified_test.go | 71 - .../frontend/chunkstore/chunk_remote_round.go | 391 ---- .../chunkstore/chunk_remote_round_test.go | 726 ------ .../frontend/chunkstore/chunk_remote_test.go | 328 --- .../core/frontend/chunkstore/clean_b.go | 65 + .../core/frontend/chunkstore/clean_b_test.go | 300 +++ .../concurrent_cas_integration_test.go | 235 -- .../core/frontend/chunkstore/control_types.go | 150 ++ .../frontend/chunkstore/decode_fuzz_test.go | 146 -- .../frontend/chunkstore/delete_sites_test.go | 12 +- .../chunkstore/filerpb/filer_subset.pb.go | 28 +- .../chunkstore/filerpb/filer_subset.proto | 6 +- .../frontend/chunkstore/flat_head_test.go | 78 - .../chunkstore/fork_size_limit_test.go | 61 - .../chunkstore/format_legacy_upgrade_test.go | 222 -- .../chunkstore/format_refusal_test.go | 105 - .../frontend/chunkstore/format_reuse_test.go | 185 -- .../chunkstore/format_sustained_test.go | 113 - .../chunkstore/format_upgrade_test.go | 125 - seaweed-block/core/frontend/chunkstore/gc.go | 485 ---- .../frontend/chunkstore/gc_clock_skew_test.go | 308 --- .../core/frontend/chunkstore/gc_copy.go | 191 -- .../core/frontend/chunkstore/gc_copy_test.go | 197 -- .../chunkstore/gc_delete_progress_test.go | 97 - .../core/frontend/chunkstore/gc_execution.go | 221 -- .../frontend/chunkstore/gc_execution_test.go | 102 - .../core/frontend/chunkstore/gc_test.go | 393 ---- .../frontend/chunkstore/gc_volume_test.go | 251 -- .../frontend/chunkstore/head_cas_root_test.go | 66 - .../core/frontend/chunkstore/head_decode.go | 112 - .../frontend/chunkstore/head_readers_test.go | 304 ++- .../chunkstore/interrupt_every_step_test.go | 268 --- .../core/frontend/chunkstore/layout/commit.go | 50 +- .../layout/commit_monotonic_test.go | 37 + .../layout/commit_snapshot_position_test.go | 28 + .../frontend/chunkstore/layout/commit_test.go | 8 +- .../core/frontend/chunkstore/layout/create.go | 123 + .../layout/create_target_interrupt_test.go | 97 + .../frontend/chunkstore/layout/create_test.go | 243 ++ .../core/frontend/chunkstore/layout/delete.go | 57 +- .../frontend/chunkstore/layout/delete_test.go | 78 +- .../chunkstore/layout/detached_test.go | 6 +- .../chunkstore/layout/each_ref_test.go | 61 + .../frontend/chunkstore/layout/guard_test.go | 12 + .../core/frontend/chunkstore/layout/head.go | 172 +- .../frontend/chunkstore/layout/head_test.go | 7 + .../chunkstore/layout/kernel_table_test.go | 418 ++++ .../frontend/chunkstore/layout/objects.go | 28 + .../chunkstore/layout/prepare_root_test.go | 58 + .../core/frontend/chunkstore/layout/read.go | 71 +- .../frontend/chunkstore/layout/read_test.go | 4 +- .../core/frontend/chunkstore/layout/remove.go | 25 +- .../frontend/chunkstore/layout/remove_test.go | 2 +- .../frontend/chunkstore/layout/snapshots.go | 137 ++ .../chunkstore/layout/snapshots_test.go | 328 +++ .../frontend/chunkstore/layout/stale_test.go | 16 +- .../core/frontend/chunkstore/layout/start.go | 95 +- .../chunkstore/layout/start_any_test.go | 5 + .../chunkstore/layout/start_seed_test.go | 104 + .../frontend/chunkstore/layout/start_test.go | 40 +- .../core/frontend/chunkstore/layout/verify.go | 426 ++++ .../frontend/chunkstore/layout/verify_test.go | 271 +++ .../core/frontend/chunkstore/layout/volume.go | 59 +- .../chunkstore/layout/volume_geometry_test.go | 63 + .../frontend/chunkstore/layout/volume_test.go | 10 +- .../chunkstore/layout_clean_e2e_test.go | 99 + .../core/frontend/chunkstore/layout_create.go | 83 + .../frontend/chunkstore/layout_create_test.go | 66 + .../chunkstore/layout_fence_latch_test.go | 134 ++ .../chunkstore/layout_geometry_test.go | 55 + .../layout_noop_model_trace_test.go | 69 + .../layout_objects_integration_test.go | 175 +- .../core/frontend/chunkstore/layout_remote.go | 783 +++++++ .../layout_remote_clean_bound_test.go | 105 + .../chunkstore/layout_remote_readback_test.go | 357 +++ .../layout_remote_same_proposal_test.go | 157 ++ .../chunkstore/layout_remote_session_test.go | 194 ++ .../chunkstore/layout_remote_sites_test.go | 89 + .../chunkstore/layout_remote_states_test.go | 193 ++ .../frontend/chunkstore/layout_remote_test.go | 762 ++++++ .../chunkstore/layout_restore_read_test.go | 90 + .../chunkstore/layout_stop_session_test.go | 35 + .../core/frontend/chunkstore/layout_store.go | 337 +++ .../frontend/chunkstore/layout_store_test.go | 439 ++++ .../core/frontend/chunkstore/layout_verify.go | 52 + .../frontend/chunkstore/layout_verify_test.go | 150 ++ .../chunkstore/legacy_head_fixture_test.go | 25 - .../core/frontend/chunkstore/manifest.go | 255 --- .../frontend/chunkstore/manifest_format.go | 105 - .../frontend/chunkstore/manifest_perf_test.go | 187 -- .../chunkstore/manifest_review_test.go | 237 -- .../chunkstore/manifest_scaling_test.go | 36 - .../core/frontend/chunkstore/manifest_test.go | 313 --- .../frontend/chunkstore/manifest_upgrade.go | 80 - .../frontend/chunkstore/reclaim_key_test.go | 47 - .../core/frontend/chunkstore/remote.go | 2 +- .../core/frontend/chunkstore/restore.go | 163 -- .../frontend/chunkstore/restore_lsn_test.go | 28 - .../core/frontend/chunkstore/restore_test.go | 392 ---- .../core/frontend/chunkstore/retain/retain.go | 176 ++ .../frontend/chunkstore/retain/retain_test.go | 178 ++ .../core/frontend/chunkstore/retain_b.go | 153 ++ .../core/frontend/chunkstore/retain_b_test.go | 163 ++ .../core/frontend/chunkstore/retention.go | 533 ----- .../chunkstore/retention_integration_test.go | 254 -- .../chunkstore/retention_review_test.go | 212 -- .../frontend/chunkstore/retention_test.go | 431 ---- .../frontend/chunkstore/segment_fuzz_test.go | 53 - .../core/frontend/chunkstore/share_guard.go | 61 - .../frontend/chunkstore/share_guard_test.go | 204 -- .../chunkstore/snapshot_delete_test.go | 208 -- .../frontend/chunkstore/snapshot_info_b.go | 16 + .../frontend/chunkstore/start_any_test.go | 7 + .../core/frontend/chunkstore/swfs.go | 9 +- .../chunkstore/swfs_batch_integration_test.go | 38 - .../frontend/chunkstore/swfs_batch_test.go | 14 - .../core/frontend/chunkstore/swfs_catalog.go | 22 + .../core/frontend/chunkstore/swfs_flags.go | 14 + .../chunkstore/swfs_list_delete_test.go | 4 +- .../core/frontend/chunkstore/usage.go | 282 --- .../core/frontend/chunkstore/verify.go | 1633 ------------- .../core/frontend/chunkstore/verify_test.go | 2036 ----------------- .../core/frontend/chunkstore/volume_delete.go | 502 ---- .../chunkstore/volume_delete_crash_test.go | 172 -- .../volume_delete_integration_test.go | 163 -- .../frontend/chunkstore/volume_delete_test.go | 550 ----- .../chunkstore/volume_size_limit_test.go | 28 - .../weed_cluster_integration_test.go} | 58 +- .../durable/checkpoint_status_test.go | 11 +- .../durable/chunk_settled_cleanup_test.go | 22 +- .../durable/cut_durable_before_cas_test.go | 34 +- .../durable/first_cut_known_zero_test.go | 54 +- .../frontend/durable/head_belt_close_test.go | 83 - .../core/frontend/durable/headroom_test.go | 11 +- .../core/frontend/durable/host_limit_test.go | 24 +- .../frontend/durable/host_slot_wait_test.go | 40 +- .../frontend/durable/hydration_budget_test.go | 98 +- .../durable/hydration_progress_test.go | 6 +- .../durable/known_zero_premise_test.go | 143 +- .../frontend/durable/m5_sync_bench_test.go | 5 +- .../durable/m5_sync_concurrent_bench_test.go | 5 +- .../m5_sync_crash_layout_integration_test.go | 216 ++ .../frontend/durable/m5_sync_crash_test.go | 7 +- .../durable/maintenance_lineage_test.go | 41 +- .../durable/one_process_per_volume_test.go | 26 +- .../durable/precopy_fifty_iops_test.go | 10 +- .../durable/precopy_rolling_pause_test.go | 39 +- .../durable/precopy_stop_boundary_test.go | 28 +- .../core/frontend/durable/provider.go | 55 +- .../durable/provider_assignment_test.go | 28 +- .../durable/provider_auto_chunk_test.go | 9 +- .../durable/provider_auto_impl_test.go | 5 + .../core/frontend/durable/provider_chunk.go | 299 +-- .../provider_chunk_attach_check_test.go | 39 +- .../provider_chunk_authority_log_test.go | 75 +- .../durable/provider_chunk_burst_test.go | 11 +- .../durable/provider_chunk_control_test.go | 22 +- .../provider_chunk_detach_abort_test.go | 109 +- .../provider_chunk_detach_bounds_test.go | 9 +- .../provider_chunk_detach_hook_test.go | 30 +- .../provider_chunk_detach_stop_test.go | 58 +- .../durable/provider_chunk_holder_test.go | 31 +- .../durable/provider_chunk_lifetime_test.go | 273 ++- .../durable/provider_chunk_moveback_test.go | 83 +- .../durable/provider_chunk_noflush_test.go | 35 +- .../durable/provider_chunk_precopy_test.go | 86 +- .../durable/provider_chunk_sched_test.go | 118 +- .../provider_chunk_snapshot_schedule_test.go | 40 +- .../frontend/durable/provider_chunk_test.go | 180 +- .../durable/provider_format_v3_base_test.go | 41 +- .../provider_format_v3_fresh_crash_test.go | 101 +- .../durable/provider_format_v3_test.go | 313 ++- .../durable/provider_frozen_budget_test.go | 32 +- .../provider_initial_memory_linux_test.go | 106 +- .../core/frontend/durable/provider_layout.go | 169 ++ .../durable/provider_layout_crash_test.go | 209 ++ .../durable/provider_layout_fixture_test.go | 106 + .../provider_layout_plain_replay_test.go | 240 ++ .../durable/provider_layout_restart_test.go | 171 ++ .../provider_layout_same_host_clean_test.go | 62 + .../durable/provider_layout_snapshot.go | 78 + .../durable/provider_layout_snapshot_test.go | 196 ++ .../provider_layout_start_class_test.go | 46 + .../durable/provider_layout_stop_race_test.go | 67 + .../frontend/durable/provider_layout_test.go | 220 ++ .../durable/provider_maintenance_test.go | 93 +- .../durable/provider_manifest_test.go | 33 - .../durable/provider_master_wait_test.go | 42 +- .../durable/provider_offline_seal_test.go | 49 +- .../durable/provider_plain_detach_test.go | 36 +- .../provider_plain_seal_replay_test.go | 229 -- .../durable/provider_reopen_belt_test.go | 87 +- .../durable/provider_restore_schedule_test.go | 106 +- .../durable/provider_seal_progress_test.go | 95 +- .../frontend/durable/provider_seal_replay.go | 58 +- .../durable/provider_seed_linux_test.go | 202 +- .../durable/provider_seed_order_test.go | 90 +- .../provider_ship_rebase_order_test.go | 97 +- .../core/frontend/durable/provider_startup.go | 8 +- .../durable/provider_startup_outcome_test.go | 38 +- .../core/frontend/durable/provider_test.go | 5 + .../durable/provider_zero_bootstrap_test.go | 100 - .../durable/recovery_permanent_test.go | 10 +- .../frontend/durable/rolled_back_copy_test.go | 81 +- .../frontend/durable/runtime_fence_test.go | 16 +- .../core/frontend/durable/start_any_test.go | 7 + .../core/frontend/durable/start_path_test.go | 68 + .../durable/takeover_read_ready_test.go | 57 +- .../durable/testutil/layout_fixture.go | 95 + .../durable/volume_size_admission_test.go | 24 +- .../frontend/ublk/target_latency_perf_test.go | 5 +- .../core/host/master/auth_red_test.go | 2 +- seaweed-block/core/host/master/authz.go | 4 + seaweed-block/core/host/master/authz_test.go | 12 +- seaweed-block/core/host/master/host.go | 18 + .../core/host/master/journal_isolation.go | 4 +- .../host/master/journal_isolation_test.go | 2 +- .../core/host/master/launcher_plan.go | 2 +- .../core/host/master/layout_ready.go | 37 + .../host/master/layout_ready_guard_test.go | 110 + .../core/host/master/layout_ready_test.go | 59 + .../host/master/lifecycle_service_test.go | 138 ++ .../core/host/master/lifecycle_snapshot.go | 1 + .../core/host/master/lifecycle_test.go | 12 + .../core/host/master/product_loop.go | 5 +- .../host/master/server_host_identity_test.go | 2 +- seaweed-block/core/host/master/services.go | 155 +- .../host/master/volume_delete_authority.go | 75 + .../master/volume_delete_authority_test.go | 141 ++ .../core/host/master/volume_identity_test.go | 73 + .../workspace_ack_stop_identity_test.go | 55 + .../core/host/master/workspace_binding.go | 7 +- .../master/workspace_binding_review_test.go | 7 +- .../host/master/workspace_binding_test.go | 6 +- .../master/workspace_exited_holder_test.go | 34 +- .../core/host/master/workspace_head.go | 111 - .../master/workspace_head_format3_test.go | 98 - .../core/host/master/workspace_head_test.go | 105 - .../core/host/master/workspace_layout_head.go | 125 + .../host/master/workspace_layout_head_test.go | 205 ++ .../workspace_lost_range_readout_test.go | 37 +- .../master/workspace_move_integration_test.go | 325 --- .../master/workspace_move_refusal_test.go | 4 +- .../host/master/workspace_move_slot_test.go | 2 +- .../master/workspace_paused_grantee_test.go | 26 +- .../core/host/master/workspace_protocol.md | 16 +- .../host/master/workspace_restore_test.go | 76 +- .../master/workspace_same_host_forced_test.go | 175 ++ .../core/host/master/workspace_service.go | 26 +- .../host/master/workspace_service_test.go | 36 +- .../core/host/master/workspace_skew_test.go | 4 +- .../master/workspace_unclaimed_grant_test.go | 39 +- .../core/host/volume/chunk_b_catalog_test.go | 147 ++ .../core/host/volume/chunk_bootstrap_test.go | 27 +- .../core/host/volume/chunk_control.go | 139 +- .../host/volume/chunk_control_adapter_test.go | 83 +- .../host/volume/chunk_control_class_test.go | 11 +- .../host/volume/chunk_control_order_test.go | 140 +- .../core/host/volume/chunk_control_test.go | 4 +- .../host/volume/chunk_frozen_budget_test.go | 9 +- .../host/volume/chunk_frozen_refused_test.go | 3 +- .../host/volume/chunk_plain_detach_test.go | 3 +- .../core/host/volume/chunk_restore.go | 246 -- .../core/host/volume/chunk_restore_test.go | 394 ---- .../host/volume/chunk_scheduled_snapshot.go | 25 +- .../volume/chunk_scheduled_snapshot_test.go | 56 +- .../volume/chunk_seed_replication_test.go | 50 +- .../core/host/volume/status_chunk_test.go | 14 +- .../core/host/volume/status_schema_test.go | 2 +- .../workspace_lease_stop_pending_test.go | 69 +- .../host/volume/workspace_runtime_test.go | 92 +- seaweed-block/core/launcher/k8s_renderer.go | 17 +- .../core/launcher/layout_identity_test.go | 26 + .../core/lifecycle/deletion_reservations.go | 16 + seaweed-block/core/lifecycle/geometry_test.go | 52 + .../lifecycle/layout_identity_guard_test.go | 144 ++ .../core/lifecycle/layout_identity_test.go | 133 ++ .../core/lifecycle/restore_request_test.go | 56 + seaweed-block/core/lifecycle/store.go | 124 +- .../core/lifecycle/store_crash_test.go | 19 + seaweed-block/core/lifecycle/store_test.go | 5 + seaweed-block/core/lifecycle/workload_plan.go | 2 + .../core/lifecycle/workload_plan_test.go | 4 + seaweed-block/core/rpc/control/control.pb.go | 904 +++++--- .../core/rpc/control/control_grpc.pb.go | 137 +- .../core/rpc/lifecycleclient/identity.go | 31 + .../core/rpc/lifecycleclient/identity_test.go | 48 + seaweed-block/core/rpc/proto/control.proto | 24 + .../storage/chunk_abort_upload_bytes_test.go | 2 +- seaweed-block/core/storage/chunk_birth.go | 15 - .../core/storage/chunk_birth_manifest_test.go | 156 -- seaweed-block/core/storage/chunk_cut_cow.go | 8 +- .../core/storage/chunk_cut_crash_test.go | 30 +- ..._birth_test.go => chunk_cut_image_test.go} | 60 +- .../core/storage/chunk_cut_payload.go | 36 +- .../core/storage/chunk_cut_progress_test.go | 6 +- .../storage/chunk_cut_revoke_reuse_test.go | 2 +- .../core/storage/chunk_fake_remote_test.go | 70 +- .../core/storage/chunk_fixed_spans_test.go | 12 +- seaweed-block/core/storage/chunk_frontier.go | 47 +- .../core/storage/chunk_head_belt_test.go | 145 +- .../core/storage/chunk_intent_test.go | 54 - .../core/storage/chunk_key_domain_test.go | 33 +- seaweed-block/core/storage/chunk_layer.go | 324 +-- .../core/storage/chunk_layer_intent_test.go | 326 --- .../core/storage/chunk_layer_map_v3_test.go | 2 +- .../core/storage/chunk_layer_precopy_test.go | 78 +- .../core/storage/chunk_layer_session_test.go | 290 +++ .../core/storage/chunk_layer_takeover_test.go | 136 -- seaweed-block/core/storage/chunk_manifest.go | 19 +- seaweed-block/core/storage/chunk_memremote.go | 66 +- .../core/storage/chunk_noop_cut_gen_test.go | 41 + seaweed-block/core/storage/chunk_precopy.go | 5 +- .../core/storage/chunk_precopy_detach_test.go | 23 +- seaweed-block/core/storage/chunk_public.go | 9 +- seaweed-block/core/storage/chunk_recency.go | 16 + ...t_test.go => chunk_recency_budget_test.go} | 10 +- .../core/storage/chunk_reopen_belt_test.go | 121 - seaweed-block/core/storage/chunk_restore.go | 122 - .../core/storage/chunk_restore_test.go | 81 +- .../core/storage/chunk_review271_test.go | 62 +- .../storage/chunk_same_host_clean_test.go | 41 - .../core/storage/chunk_seal_replay.go | 27 - seaweed-block/core/storage/chunk_seam.go | 90 +- .../core/storage/chunk_seed_check_test.go | 34 + ...ation_test.go => chunk_seed_image_test.go} | 7 +- .../storage/chunk_session_contract_test.go | 67 + .../storage/chunk_stage_accounting_test.go | 2 +- .../storage/chunk_upload_parallel_test.go | 16 +- .../storage/layout_fresh_mutators_test.go | 156 ++ .../core/storage/layout_identity_v3_test.go | 146 ++ .../storage/legacy_replacement_v3_test.go | 2 +- seaweed-block/core/storage/superblock_v3.go | 51 +- seaweed-block/core/storage/walstore.go | 16 + .../core/storage/walstore_readonly_v3.go | 5 - .../core/storage/walstore_readonly_v3_test.go | 6 +- seaweed-block/core/storage/walstore_v3.go | 56 +- .../docs/design/agent-workspace-design.md | 30 +- seaweed-block/docs/design/invariants.md | 266 +-- seaweed-block/docs/operator-guide.md | 14 +- seaweed-block/docs/standalone-deployment.md | 22 +- seaweed-block/docs/status-schema.md | 30 +- .../internal/invcheck/invariants_test.go | 23 + .../layout-realcluster-integration-gate.yaml | 303 +++ 436 files changed, 22737 insertions(+), 29268 deletions(-) create mode 100644 seaweed-block/cmd/blockmaster/layout_create.go create mode 100644 seaweed-block/cmd/blockmaster/layout_create_test.go create mode 100644 seaweed-block/cmd/blockmaster/workspace_layout_head_test.go create mode 100644 seaweed-block/cmd/blockvolume/cutover_end_to_end_integration_test.go create mode 100644 seaweed-block/cmd/blockvolume/layout_identity_test.go create mode 100644 seaweed-block/cmd/blockvolume/layout_master_fixture_test.go create mode 100644 seaweed-block/cmd/blockvolume/nvme_witness_integration_test.go create mode 100644 seaweed-block/cmd/blockvolume/start_any_test.go create mode 100644 seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go create mode 100644 seaweed-block/cmd/blockvolume/workspace_layout_proof_test.go delete mode 100644 seaweed-block/cmd/blockvolume/workspace_proof_test.go create mode 100644 seaweed-block/cmd/sw-block/chunk_b.go create mode 100644 seaweed-block/cmd/sw-block/chunk_b_test.go create mode 100644 seaweed-block/cmd/sw-block/chunk_delete_authority_guard_test.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_gc.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_gc_integration_test.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_gc_master_test.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_gc_test.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_restore.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_restore_test.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_retain.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_retain_partial_test.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_retain_test.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_show_test.go create mode 100644 seaweed-block/cmd/sw-block/chunk_volume_delete_schedule_test.go delete mode 100644 seaweed-block/cmd/sw-block/chunk_volume_delete_test.go create mode 100644 seaweed-block/cmd/sw-block/master_helpers_test.go create mode 100644 seaweed-block/cmd/sw-block/start_any_test.go create mode 100644 seaweed-block/core/authority/layout_granted_epoch_guard_test.go create mode 100644 seaweed-block/core/authority/workspace_clean_metadata_test.go create mode 100644 seaweed-block/core/authority/workspace_delete_guard_test.go create mode 100644 seaweed-block/core/authority/workspace_delete_reservation.go create mode 100644 seaweed-block/core/authority/workspace_delete_reservation_test.go create mode 100644 seaweed-block/core/authority/workspace_same_host_forced_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/catalog.go create mode 100644 seaweed-block/core/frontend/chunkstore/catalog_b.go create mode 100644 seaweed-block/core/frontend/chunkstore/catalog_b_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/catalog_crash_snapshot_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/catalog_interleave_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/catalog_replay_deleting_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/catalog_settle_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/catalog_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/catalog_tombstone_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/chunk_remote.go delete mode 100644 seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/chunk_remote_intent_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/chunk_remote_keydomain_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/chunk_remote_qualified_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/chunk_remote_round.go delete mode 100644 seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/chunk_remote_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/clean_b.go create mode 100644 seaweed-block/core/frontend/chunkstore/clean_b_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/concurrent_cas_integration_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/control_types.go delete mode 100644 seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/flat_head_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/format_refusal_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/format_reuse_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/format_sustained_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/format_upgrade_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/gc.go delete mode 100644 seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/gc_copy.go delete mode 100644 seaweed-block/core/frontend/chunkstore/gc_copy_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/gc_execution.go delete mode 100644 seaweed-block/core/frontend/chunkstore/gc_execution_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/gc_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/gc_volume_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/head_cas_root_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/head_decode.go delete mode 100644 seaweed-block/core/frontend/chunkstore/interrupt_every_step_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/commit_monotonic_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/commit_snapshot_position_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/create.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/create_target_interrupt_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/create_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/each_ref_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/prepare_root_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/snapshots.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/snapshots_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/start_any_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/start_seed_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/verify.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/verify_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/volume_geometry_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_clean_e2e_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_create.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_create_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_fence_latch_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_geometry_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_noop_model_trace_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_remote.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_remote_clean_bound_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_remote_readback_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_remote_same_proposal_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_remote_session_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_remote_sites_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_remote_states_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_remote_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_restore_read_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_store.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_store_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_verify.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout_verify_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/manifest.go delete mode 100644 seaweed-block/core/frontend/chunkstore/manifest_format.go delete mode 100644 seaweed-block/core/frontend/chunkstore/manifest_perf_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/manifest_review_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/manifest_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/manifest_upgrade.go delete mode 100644 seaweed-block/core/frontend/chunkstore/reclaim_key_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/restore.go delete mode 100644 seaweed-block/core/frontend/chunkstore/restore_lsn_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/restore_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/retain/retain.go create mode 100644 seaweed-block/core/frontend/chunkstore/retain/retain_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/retain_b.go create mode 100644 seaweed-block/core/frontend/chunkstore/retain_b_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/retention.go delete mode 100644 seaweed-block/core/frontend/chunkstore/retention_integration_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/retention_review_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/retention_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/share_guard.go delete mode 100644 seaweed-block/core/frontend/chunkstore/share_guard_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/snapshot_info_b.go create mode 100644 seaweed-block/core/frontend/chunkstore/start_any_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/swfs_catalog.go create mode 100644 seaweed-block/core/frontend/chunkstore/swfs_flags.go delete mode 100644 seaweed-block/core/frontend/chunkstore/usage.go delete mode 100644 seaweed-block/core/frontend/chunkstore/verify.go delete mode 100644 seaweed-block/core/frontend/chunkstore/verify_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/volume_delete.go delete mode 100644 seaweed-block/core/frontend/chunkstore/volume_delete_crash_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/volume_delete_test.go delete mode 100644 seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go rename seaweed-block/core/{host/master/workspace_cluster_integration_test.go => frontend/chunkstore/weed_cluster_integration_test.go} (70%) delete mode 100644 seaweed-block/core/frontend/durable/head_belt_close_test.go create mode 100644 seaweed-block/core/frontend/durable/m5_sync_crash_layout_integration_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout_crash_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout_fixture_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout_plain_replay_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout_restart_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout_same_host_clean_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout_snapshot.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout_snapshot_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout_start_class_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout_stop_race_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_layout_test.go delete mode 100644 seaweed-block/core/frontend/durable/provider_manifest_test.go delete mode 100644 seaweed-block/core/frontend/durable/provider_plain_seal_replay_test.go delete mode 100644 seaweed-block/core/frontend/durable/provider_zero_bootstrap_test.go create mode 100644 seaweed-block/core/frontend/durable/start_any_test.go create mode 100644 seaweed-block/core/frontend/durable/start_path_test.go create mode 100644 seaweed-block/core/frontend/durable/testutil/layout_fixture.go create mode 100644 seaweed-block/core/host/master/layout_ready.go create mode 100644 seaweed-block/core/host/master/layout_ready_guard_test.go create mode 100644 seaweed-block/core/host/master/layout_ready_test.go create mode 100644 seaweed-block/core/host/master/volume_delete_authority.go create mode 100644 seaweed-block/core/host/master/volume_delete_authority_test.go create mode 100644 seaweed-block/core/host/master/volume_identity_test.go create mode 100644 seaweed-block/core/host/master/workspace_ack_stop_identity_test.go delete mode 100644 seaweed-block/core/host/master/workspace_head.go delete mode 100644 seaweed-block/core/host/master/workspace_head_format3_test.go delete mode 100644 seaweed-block/core/host/master/workspace_head_test.go create mode 100644 seaweed-block/core/host/master/workspace_layout_head.go create mode 100644 seaweed-block/core/host/master/workspace_layout_head_test.go delete mode 100644 seaweed-block/core/host/master/workspace_move_integration_test.go create mode 100644 seaweed-block/core/host/master/workspace_same_host_forced_test.go create mode 100644 seaweed-block/core/host/volume/chunk_b_catalog_test.go delete mode 100644 seaweed-block/core/host/volume/chunk_restore.go delete mode 100644 seaweed-block/core/host/volume/chunk_restore_test.go create mode 100644 seaweed-block/core/launcher/layout_identity_test.go create mode 100644 seaweed-block/core/lifecycle/geometry_test.go create mode 100644 seaweed-block/core/lifecycle/layout_identity_guard_test.go create mode 100644 seaweed-block/core/lifecycle/layout_identity_test.go create mode 100644 seaweed-block/core/lifecycle/restore_request_test.go create mode 100644 seaweed-block/core/rpc/lifecycleclient/identity.go create mode 100644 seaweed-block/core/rpc/lifecycleclient/identity_test.go delete mode 100644 seaweed-block/core/storage/chunk_birth.go delete mode 100644 seaweed-block/core/storage/chunk_birth_manifest_test.go rename seaweed-block/core/storage/{chunk_birth_test.go => chunk_cut_image_test.go} (56%) delete mode 100644 seaweed-block/core/storage/chunk_intent_test.go delete mode 100644 seaweed-block/core/storage/chunk_layer_intent_test.go create mode 100644 seaweed-block/core/storage/chunk_layer_session_test.go delete mode 100644 seaweed-block/core/storage/chunk_layer_takeover_test.go create mode 100644 seaweed-block/core/storage/chunk_noop_cut_gen_test.go create mode 100644 seaweed-block/core/storage/chunk_recency.go rename seaweed-block/core/storage/{chunk_birth_budget_test.go => chunk_recency_budget_test.go} (82%) delete mode 100644 seaweed-block/core/storage/chunk_reopen_belt_test.go delete mode 100644 seaweed-block/core/storage/chunk_restore.go delete mode 100644 seaweed-block/core/storage/chunk_same_host_clean_test.go delete mode 100644 seaweed-block/core/storage/chunk_seal_replay.go create mode 100644 seaweed-block/core/storage/chunk_seed_check_test.go rename seaweed-block/core/storage/{chunk_birth_migration_test.go => chunk_seed_image_test.go} (71%) create mode 100644 seaweed-block/core/storage/chunk_session_contract_test.go create mode 100644 seaweed-block/core/storage/layout_fresh_mutators_test.go create mode 100644 seaweed-block/core/storage/layout_identity_v3_test.go create mode 100644 seaweed-block/testops/scenarios/layout-realcluster-integration-gate.yaml diff --git a/seaweed-block/README.md b/seaweed-block/README.md index 2787c44c4a..38101ef947 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -132,7 +132,6 @@ sw-block ops chunk restore --chunk-filer --source v1 --snapshot s1 --t sw-block ops chunk restore --volume v3 --status-addr --status # restore progress sw-block ops chunk detach --volume v1 --status-addr # final cut (seal); moving needs revoke + move, see docs/volume-lifecycle.md sw-block ops chunk volume-delete --volume v2 --chunk-filer --master --request-id del-v2 -sw-block ops chunk gc --chunk-filer --master # preview; --apply to reclaim sw-block ops chunk verify --volume v1 --chunk-filer # read-only check of the remote image ``` diff --git a/seaweed-block/cmd/blockmaster/cluster_volume_cli_test.go b/seaweed-block/cmd/blockmaster/cluster_volume_cli_test.go index d02ebf685b..ec3c98905d 100644 --- a/seaweed-block/cmd/blockmaster/cluster_volume_cli_test.go +++ b/seaweed-block/cmd/blockmaster/cluster_volume_cli_test.go @@ -223,7 +223,11 @@ func TestClusterSpecCLIMissingSizeExplainsCreateVolumePrerequisite(t *testing.T) o2, e2, l2 := importedVolumeClients(t, p2) reportImportedVolume(t, o2) waitImportedAuthority(t, p2, e2) - got, err := l2.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 1048576, ReplicationFactor: 1, Protocol: "nvme", FrontendTransport: "tcp"}) + // The earlier RPC budget belongs to the first daemon. Give this distinct + // request the same budget after the restart, without extending either RPC. + replayCtx, replayCancel := context.WithTimeout(context.Background(), 3*time.Second) + defer replayCancel() + got, err := l2.CreateVolume(replayCtx, &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 1048576, ReplicationFactor: 1, Protocol: "nvme", FrontendTransport: "tcp"}) if err != nil || got.Protocol != "nvme" || got.FrontendTransport != "tcp" || got.PvcNamespace != "workspaces" || got.PvcName != "claim-v1" { t.Fatalf("cluster import changed existing protocol/metadata: %v %v", got, err) } diff --git a/seaweed-block/cmd/blockmaster/layout_create.go b/seaweed-block/cmd/blockmaster/layout_create.go new file mode 100644 index 0000000000..c3131e2b32 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/layout_create.go @@ -0,0 +1,73 @@ +package main + +import ( + "context" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +// layoutVolumeCreator writes only the master's initial VOLUME and unclaimed +// HEAD. layout.CreateVolume performs exclusive writes and heals a replay +// stopped between them without minting another identity. +func layoutVolumeCreator(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec) error { + return func(ctx context.Context, spec lifecycle.VolumeSpec) error { + if cat == nil { + return fmt.Errorf("master: layout catalog is unavailable") + } + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return err + } + _, err = cat.CreateVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}, layout.Geometry{ + SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes, + }) + return err + } +} + +func layoutVolumeReader(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec) (layout.Volume, error) { + return func(ctx context.Context, spec lifecycle.VolumeSpec) (layout.Volume, error) { + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return layout.Volume{}, err + } + return cat.ReadVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}) + } +} + +func layoutHeadReader(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec) (layout.Head, error) { + return func(ctx context.Context, spec lifecycle.VolumeSpec) (layout.Head, error) { + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return layout.Head{}, err + } + h, found, err := cat.ReadHead(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}) + if err != nil { + return layout.Head{}, err + } + if !found { + return layout.Head{}, layout.ErrHeadAbsent + } + return h, nil + } +} + +func layoutTargetCreator(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec, lifecycle.VolumeSpec, string) error { + return func(ctx context.Context, source, target lifecycle.VolumeSpec, snapshot string) error { + sid, err := layout.ParseVolumeID(source.LayoutID) + if err != nil { + return err + } + tid, err := layout.ParseVolumeID(target.LayoutID) + if err != nil { + return err + } + _, err = cat.Restore(ctx, + chunkstore.VolumeRef{Name: source.VolumeID, ID: sid}, snapshot, + chunkstore.VolumeRef{Name: target.VolumeID, ID: tid}) + return err + } +} diff --git a/seaweed-block/cmd/blockmaster/layout_create_test.go b/seaweed-block/cmd/blockmaster/layout_create_test.go new file mode 100644 index 0000000000..ed16858a5e --- /dev/null +++ b/seaweed-block/cmd/blockmaster/layout_create_test.go @@ -0,0 +1,125 @@ +package main + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +type failFirstHead struct { + chunkstore.Filer + fail bool +} + +func (f *failFirstHead) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, excl bool) error { + if e.Name == "HEAD" && f.fail { + f.fail = false + return errors.New("fixture: lost filer HEAD create") + } + return f.Filer.CreateEntry(ctx, dir, e, excl) +} + +type noCreateBlobs struct{} + +func (noCreateBlobs) Put(context.Context, []byte) (string, error) { + return "", errors.New("unexpected blob upload") +} +func (noCreateBlobs) Get(context.Context, string) ([]byte, error) { + return nil, errors.New("unexpected blob read") +} + +func TestMasterLayoutCreatorWritesUnclaimedHeadAndReplays(t *testing.T) { + ctx := context.Background() + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), noCreateBlobs{}, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + spec := lifecycle.VolumeSpec{VolumeID: "v", LayoutID: id.String(), SizeBytes: 1 << 20, BlockSize: 4096, ChunkBytes: 4 << 20, ReplicationFactor: 1} + create := layoutVolumeCreator(cat) + var firstGen uint64 + for i := 0; i < 2; i++ { + if err := create(ctx, spec); err != nil { + t.Fatalf("create attempt %d: %v", i, err) + } + h, found, err := cat.ReadHead(ctx, chunkstore.VolumeRef{Name: "v", ID: id}) + if err != nil || !found { + t.Fatalf("read HEAD after attempt %d: found=%t err=%v", i, found, err) + } + if i == 0 { + firstGen = h.Gen + } else if h.Gen != firstGen { + t.Fatalf("replay changed HEAD generation %d -> %d", firstGen, h.Gen) + } + } + st, err := cat.Store(chunkstore.VolumeRef{Name: "v", ID: id}) + if err != nil { + t.Fatal(err) + } + v, found, err := st.ReadVolumeRecord(ctx) + if err != nil || !found || v.Geometry != (layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes}) { + t.Fatalf("VOLUME=%+v found=%t err=%v", v, found, err) + } + h, found, err := st.ReadHead(ctx) + if err != nil || !found || h.Epoch != 0 || h.Holder != "" || h.ClaimID != "" || h.Gen == 0 { + t.Fatalf("unclaimed HEAD=%+v found=%t err=%v", h, found, err) + } +} + +func TestMasterLayoutCreatorHealsCrashBetweenVolumeAndHead(t *testing.T) { + ctx := context.Background() + filer := &failFirstHead{Filer: chunkstore.NewMemFiler(), fail: true} + cat, err := chunkstore.NewBCatalog(filer, noCreateBlobs{}, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v", ID: id} + spec := lifecycle.VolumeSpec{VolumeID: ref.Name, LayoutID: id.String(), SizeBytes: 1 << 20, BlockSize: 4096, ChunkBytes: 4 << 20, ReplicationFactor: 1} + create := layoutVolumeCreator(cat) + if err := create(ctx, spec); err == nil { + t.Fatal("first HEAD create did not fail") + } + st, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } + if _, found, err := st.ReadVolumeRecord(ctx); err != nil || !found { + t.Fatalf("VOLUME after interrupted create: found=%t err=%v", found, err) + } + if _, found, err := st.ReadHead(ctx); err != nil || found { + t.Fatalf("HEAD after interrupted create: found=%t err=%v", found, err) + } + if err := create(ctx, spec); err != nil { + t.Fatalf("retry did not complete HEAD: %v", err) + } + if h, found, err := st.ReadHead(ctx); err != nil || !found || h.Epoch != 0 { + t.Fatalf("healed HEAD=%+v found=%t err=%v", h, found, err) + } +} + +func TestMasterLayoutHeadReaderRefusesAbsentHead(t *testing.T) { + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), noCreateBlobs{}, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + spec := lifecycle.VolumeSpec{VolumeID: "source", LayoutID: id.String()} + if _, err := layoutHeadReader(cat)(context.Background(), spec); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("absent source HEAD: %v; want ErrHeadAbsent", err) + } +} diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index d2c129dc89..d42f53dd68 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -13,6 +13,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "github.com/seaweedfs/seaweed-block/core/host/master" @@ -63,6 +64,10 @@ type flags struct { workspaceMaxClockSkew time.Duration workspaceRPC bool workspaceHEADBase string + chunkFiler string + chunkPath string + chunkCollection string + chunkReplication string frontendPublicationRuntimeHTTP bool frontendPublicationRuntimeListen string strictJournalIsolation bool @@ -122,7 +127,8 @@ func parseFlags(args []string) (flags, error) { fs.BoolVar(&f.failbackRuntimeRPC, "failback-runtime-rpc", false, "enable disabled-by-default authority failback RPC; requires expected-current and terminal evidence") fs.DurationVar(&f.workspaceMaxClockSkew, "workspace-max-clock-skew", 20*time.Second, "maximum workspace clock skew; host lease shortens by half, forced moves wait the full bound") fs.BoolVar(&f.workspaceRPC, "workspace-rpc", false, "enable RF1 workspace lease/revocation/move RPCs") - fs.StringVar(&f.workspaceHEADBase, "workspace-head-base-url", "", "filer HTTP directory containing per-volume HEAD files; required with --workspace-rpc") + fs.StringVar(&f.workspaceHEADBase, "workspace-head-base-url", "", "filer HTTP base containing -/HEAD; required with --workspace-rpc") + chunkstore.RegisterSWFSFlags(fs, &f.chunkFiler, &f.chunkPath, &f.chunkCollection, &f.chunkReplication) fs.BoolVar(&f.frontendPublicationRuntimeHTTP, "frontend-publication-runtime-http", false, "enable disabled-by-default frontend publication HTTP runtime; confirms post-failback authority publication only") fs.StringVar(&f.frontendPublicationRuntimeListen, "frontend-publication-runtime-listen", "127.0.0.1:9334", "HTTP listen address for --frontend-publication-runtime-http") fs.BoolVar(&f.strictJournalIsolation, "strict-journal-isolation", false, "refuse new work on nodes whose durable root shares the authority store's file system (one journal): their heartbeats are refused until they serve a volume, and no placement or move targets them; off = alarm only") @@ -238,6 +244,21 @@ func run(f flags) int { return 1 } cfg.Auth, cfg.ServerOptions = authn, serverOpts + if f.workspaceRPC { + cat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{ + FilerGRPC: f.chunkFiler, Collection: f.chunkCollection, + Replication: f.chunkReplication, AssignPath: f.chunkPath, + }) + if err != nil { + fmt.Fprintln(os.Stderr, "blockmaster: layout filer:", err) + return 1 + } + defer client.Close() + cfg.LayoutCreateVolume = layoutVolumeCreator(cat) + cfg.LayoutReadVolume = layoutVolumeReader(cat) + cfg.LayoutReadHead = layoutHeadReader(cat) + cfg.LayoutCreateTarget = layoutTargetCreator(cat) + } if authn != nil { if days, until, err := certDaysLeft(f.auth.tlsCert, f.auth.tlsKey, time.Now()); err == nil { fmt.Fprintln(os.Stderr, fmt.Sprintf("blockmaster: mutual TLS on; role file %s; own certificate expires %s (%d days)", f.auth.roleFile, until.UTC().Format(time.RFC3339), days)) @@ -245,8 +266,12 @@ func run(f flags) int { } else { warnUnauthenticated(f.listen) } + // New starts no loops: bind h before Start permits any HEAD request. + var h *master.Host if f.workspaceRPC { - reader, err := master.NewWorkspaceHEADReader(f.workspaceHEADBase) + reader, err := master.NewLayoutWorkspaceHEADReader(f.workspaceHEADBase, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { + return h.WorkspaceLayoutVolume(ctx, name) + }) if err != nil { fmt.Fprintln(os.Stderr, "blockmaster:", err) return 1 @@ -254,7 +279,7 @@ func run(f flags) int { cfg.WorkspaceRPC = true cfg.WorkspaceHeadReader = reader } - h, err := master.New(cfg) + h, err = master.New(cfg) if err != nil { fmt.Fprintln(os.Stderr, "blockmaster:", err) return 1 diff --git a/seaweed-block/cmd/blockmaster/workspace_layout_head_test.go b/seaweed-block/cmd/blockmaster/workspace_layout_head_test.go new file mode 100644 index 0000000000..c20811c87d --- /dev/null +++ b/seaweed-block/cmd/blockmaster/workspace_layout_head_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "reflect" + "strings" + "testing" +) + +// The runtime uses the master-bound reader; the legacy constructor is not a +// fallback. Every constructor/resolver caller is a classified production site. +func TestWorkspaceLayoutHEADReaderWiring(t *testing.T) { + want := map[string]int{"cmd/blockmaster/main.go run -> NewLayoutWorkspaceHEADReader": 1, "cmd/blockmaster/main.go run -> WorkspaceLayoutVolume": 1} + found := map[string]int{} + root := filepath.Join("..", "..") + for _, top := range []string{"core", "cmd"} { + err := filepath.WalkDir(filepath.Join(root, top), func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return err + } + f, err := parser.ParseFile(token.NewFileSet(), p, nil, 0) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, p) + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + c, ok := n.(*ast.CallExpr) + if !ok { + return true + } + name := "" + switch x := c.Fun.(type) { + case *ast.Ident: + name = x.Name + case *ast.SelectorExpr: + name = x.Sel.Name + } + switch name { + case "NewLayoutWorkspaceHEADReader", "WorkspaceLayoutVolume": + found[filepath.ToSlash(rel)+" "+fn.Name.Name+" -> "+name]++ + } + return true + }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + if !reflect.DeepEqual(want, found) { + t.Fatalf("HEAD reader wiring changed; classify and probe the new site: want %v, got %v", want, found) + } +} diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance.go b/seaweed-block/cmd/blockvolume/chunk_maintenance.go index cbb361c897..840a87b572 100644 --- a/seaweed-block/cmd/blockvolume/chunk_maintenance.go +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance.go @@ -5,55 +5,55 @@ import ( "errors" "fmt" "log" + "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/rpc/link" - "google.golang.org/grpc" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) -// Automatic GC stays default-off until restart-safe unknown-CAS settlement and -// the 50/200-volume root-scan measurement both pass. Retention remains enabled. -// The CLI fixes the maximum cut/copy lifetime at five minutes and the HEAD -// hydration reader at thirty seconds. A one-minute mark fits strictly inside -// the one-hour grace. No elapsed TTL alone authorizes capture-intent expiry. -func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter, collect bool, master string, masterTLS grpc.DialOption) (func(context.Context, string) error, func() error, error) { - closeFn := func() error { return nil } - cfg := chunkstore.GCConfig{Grace: defaultChunkGCGrace, IntentTTL: defaultChunkIntentTTL} - if collect { - if master == "" { - return nil, closeFn, errors.New("automatic chunk GC requires blockmaster authority") - } - if defaultChunkGCGrace <= max(defaultChunkCutTimeout, chunkstore.DefaultOpDeadline)+defaultChunkMaintenanceTimeout { - return nil, closeFn, errors.New("automatic GC grace does not cover cut/copy and mark bounds") - } - conn, err := link.DialMaster(master, masterTLS, link.MasterReconnect()) - if err != nil { - return nil, closeFn, err - } - closeFn = conn.Close - evidence := control.NewEvidenceServiceClient(conn) - cfg.IssuedEpoch = func(ctx context.Context, vol string) (uint64, error) { - reply, err := evidence.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: vol}) - if err != nil { - return 0, err - } - if reply.GetVolumeId() != vol || !reply.GetAssigned() || reply.GetEpoch() == 0 { - return 0, fmt.Errorf("blockmaster has no issued authority for %s", vol) - } - return reply.Epoch, nil - } - } +// errNoLayoutHolder: the process has no holder identity for the volume yet +// (it is not attached, or Start has not returned), so it does not clean. +var errNoLayoutHolder = errors.New("blockvolume: no layout holder identity for the volume") + +// newChunkMaintenance is the holder's periodic pass over its one volume ref: +// retention, then, when collect is set, the cleaning through the holder's +// own layout remote (remote.Clean with the catalog's removal step), the one +// cleaning entry: a cut or a stop cancels it through the remote's state. +// cleanerOf returns the remote Start established; its Begin refuses unless +// HEAD is still that holder's at its epoch, so a process that lost the +// volume removes nothing. Automatic cleaning stays default-off; retention runs either way. +// layoutCleaner is the holder's layout remote as the maintenance cleans +// through it (chunkstore.LayoutRemote). +type layoutCleaner interface { + Clean(ctx context.Context, run func(ctx context.Context, me layout.HolderID, session string) error) error +} + +func newChunkMaintenance(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, cleanerOf func(context.Context) (layoutCleaner, error), collect bool, now func() time.Time) func(context.Context, string) error { return func(ctx context.Context, vol string) error { - retained, err := cat.Retain(ctx, vol, false) - if err != nil { - return fmt.Errorf("retain deleted=%d not_attempted=%d: %w", len(retained.Deleted), len(retained.NotAttempted), err) + if cat == nil || vol != ref.Name || ref.ID.IsZero() { + return fmt.Errorf("%w: maintenance of %q, process holds %q", layout.ErrIdentity, vol, ref.Name) + } + if _, err := cat.Retain(ctx, ref, now(), false); err != nil { + return fmt.Errorf("retain: %w", err) } if !collect { return nil } - out, err := cat.ExecuteVolumeGC(ctx, vol, blobs, cfg, true) - log.Printf("blockvolume: maintenance volume=%s mark=%s reclaimed=%d settled=%d unknown=%v", vol, out.MarkOutcome, out.Reclaimed, out.SettledCopies, out.UnknownOutcomes) - return err - }, closeFn, nil + remote, err := cleanerOf(ctx) + if err != nil { + return err + } + var res chunkstore.CleanResult + var session string + err = remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, s string) error { + session = s + var rerr error + res, rerr = cat.RemoveUnreachableAll(ctx, ref, me, s) + return rerr + }) + log.Printf("blockvolume: maintenance volume=%s clean=%s shards=%d planned=%d removed=%d", vol, session, res.Shards, res.Planned, res.Removed) + // A cleaning refused because HEAD moved away from this holder is + // the same fence a cut would see: classified so the provider latches. + return chunkstore.LayoutErr(err) + } } diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go index b61568b10c..31dc651484 100644 --- a/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go @@ -1,114 +1,189 @@ package main import ( + "bytes" "context" "errors" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" + "fmt" "path" + "sync" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" ) -type maintenanceGCFiler struct { - chunkstore.Filer - gcCalls, marked, freed int - failSecond bool +// maintenanceBlobs is an in-memory needle store. +type maintenanceBlobs struct { + mu sync.Mutex + n int + d map[string][]byte } -func (f *maintenanceGCFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { - if name == "_GC_MARK" { - f.gcCalls++ - return nil, errors.New("witness: GC reached") - } - return f.Filer.LookupEntry(ctx, dir, name) +func (b *maintenanceBlobs) Put(_ context.Context, data []byte) (string, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.n++ + fid := fmt.Sprintf("1,%x", b.n) + b.d[fid] = append([]byte(nil), data...) + return fid, nil } -func (f *maintenanceGCFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { - if string(e.Extended["swb.snap.state"]) == chunkstore.SnapDeleting { - if f.failSecond && f.marked == 1 { - return errors.New("second retention mark refused") + +func (b *maintenanceBlobs) Get(_ context.Context, fid string) ([]byte, error) { + b.mu.Lock() + defer b.mu.Unlock() + d, ok := b.d[fid] + if !ok { + return nil, chunkstore.ErrBlobNotFound + } + return append([]byte(nil), d...), nil +} + +// failingLookups fails every entry lookup once armed (a filer gone away). +type failingLookups struct { + *chunkstore.MemFiler + armed bool +} + +func (f *failingLookups) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if f.armed { + return nil, errors.New("filer: unavailable") + } + return f.MemFiler.LookupEntry(ctx, dir, name) +} + +type okLease struct{} + +func (okLease) OldLeaseEnded(context.Context, uint64) error { return nil } + +var maintenanceHolder = layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + +// maintenanceFixture is volume v1 started by maintenanceHolder, with one +// orphan chunk in shard 0 that no root names. +func maintenanceFixture(t *testing.T) (*chunkstore.BCatalog, chunkstore.VolumeRef, *failingLookups, *chunkstore.LayoutStore, layout.ChunkName) { + t.Helper() + ctx := context.Background() + f := &failingLookups{MemFiler: chunkstore.NewMemFiler()} + cat, err := chunkstore.NewBCatalog(f, &maintenanceBlobs{d: map[string][]byte{}}, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + s, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } + if _, err := layout.Start(ctx, s, okLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + data := bytes.Repeat([]byte{9}, 4096) + orphan := layout.NameChunk(3, data) + if err := layout.EnsureObject(ctx, s, orphan.Path(), data, "dead-session"); err != nil { + t.Fatal(err) + } + // A real filer lists the shard directory it created; the in-memory one + // keeps only entries. + if err := f.CreateEntry(ctx, path.Join("/blocks", ref.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil { + t.Fatal(err) + } + return cat, ref, f, s, orphan +} + +func orphanPresent(t *testing.T, s *chunkstore.LayoutStore, n layout.ChunkName) bool { + t.Helper() + _, found, err := s.Stat(context.Background(), n.Path()) + if err != nil { + t.Fatal(err) + } + return found +} + +// holderCalls is the attachment's layout remote for holder me (or err when +// the process has no holder identity yet), counting the calls. +func holderCalls(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, me layout.HolderID, err error) (func(context.Context) (layoutCleaner, error), *int) { + n := 0 + return func(context.Context) (layoutCleaner, error) { + n++ + if err != nil { + return nil, err } - f.marked++ - } - return f.Filer.UpdateEntry(ctx, dir, e, expected) -} -func (f *maintenanceGCFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { - err := f.Filer.DeleteEntry(ctx, dir, name, expected) - if err == nil && path.Base(dir) == "snapnames" { - f.freed++ - } - return err + return chunkstore.NewLayoutRemote(cat, ref, me) + }, &n } -type maintenanceBlobs struct{} - -func (maintenanceBlobs) DeleteBlob(context.Context, string) error { return nil } -func (maintenanceBlobs) Put(context.Context, []byte) (string, error) { return "unused", nil } -func (maintenanceBlobs) Get(context.Context, string) ([]byte, error) { - return nil, errors.New("unexpected blob read") +// Default-off: the pass retains and never asks for a holder or removes. +func TestMaintenanceDefaultRetainsAndDoesNotClean(t *testing.T) { + cat, ref, _, s, orphan := maintenanceFixture(t) + holder, calls := holderCalls(cat, ref, maintenanceHolder, nil) + pass := newChunkMaintenance(cat, ref, holder, false, time.Now) + if err := pass(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + if *calls != 0 || !orphanPresent(t, s, orphan) { + t.Fatalf("default pass: holder asked %d times, orphan present %v; want 0, true", *calls, orphanPresent(t, s, orphan)) + } } -func TestMaintenanceRetentionFailureNeverStartsGC(t *testing.T) { - for _, partial := range []bool{false, true} { - t.Run(map[bool]string{false: "missing", true: "partial"}[partial], func(t *testing.T) { - ctx := context.Background() - f := &maintenanceGCFiler{Filer: chunkstore.NewMemFiler(), failSecond: partial} - cat, err := chunkstore.NewCatalog(f, defaultChunkPath) - if err != nil { - t.Fatal(err) + +// With collect on, the holder's pass removes the orphan; a process with +// another claim, or with no holder identity yet, removes nothing. +func TestMaintenanceCleansOnlyAsTheHolder(t *testing.T) { + ctx := context.Background() + for name, tc := range map[string]struct { + me layout.HolderID + err error + removed bool + }{ + "holder": {me: maintenanceHolder, removed: true}, + "other claim": {me: layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "old"}}, + "next epoch": {me: layout.HolderID{Epoch: 2, Holder: "s/r", ClaimID: "k"}}, + "no identity": {err: errNoLayoutHolder}, + } { + t.Run(name, func(t *testing.T) { + cat, ref, _, s, orphan := maintenanceFixture(t) + holder, _ := holderCalls(cat, ref, tc.me, tc.err) + err := newChunkMaintenance(cat, ref, holder, true, time.Now)(ctx, "v1") + if gone := !orphanPresent(t, s, orphan); gone != tc.removed || (err == nil) != tc.removed { + t.Fatalf("pass: err %v, orphan removed %v; want removed %v", err, gone, tc.removed) } - vol := "missing-volume" - if partial { - vol = "v1" - if _, err = cat.EnsureVolume(ctx, vol, chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } - if err = cat.SetRetentionPolicy(ctx, vol, chunkstore.RetentionPolicy{}); err != nil { - t.Fatal(err) - } - now := time.Now().Add(-48 * time.Hour) - cat.SetClock(func() time.Time { return now }) - for _, name := range []string{"a", "b"} { - if _, err = cat.CreateSnapshot(ctx, vol, chunkstore.SnapshotRequest{Name: name, RequestID: "req"}, storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{}}); err != nil { - t.Fatal(err) - } - now = now.Add(time.Second) - } - now = time.Now() + if tc.err != nil && !errors.Is(err, tc.err) { + t.Fatalf("pass: %v; want %v", err, tc.err) } - pass, closeFn, err := newChunkMaintenance(cat, maintenanceBlobs{}, true, "unused-master:1234", nil) - if err != nil { - t.Fatal(err) - } - defer closeFn() - if err = pass(ctx, vol); err == nil { - t.Fatal("retention failure accepted") - } - if f.gcCalls != 0 { - t.Fatalf("retention failure entered GC %d times", f.gcCalls) - } - if partial && (f.marked != 1 || f.freed != 1) { - t.Fatalf("partial retention effects not retained: marked=%d freed=%d err=%v", f.marked, f.freed, err) + // HEAD is another claim's or epoch's: the refusal is the fence a + // cut would see, so the provider latches the layer on it. + if (name == "other claim" || name == "next epoch") && !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("pass refused as %v; want it classified as the fence", err) } }) } } -func TestMaintenanceDefaultRetainNeedsNoEpochClient(t *testing.T) { - f := chunkstore.NewMemFiler() - cat, err := chunkstore.NewCatalog(f, defaultChunkPath) - if err != nil { - t.Fatal(err) +// A failed retention ends the pass before the cleaning starts. +func TestMaintenanceRetentionFailureNeverStartsCleaning(t *testing.T) { + cat, ref, f, s, orphan := maintenanceFixture(t) + holder, calls := holderCalls(cat, ref, maintenanceHolder, nil) + f.armed = true + err := newChunkMaintenance(cat, ref, holder, true, time.Now)(context.Background(), "v1") + f.armed = false + if err == nil || *calls != 0 || !orphanPresent(t, s, orphan) { + t.Fatalf("pass with retention failing: err %v, holder asked %d, orphan present %v", err, *calls, orphanPresent(t, s, orphan)) } - if _, err = cat.EnsureVolume(context.Background(), "v", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } - pass, closeFn, err := newChunkMaintenance(cat, nil, false, "", nil) - if err != nil { - t.Fatal(err) - } - defer closeFn() - if err = pass(context.Background(), "v"); err != nil { - t.Fatal(err) +} + +// The pass serves only the volume the process was started for. +func TestMaintenanceRefusesAnotherVolume(t *testing.T) { + cat, ref, _, _, _ := maintenanceFixture(t) + holder, _ := holderCalls(cat, ref, maintenanceHolder, nil) + if err := newChunkMaintenance(cat, ref, holder, true, time.Now)(context.Background(), "v2"); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("pass for another volume: %v; want ErrIdentity", err) } } diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index c6b80aa4ca..891343b2e8 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -15,22 +15,20 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/hostlimit" - "github.com/seaweedfs/seaweed-block/core/storage" "google.golang.org/grpc" ) const ( - defaultChunkPath = "/swblock/chunks" + defaultChunkPath = chunkstore.DefaultChunkPath // Periodic HEAD publication bounds the host-loss recovery point. Scheduled // named snapshots are set by --chunk-snapshot-schedule. defaultChunkCaptureInterval = 0 defaultChunkMaintenanceInterval = time.Hour defaultChunkCutTimeout = 5 * time.Minute defaultChunkMaintenanceTimeout = time.Minute - defaultChunkGCGrace = time.Hour - defaultChunkIntentTTL = time.Hour ) type chunkFlags struct { @@ -155,16 +153,14 @@ func (s *snapshotSchedule) Set(v string) error { } type chunkWiring struct { - remoteFor func(volumeID string) (storage.ChunkRemote, error) - catalog *chunkstore.Catalog - maintenance func(context.Context, string) error - close func() error + bCatalog *chunkstore.BCatalog + close func() error } // newChunkWiring dials the filer and refuses unless it is the only filer of // its group (chunkstore.CheckSingleFiler). func newChunkWiring(c chunkFlags, masterTLS grpc.DialOption, master ...string) (chunkWiring, error) { - client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{ + bcat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{ FilerGRPC: c.filer, Collection: c.collection, Replication: c.replication, @@ -173,47 +169,42 @@ func newChunkWiring(c chunkFlags, masterTLS grpc.DialOption, master ...string) ( if err != nil { return chunkWiring{}, err } - // Deployment rule: block metadata goes through exactly one filer. - if err := client.CheckSingleFiler(context.Background()); err != nil { - _ = client.Close() - return chunkWiring{}, err - } - cat, err := chunkstore.NewCatalog(client, c.path) - if err != nil { - _ = client.Close() - return chunkWiring{}, err - } - var masterAddr string - if len(master) > 0 { - masterAddr = master[0] - } - maintenance, closeMaintenance, err := newChunkMaintenance(cat, client, c.automaticGC, masterAddr, masterTLS) - if err != nil { - _ = client.Close() - return chunkWiring{}, err - } return chunkWiring{ - maintenance: maintenance, - remoteFor: func(volumeID string) (storage.ChunkRemote, error) { - root, err := chunkVolumeRoot(c.path, volumeID) - if err != nil { - return nil, err - } - return chunkstore.NewSWFSChunkRemote(client, root) - }, - catalog: cat, - close: func() error { return errors.Join(closeMaintenance(), client.Close()) }, + bCatalog: bcat, + close: client.Close, }, nil } -// chunkAttachCheck applies the VOLUME entry's attach rules before the chunk -// layer attaches (B9 W2 §4.2): create VOLUME from the local geometry when -// it is missing, refuse geometry_mismatch, and refuse fork_incomplete for a -// fork whose HEAD is not written yet. -func chunkAttachCheck(cat *chunkstore.Catalog) func(context.Context, string, durable.ChunkGeometry) error { - return func(ctx context.Context, volumeID string, g durable.ChunkGeometry) error { - _, err := cat.EnsureVolume(ctx, volumeID, chunkstore.Geometry{NumBlocks: g.NumBlocks, BlockSize: g.BlockSize, ChunkBlocks: g.ChunkBlocks}) - return err +// chunkAttachCheck admits only a volume the master already created in the +// store. Starting a holder never creates VOLUME or HEAD. +func chunkAttachCheck(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef) func(context.Context, string, durable.ChunkGeometry) error { + return func(ctx context.Context, name string, g durable.ChunkGeometry) error { + if cat == nil || name != ref.Name || ref.ID.IsZero() { + return layout.ErrIdentity + } + st, err := cat.Store(ref) + if err != nil { + return err + } + v, found, err := st.ReadVolumeRecord(ctx) + if err != nil { + return err + } + if !found { + return fmt.Errorf("%w: volume %s not created in the store", layout.ErrMissing, name) + } + want := layout.Geometry{SizeBytes: g.NumBlocks * uint64(g.BlockSize), BlockSize: g.BlockSize, ChunkBytes: uint64(g.ChunkBlocks) * uint64(g.BlockSize)} + if v.Geometry != want { + return fmt.Errorf("%w: local %+v differs from VOLUME %+v", layout.ErrGeometryMismatch, want, v.Geometry) + } + _, found, err = cat.ReadHead(ctx, ref) + if err != nil { + return err + } + if !found { + return fmt.Errorf("%w: volume %s not created in the store", layout.ErrHeadAbsent, name) + } + return nil } } @@ -222,33 +213,31 @@ func chunkAttachCheck(cat *chunkstore.Catalog) func(context.Context, string, dur // volume record stays wrong until the operator changes the flag. const exitGeometryRefused = 78 -// geometryFlagsRefusal compares the geometry flags with the volume record -// before any local store is created, so a wrong flag never leaves a store of -// the wrong size behind. It returns the refusal line and its exit status: -// exitGeometryRefused (78) when the record disagrees or is there but does not -// decode; exitWorkspaceRetry (75) when the filer could not be read (an -// unknown, never taken as "absent"); ("", 0) when the record agrees, does -// not exist yet (the attach -// check creates it from the flags), or no store is being created (numBlocks -// 0: an existing store opens with its own geometry). -func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.Catalog, volumeID string, numBlocks uint64, blockSize uint32) (string, int) { +// geometryFlagsRefusal reads only the immutable size_bytes, block_size and +// chunk_bytes of VOLUME before creating a local store. An unreadable record +// is unknown (75); corrupt bytes or a mismatch are final refusals (78). +func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, numBlocks uint64, blockSize uint32, chunkBlocks uint32) (string, int) { if numBlocks == 0 { - return "", 0 // an existing store: the flags are not used - } - v, ok, err := cat.ReadVolume(ctx, volumeID) - if err != nil && chunkstore.CodeOf(err) == chunkstore.CodeRemoteUnavailable { - return fmt.Sprintf("blockvolume: the volume record of %s could not be read (%v); no local store was created; retrying", volumeID, err), exitWorkspaceRetry - } - if err != nil { - // A record that is there but does not decode stays that way: a - // permanent refusal, not a retry loop. - return fmt.Sprintf("blockvolume: the volume record of %s is unreadable (corrupt: %v); no local store was created; restore or recreate the record", volumeID, err), exitGeometryRefused - } - if !ok || (v.NumBlocks == numBlocks && v.BlockSize == blockSize) { return "", 0 } - return fmt.Sprintf("blockvolume: geometry_mismatch: --durable-blocks %d --durable-blocksize %d disagree with the volume record of %s (%d blocks of %d bytes); no local store was created; start it with the record's geometry", - numBlocks, blockSize, volumeID, v.NumBlocks, v.BlockSize), exitGeometryRefused + st, err := cat.Store(ref) + if err != nil { + return fmt.Sprintf("blockvolume: invalid volume identity: %v", err), exitGeometryRefused + } + v, found, err := st.ReadVolumeRecord(ctx) + if err != nil { + if errors.Is(err, layout.ErrMalformed) || errors.Is(err, layout.ErrCorrupt) || errors.Is(err, layout.ErrIdentity) { + return fmt.Sprintf("blockvolume: the volume record of %s is unreadable (corrupt: %v); no local store was created; restore or recreate the record", ref.Name, err), exitGeometryRefused + } + return fmt.Sprintf("blockvolume: the volume record of %s could not be read (%v); no local store was created; retrying", ref.Name, err), exitWorkspaceRetry + } + if !found { + return fmt.Sprintf("blockvolume: volume %s was not created in the store; no local store was created; retry the master CreateVolume operation", ref.Name), exitGeometryRefused + } + if v.SizeBytes == numBlocks*uint64(blockSize) && v.BlockSize == blockSize && v.ChunkBytes == uint64(chunkBlocks)*uint64(blockSize) { + return "", 0 + } + return fmt.Sprintf("blockvolume: geometry_mismatch: --durable-blocks %d --durable-blocksize %d --chunk-blocks %d disagree with the volume record of %s (%d blocks of %d bytes, chunk_bytes %d); no local store was created; start it with the record's geometry", numBlocks, blockSize, chunkBlocks, ref.Name, v.SizeBytes/uint64(v.BlockSize), v.BlockSize, v.ChunkBytes), exitGeometryRefused } // chunkHolder is how this host names itself in HEAD: / diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index 7a2f2cbe4a..b3613b8feb 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -10,6 +10,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" ) @@ -120,73 +121,53 @@ func TestChunkVolumeRootStaysInsideBase(t *testing.T) { // Before any local store is created, a geometry flag that disagrees with the // volume record is refused with a line naming both (78); a record the filer // could not deliver is refused as retryable (75), never taken as "absent"; -// a record that is there but does not decode is refused for good (78); a matching -// record, a missing record (the attach check creates it) and an existing -// store (no create geometry) are not refused. +// a record that is there but does not decode is refused for good (78); +// a missing record is also refused (78), while matching geometry proceeds. func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) { ctx := context.Background() - cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), defaultChunkPath) + + id, err := layout.NewVolumeID() if err != nil { t.Fatal(err) } - if got, code := geometryFlagsRefusal(ctx, cat, "v1", 32768, 4096); got != "" || code != 0 { - t.Fatalf("no record yet: %q, %d", got, code) - } - if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { - t.Fatal(err) - } - if got, code := geometryFlagsRefusal(ctx, cat, "v1", 65536, 4096); got != "" || code != 0 { - t.Fatalf("matching flags refused: %q, %d", got, code) - } - for _, c := range []struct { - blocks uint64 - size uint32 - }{{32768, 4096}, {65536, 512}} { - got, code := geometryFlagsRefusal(ctx, cat, "v1", c.blocks, c.size) - if code != exitGeometryRefused { - t.Fatalf("flags %d x %d: exit %d, want %d", c.blocks, c.size, code, exitGeometryRefused) - } - for _, want := range []string{"geometry_mismatch", "--durable-blocks", "65536 blocks of 4096 bytes"} { - if !strings.Contains(got, want) { - t.Fatalf("flags %d x %d: refusal %q lacks %q", c.blocks, c.size, got, want) - } - } - } - if got, code := geometryFlagsRefusal(ctx, cat, "v1", 0, 0); got != "" || code != 0 { - t.Fatalf("an existing store (no create geometry) must not be refused: %q, %d", got, code) - } - // An unreadable record: the same valid volume over a filer whose - // lookups fail. The record is read, fails, and the start is refused as - // retryable before anything is created. - failing := &lookupFailFiler{MemFiler: chunkstore.NewMemFiler()} - failCat, err := chunkstore.NewCatalog(failing, defaultChunkPath) - if err != nil { - t.Fatal(err) - } - if _, err := failCat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { - t.Fatal(err) - } - failing.fail, failing.reads = true, 0 - for _, blocks := range []uint64{32768, 65536} { // a wrong and a right flag alike - got, code := geometryFlagsRefusal(ctx, failCat, "v1", blocks, 4096) - if code != exitWorkspaceRetry || !strings.Contains(got, "the volume record of v1 could not be read") || !strings.Contains(got, "no local store was created; retrying") { - t.Fatalf("--durable-blocks %d over an unreadable record: %q, exit %d; want a retryable refusal (%d)", blocks, got, code, exitWorkspaceRetry) - } - } - if failing.reads == 0 { - t.Fatal("the unreadable-record case never read the record") - } - // A record that is there but does not decode: a permanent refusal - // (78), not a retry loop, for a wrong and a right flag alike. + ref := chunkstore.VolumeRef{Name: "v1", ID: id} mem := chunkstore.NewMemFiler() - corruptCat, err := chunkstore.NewCatalog(mem, defaultChunkPath) + blobs := &maintenanceBlobs{d: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(mem, blobs, defaultChunkPath) if err != nil { t.Fatal(err) } - if _, err := corruptCat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { + if got, code := geometryFlagsRefusal(ctx, cat, ref, 32768, 4096, 1024); code != exitGeometryRefused || !strings.Contains(got, "not created in the store") { + t.Fatal("missing VOLUME must refuse attach", got, code) + } + g := layout.Geometry{SizeBytes: 65536 * 4096, BlockSize: 4096, ChunkBytes: 1024 * 4096} + if _, err := cat.CreateVolume(ctx, ref, g); err != nil { t.Fatal(err) } - dir := path.Join(defaultChunkPath, "v1") + if got, code := geometryFlagsRefusal(ctx, cat, ref, 65536, 4096, 1024); got != "" || code != 0 { + t.Fatal(got, code) + } + for _, g := range []struct { + blocks uint64 + size, chunk uint32 + }{{32768, 4096, 1024}, {65536, 512, 1024}, {65536, 4096, 512}} { + got, code := geometryFlagsRefusal(ctx, cat, ref, g.blocks, g.size, g.chunk) + if code != exitGeometryRefused || !strings.Contains(got, "geometry_mismatch") || !strings.Contains(got, "65536 blocks of 4096 bytes") { + t.Fatalf("mismatch: %q %d", got, code) + } + } + if got, code := geometryFlagsRefusal(ctx, cat, ref, 0, 0, 0); got != "" || code != 0 { + t.Fatal(got, code) + } + failing := &lookupFailFiler{MemFiler: mem, fail: true} + failCat, err := chunkstore.NewBCatalog(failing, blobs, defaultChunkPath) + if err != nil { + t.Fatal(err) + } + if got, code := geometryFlagsRefusal(ctx, failCat, ref, 65536, 4096, 1024); code != exitWorkspaceRetry || !strings.Contains(got, "could not be read") || failing.reads == 0 { + t.Fatal(got, code, failing.reads) + } + dir := path.Join(defaultChunkPath, ref.Dir()) e, err := mem.LookupEntry(ctx, dir, "VOLUME") if err != nil { t.Fatal(err) @@ -195,12 +176,10 @@ func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) { if err := mem.UpdateEntry(ctx, dir, e, nil); err != nil { t.Fatal(err) } - for _, blocks := range []uint64{32768, 65536} { - got, code := geometryFlagsRefusal(ctx, corruptCat, "v1", blocks, 4096) - if code != exitGeometryRefused || !strings.Contains(got, "the volume record of v1 is unreadable (corrupt:") || !strings.Contains(got, "no local store was created") { - t.Fatalf("--durable-blocks %d over a corrupt record: %q, exit %d; want a permanent refusal (%d)", blocks, got, code, exitGeometryRefused) - } + if got, code := geometryFlagsRefusal(ctx, cat, ref, 65536, 4096, 1024); code != exitGeometryRefused || !strings.Contains(got, "unreadable (corrupt:") { + t.Fatal(got, code) } + } // lookupFailFiler is a MemFiler whose LookupEntry fails once fail is set; it @@ -219,32 +198,54 @@ func (f *lookupFailFiler) LookupEntry(ctx context.Context, dir, name string) (*f return f.MemFiler.LookupEntry(ctx, dir, name) } -// The attach check is the VOLUME entry's attach rules (B9 W2 §4.2): the first -// attach creates VOLUME from the local geometry, a later attach with the same -// geometry passes, and another geometry is refused. +// Attach only reads the master's identified VOLUME and HEAD. func TestChunkAttachCheckAppliesVolumeRules(t *testing.T) { ctx := context.Background() - cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), defaultChunkPath) + f := &layoutAttachFiler{MemFiler: chunkstore.NewMemFiler()} + cat, err := chunkstore.NewBCatalog(f, f, defaultChunkPath) if err != nil { t.Fatal(err) } - check := chunkAttachCheck(cat) + id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff") + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + check := chunkAttachCheck(cat, ref) g := durable.ChunkGeometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} - if err := check(ctx, "v1", g); err != nil { - t.Fatalf("first attach: %v", err) + if err := check(ctx, "v1", g); !errors.Is(err, layout.ErrMissing) { + t.Fatal("attach created a missing volume", err) } - v, ok, err := cat.ReadVolume(ctx, "v1") - if err != nil || !ok || v.Origin != chunkstore.OriginCreate || v.Geometry != (chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}) { - t.Fatalf("VOLUME after the first attach: %+v ok=%v %v", v, ok, err) + if _, found, err := cat.ReadHead(ctx, ref); err != nil || found { + t.Fatal("attach created a missing HEAD", found, err) } - if err := check(ctx, "v1", g); err != nil { - t.Fatalf("attach with the same geometry: %v", err) + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 8 * 4096}); err != nil { + t.Fatal(err) } - other := g - other.NumBlocks = 128 - if err := check(ctx, "v1", other); chunkstore.CodeOf(err) != chunkstore.CodeGeometryMismatch { - t.Fatalf("attach with another geometry: %v, want geometry_mismatch", err) + for i := 0; i < 2; i++ { + if err := check(ctx, "v1", g); err != nil { + t.Fatal(err) + } } + h, found, err := cat.ReadHead(ctx, ref) + if err != nil || !found || h.VolumeID != id || h.Epoch != 0 || h.Holder != "" || h.Current != nil { + t.Fatalf("unclaimed HEAD: %+v %v", h, err) + } + if err := check(ctx, "other", g); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("wrong name: %v", err) + } + if err := chunkAttachCheck(cat, chunkstore.VolumeRef{Name: "v1"})(ctx, "v1", g); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("missing master id: %v", err) + } + if found, err := f.LookupEntry(ctx, defaultChunkPath+"/v1", "VOLUME"); err == nil || found != nil { + t.Fatalf("legacy directory created: %v", err) + } +} + +type layoutAttachFiler struct{ *chunkstore.MemFiler } + +func (*layoutAttachFiler) Put(context.Context, []byte) (string, error) { + return "", errors.New("attach must not upload data") +} +func (*layoutAttachFiler) Get(context.Context, string) ([]byte, error) { + return nil, errors.New("attach must not read data") } // HEAD names a host as /: two servers serving the same diff --git a/seaweed-block/cmd/blockvolume/cutover_end_to_end_integration_test.go b/seaweed-block/cmd/blockvolume/cutover_end_to_end_integration_test.go new file mode 100644 index 0000000000..8be47c6af7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cutover_end_to_end_integration_test.go @@ -0,0 +1,72 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "syscall" + "testing" + "time" +) + +// TestCutoverCreateFromSnapshot pins the public master create contract: one +// request creates the target identity and its restored image together. +func TestCutoverCreateFromSnapshot(t *testing.T) { + env := startCutoverLayoutEnv(t, false) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + source := startCutoverVolume(t, env, "restore-source", "s1") + env.adopt(t, source, "s1") + env.writeBlock(t, "s1", 5, pattern("restore-seam-A!!")) + env.snapshot(t, "s1", "v1", "restore-seam") + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "restore-seam", "--target", "v2", + "--master", env.h.masterAddr) + target := startCutoverVolume(t, env, "restored-target", "n-v2") + target.waitLog(t, 60*time.Second, "blockvolume: volume v2 adopted as PRIMARY at r1@") + poll(t, 60*time.Second, "restored target never ready", func() bool { return volumeFrontendReady(env.hosts["n-v2"].status, "v2") }) + env.requireBlocks(t, "n-v2", 0, ladderLastBlock+1, map[uint64][]byte{5: pattern("restore-seam-A!!")}) +} + +// TestCutoverWriteSnapshotKillRestartRestore follows the public path through +// real binaries, a stock filer and the NVMe frontend. The guest is quiescent +// at snapshot and kill; process kill is not a power-loss durability claim. +func TestCutoverWriteSnapshotKillRestartRestore(t *testing.T) { + env := startCutoverLayoutEnv(t, false) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + source := startCutoverVolume(t, env, "source-before-kill", "s1") + env.adopt(t, source, "s1") + a, b, c := pattern("cutover-block-A!"), pattern("cutover-block-B!"), pattern("cutover-block-C!") + before := map[uint64][]byte{5: a, 2*ladderChunkBlocks + 7: b} + env.writeBlock(t, "s1", 5, a) + env.writeBlock(t, "s1", 2*ladderChunkBlocks+7, b) + env.snapshot(t, "s1", "v1", "before-kill") + // A later synced write must survive restart but must not enter the snapshot. + env.writeBlock(t, "s1", 4*ladderChunkBlocks+9, c) + source.kill(t) + if err := source.proc.Signal(syscall.Signal(0)); err == nil { + t.Fatal("the killed source process still exists") + } + restarted := startCutoverVolume(t, env, "source-after-kill", "s1") + env.adopt(t, restarted, "s1") + after := map[uint64][]byte{5: a, 2*ladderChunkBlocks + 7: b, 4*ladderChunkBlocks + 9: c} + env.requireBlocks(t, "s1", 0, ladderLastBlock+1, after) + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "before-kill", "--target", "v2", + "--master", env.h.masterAddr) + target := startCutoverVolume(t, env, "restored-target", "n-v2") + target.waitLog(t, 60*time.Second, "blockvolume: volume v2 adopted as PRIMARY at r1@") + poll(t, 60*time.Second, "restored target never ready", func() bool { return volumeFrontendReady(env.hosts["n-v2"].status, "v2") }) + env.requireBlocks(t, "n-v2", 0, ladderLastBlock+1, before) + env.requireBlocks(t, "s1", 0, ladderLastBlock+1, after) +} + +func startCutoverLayoutEnv(t *testing.T, precreateTarget bool) *handoffEnv { + t.Helper() + var tlsCfg map[string]time.Time + if procedureTLSOn() { + tlsCfg = map[string]time.Time{} + } + return startHandoffEnvConfigured(t, 1, []string{"v2"}, tlsCfg, precreateTarget) +} + +func startCutoverVolume(t *testing.T, env *handoffEnv, label, host string) *daemon { + t.Helper() + return env.h.start(t, label, env.h.volume, env.volArgs(host)...) +} diff --git a/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go index 332bb0b8ff..6c69d7656f 100644 --- a/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go +++ b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -109,9 +110,13 @@ func TestExistingDurableVolumeDisappearsDoesNotCreateFromIgnoredFlags(t *testing if _, _, err = durableCreateGeometry(f); err == nil { t.Fatal("fresh recheck accepted original overflowing count") } - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: blocks, BlockSize: bs, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { - return nil, errors.New("unexpected remote access for missing open-only volume") - }}, healthyView{}) + cfg := durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: blocks, BlockSize: bs} + if impl == durable.ImplWALStoreChunk { + unexpected := errors.New("unexpected layout access for missing open-only volume") + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return nil, unexpected } + cfg.ChunkLayoutRemoteFor = func(string, layout.HolderID) (storage.ChunkRemote, error) { return nil, unexpected } + } + p, err := durable.NewDurableProvider(cfg, healthyView{}) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/cmd/blockvolume/layout_identity_test.go b/seaweed-block/cmd/blockvolume/layout_identity_test.go new file mode 100644 index 0000000000..e011b481ed --- /dev/null +++ b/seaweed-block/cmd/blockvolume/layout_identity_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "path/filepath" + "testing" +) + +func TestBlockvolumeLayoutIdentitySelectsTheLocalRoot(t *testing.T) { + base := []string{"--master=127.0.0.1:9333", "--server-id=s1", "--volume-id=v", "--replica-id=r1", "--data-addr=127.0.0.1:19101", "--ctrl-addr=127.0.0.1:19102", "--durable-root=" + t.TempDir()} + first, err := parseFlags(append(append([]string{}, base...), "--layout-id=1234567890abcdef1234567890abcdef")) + if err != nil { + t.Fatal(err) + } + if filepath.Base(first.durableRoot) != "v-12345678" { + t.Fatal(first.durableRoot) + } + second, err := parseFlags(append(append([]string{}, base...), "--layout-id=abcdef1290abcdef1234567890abcdef")) + if err != nil || second.durableRoot == first.durableRoot { + t.Fatalf("different incarnation reused local root: %v", err) + } + if _, err := parseFlags(append(append([]string{}, base...), "--layout-id=bad")); err == nil { + t.Fatal("malformed identity accepted") + } +} diff --git a/seaweed-block/cmd/blockvolume/layout_master_fixture_test.go b/seaweed-block/cmd/blockvolume/layout_master_fixture_test.go new file mode 100644 index 0000000000..28973b1e8a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/layout_master_fixture_test.go @@ -0,0 +1,68 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// layoutMasterWriter gives an in-process master the layout writer a +// production master gets from --chunk-filer: CreateVolume writes the VOLUME +// and the unclaimed HEAD under base on the test filer before the record is +// store-ready. +func layoutMasterWriter(t *testing.T, cluster *w4WeedCluster, base string) func(context.Context, lifecycle.VolumeSpec) error { + t.Helper() + cat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{FilerGRPC: cluster.filerGRPC, AssignPath: base}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { client.Close() }) + return func(ctx context.Context, spec lifecycle.VolumeSpec) error { + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return err + } + _, err = cat.CreateVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}, layout.Geometry{ + SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes}) + return err + } +} + +// createStoreReadyVolume creates a volume through the master's public create, +// the path production uses, and requires the record to come back store-ready. +func createStoreReadyVolume(t *testing.T, h *master.Host, volume string, sizeBytes uint64) layout.VolumeID { + t.Helper() + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + resp, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: volume, SizeBytes: sizeBytes, ReplicationFactor: 1}) + if err != nil { + t.Fatalf("create %s through the master: %v", volume, err) + } + if !resp.GetStoreReady() { + t.Fatalf("create %s: the master answered store_ready=false", volume) + } + id, err := layout.ParseVolumeID(resp.GetLayoutId()) + if err != nil { + t.Fatalf("master-minted layout id %q: %v", resp.GetLayoutId(), err) + } + if rec, ok := h.Lifecycle().Volumes.GetVolume(volume); !ok || !rec.StoreReady { + t.Fatal(fmt.Sprintf("lifecycle record of %s is not store-ready after the create", volume)) + } + return id +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 8aa2d12663..71bca5ca8e 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -21,6 +21,8 @@ import ( "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/iscsi" "github.com/seaweedfs/seaweed-block/core/frontend/memback" @@ -46,6 +48,7 @@ type flags struct { masterAddr string serverID string volumeID string + layoutID string replicaID string dataAddr string ctrlAddr string @@ -186,6 +189,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.masterTLS.Key, "master-tls-key", "", "the key of --master-tls-cert (PEM)") fs.StringVar(&f.masterTLS.CA, "master-ca", "", "CA (PEM) blockmaster's certificate must verify against") fs.StringVar(&f.volumeID, "volume-id", "", "served volume (required)") + fs.StringVar(&f.layoutID, "layout-id", "", "master-minted layout identity; when set, durable-root is the base for -") fs.StringVar(&f.replicaID, "replica-id", "", "served replica (required)") fs.StringVar(&f.dataAddr, "data-addr", "", "data-path address (required)") fs.StringVar(&f.ctrlAddr, "ctrl-addr", "", "control-path address (required)") @@ -219,17 +223,14 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)") fs.StringVar(&f.durableImpl, "durable-impl", "", "LogicalStorage impl: empty (default) = auto: an existing volume opens with its on-disk format (a walstore-chunk root needs the explicit walstore-chunk selector), a new volume is created as walstore; or walstore, smartwal (experimental), opt-in parallel-walstore, or opt-in walstore-chunk (walstore published to SeaweedFS; proof of concept); ignored unless --durable-root is set") registerHostLimitFlags(fs, &f.chunk.hostLimit) - fs.StringVar(&f.chunk.filer, "chunk-filer", "", "walstore-chunk: SeaweedFS filer gRPC address host:port") - fs.StringVar(&f.chunk.path, "chunk-path", defaultChunkPath, "walstore-chunk: filer directory holding one directory per volume (HEAD and chunk key bindings)") - fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)") - fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") + chunkstore.RegisterSWFSFlags(fs, &f.chunk.filer, &f.chunk.path, &f.chunk.collection, &f.chunk.replication) fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: not supported in this release; blockvolume refuses to start when it is set") fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least "+durable.MinCaptureInterval.String()+")") f.chunk.snapshotSchedule = defaultSnapshotSchedule fs.Var(&f.chunk.snapshotSchedule, "chunk-snapshot-schedule", "walstore-chunk: scheduled snapshots, daily:N or weekly:N (once per period at a per-volume offset, the newest N kept) or off") fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables") - fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: enable scoped automatic GC; off pending restart-safe unknown-CAS settlement and density qualification") + fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: let the holder's maintenance pass remove chunks no root of the volume reaches (cleaning); off by default") fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)") fs.IntVar(&f.chunk.hydrationQueueDepth, "chunk-hydration-queue-depth", 64, "walstore-chunk: distinct queued/in-flight hydration chunks per volume (1..65536)") @@ -337,6 +338,19 @@ func parseFlags(args []string) (flags, error) { return flags{}, fmt.Errorf("--durable-wal-recovery-test-disable-flusher requires --durable-impl=walstore") } } + if f.layoutID != "" { + id, err := layout.ParseVolumeID(f.layoutID) + if err != nil { + return flags{}, fmt.Errorf("--layout-id: %w", err) + } + if f.durableRoot == "" { + return flags{}, fmt.Errorf("--layout-id requires --durable-root") + } + if err := (layout.Volume{ID: id, Name: f.volumeID, Format: layout.VolumeFormat}).CheckIdentity(); err != nil { + return flags{}, err + } + f.durableRoot = filepath.Join(f.durableRoot, layout.VolumeDir(f.volumeID, id)) + } if f.durableRoot != "" { if _, _, err := durableCreateGeometry(f); err != nil { return flags{}, err @@ -684,14 +698,16 @@ func runVolume(f flags, exits *processExit) int { // accept connections. var provider frontend.Provider var durableProv *durable.DurableProvider - var workspaceRemoteFor func(string) (storage.ChunkRemote, error) + var workspaceLayoutHead layout.HeadStore if f.durableRoot != "" { blocks, blockSize, geometryErr := durableCreateGeometry(f) + var dp *durable.DurableProvider cfg := durable.ProviderConfig{ Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, BlockSize: blockSize, NumBlocks: blocks, + ChunkBlocks: durable.DefaultChunkBlocks, WALRetentionLSNs: f.walRetentionLSNs, WALMultiBlockRecords: f.durableWALMultiBlockRecords, WALRecoveryTestDisableFlusher: f.durableWALRecoveryTestDisableFlusher, @@ -710,7 +726,6 @@ func runVolume(f flags, exits *processExit) int { cfg.ChunkCutTimeout = defaultChunkCutTimeout cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout - cfg.ChunkMaintenance = chunk.maintenance if f.workspaceLease { // The startup wait does not run out while the master gives no // reply; it ends 30 s after the first reply received after the @@ -721,9 +736,21 @@ func runVolume(f flags, exits *processExit) int { return deadline, final != "" } } - if chunk.catalog != nil && f.chunk.snapshotSchedule.period > 0 { + if chunk.bCatalog != nil && f.chunk.snapshotSchedule.period > 0 { cfg.ChunkSnapshotPeriod = f.chunk.snapshotSchedule.period - cfg.ChunkScheduledSnapshot = volume.ScheduledSnapshot(chunk.catalog, f.chunk.snapshotSchedule.keep) + cfg.ChunkScheduledSnapshot = volume.ScheduledSnapshot(func(ctx context.Context, name, snapshot string, meta layout.SnapshotMeta) (chunkstore.SnapshotInfo, error) { + p, ok := any(dp).(interface { + SnapshotVolume(context.Context, string, string, layout.SnapshotMeta) (layout.Head, error) + }) + if !ok { + return chunkstore.SnapshotInfo{}, errors.New("chunk snapshot data path is not configured") + } + h, err := p.SnapshotVolume(ctx, name, snapshot, meta) + if err != nil { + return chunkstore.SnapshotInfo{}, err + } + return chunkstore.SnapshotInfoFromHead(name, snapshot, h), nil + }, f.chunk.snapshotSchedule.keep) } cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency @@ -752,18 +779,49 @@ func runVolume(f flags, exits *processExit) int { cfg.OnChunkDetach = h.WorkspaceStopPending cfg.OnChunkDetachResumed = h.WorkspaceStopResumed if chunkErr == nil { - cfg.ChunkRemoteFor = chunk.remoteFor - workspaceRemoteFor = chunk.remoteFor - cfg.ChunkAttachCheck = chunkAttachCheck(chunk.catalog) + + layoutID, _ := layout.ParseVolumeID(f.layoutID) // parseFlags validates a supplied id + ref := chunkstore.VolumeRef{Name: f.volumeID, ID: layoutID} + cfg.ChunkAttachCheck = chunkAttachCheck(chunk.bCatalog, ref) + cfg.ChunkLayoutHeadFor = func(name string) (layout.StartStore, error) { + if name != ref.Name { + return nil, layout.ErrIdentity + } + return chunk.bCatalog.Store(ref) + } + cfg.ChunkLayoutRemoteFor = func(name string, me layout.HolderID) (storage.ChunkRemote, error) { + if name != ref.Name { + return nil, layout.ErrIdentity + } + return chunkstore.NewLayoutRemote(chunk.bCatalog, ref, me) + } + workspaceLayoutHead, chunkErr = chunk.bCatalog.Store(ref) + // The holder identity comes from Start (until it is wired, the + // pass retains and does not clean). + cfg.ChunkMaintenance = newChunkMaintenance(chunk.bCatalog, ref, func(ctx context.Context) (layoutCleaner, error) { + if dp == nil { + return nil, errNoLayoutHolder + } + r, err := dp.LayoutRemote(ctx, f.volumeID) + if err != nil { + return nil, fmt.Errorf("%w: %w", errNoLayoutHolder, err) + } + c, ok := r.(layoutCleaner) + if !ok { + return nil, fmt.Errorf("%w: the attachment's remote (%T) cannot clean", errNoLayoutHolder, r) + } + return c, nil + }, f.chunk.automaticGC, time.Now) defer chunk.close() } } // Only a store about to be created takes its geometry from the flags; // an existing store opens with its own (blocks == 0), and a mismatch // between it and the record is the attach check's. - if chunkErr == nil && geometryErr == nil && blocks != 0 && chunk.catalog != nil { + if chunkErr == nil && geometryErr == nil && blocks != 0 && chunk.bCatalog != nil { readCtx, readCancel := context.WithTimeout(context.Background(), 10*time.Second) - refusal, code := geometryFlagsRefusal(readCtx, chunk.catalog, f.volumeID, uint64(blocks), uint32(blockSize)) + layoutID, _ := layout.ParseVolumeID(f.layoutID) + refusal, code := geometryFlagsRefusal(readCtx, chunk.bCatalog, chunkstore.VolumeRef{Name: f.volumeID, ID: layoutID}, uint64(blocks), uint32(blockSize), cfg.ChunkBlocks) readCancel() if refusal != "" { fmt.Fprintln(os.Stderr, refusal) @@ -776,7 +834,6 @@ func runVolume(f flags, exits *processExit) int { return code } } - var dp *durable.DurableProvider err := geometryErr if err == nil { dp, err = durable.NewDurableProvider(cfg, h.ProjectionView()) @@ -805,8 +862,9 @@ func runVolume(f flags, exits *processExit) int { provider = dp if status != nil { status.SetDurableStatusSource(dp) - if f.chunk.controlEndpoint && chunk.catalog != nil { - status.SetChunkControl(volume.NewChunkControl(dp, chunk.catalog)) + if f.chunk.controlEndpoint && chunk.bCatalog != nil { + layoutID, _ := layout.ParseVolumeID(f.layoutID) + status.SetChunkControl(volume.NewChunkControl(dp, chunk.bCatalog, chunkstore.VolumeRef{Name: f.volumeID, ID: layoutID})) } } @@ -1399,6 +1457,16 @@ func runVolume(f flags, exits *processExit) int { if replVolume != nil { drainErr = errors.Join(drainErr, replVolume.Close()) } + // A detached HEAD is stable until a higher grant. Read it while the + // attachment identity is still available, then ACK only after Close succeeds. + var detachedGen uint64 + if leaseStop != nil && drainErr == nil && workspaceLayoutHead != nil { + var me layout.HolderID + me, drainErr = durableProv.LayoutHolder(leaseStop.ctx, leaseStop.id.VolumeId) + if drainErr == nil { + detachedGen, drainErr = workspaceLayoutDetachedGeneration(leaseStop.ctx, workspaceLayoutHead, leaseStop.id, me) + } + } // T3b: close DurableProvider in correct order — Provider.Close // closes backends first (flags them closed) then storage files // (releases fd + final fsync). @@ -1411,9 +1479,9 @@ func runVolume(f flags, exits *processExit) int { shutCancel() } if leaseStop != nil { - gen := uint64(0) - if drainErr == nil { - gen, drainErr = workspaceDetachedGeneration(leaseStop.ctx, workspaceRemoteFor, leaseStop.id, chunkHolder(f)) + gen := detachedGen + if drainErr == nil && workspaceLayoutHead == nil { + drainErr = errors.New("workspace layout HEAD unavailable for detached proof") } leaseStop.reply <- workspaceStopResult{gen: gen, err: drainErr} } diff --git a/seaweed-block/cmd/blockvolume/nvme_witness_integration_test.go b/seaweed-block/cmd/blockvolume/nvme_witness_integration_test.go new file mode 100644 index 0000000000..fc06c7ab9e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/nvme_witness_integration_test.go @@ -0,0 +1,160 @@ +//go:build linux && subprocess && chunkstore_integration + +// The NVMe/TCP witness client of the real-binary tests: connect, write with +// a flush, read back exactly. +package main_test + +import ( + "bytes" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +// This small initiator uses the same exported wire types and admin/IO queue +// handshake as core/frontend/nvme/client_support_test.go. It talks only to the +// real blockvolume in this harness; no kernel device or unrelated NQN is used. +type gap1NVMe struct { + admin, io net.Conn + r *nvme.Reader + w *nvme.Writer + cid uint16 +} + +func gap1ConnectNVMe(t *testing.T, addr, nqn string) *gap1NVMe { + t.Helper() + c := &gap1NVMe{} + t.Cleanup(c.close) + var controller uint16 = 0xffff + for q := uint16(0); q < 2; q++ { + conn, err := net.DialTimeout("tcp", addr, 5*time.Second) + if err != nil { + t.Fatal(err) + } + if q == 0 { + c.admin = conn + } else { + c.io = conn + } + _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) + r, w := nvme.NewReader(conn), nvme.NewWriter(conn) + if err := w.SendHeaderOnly(0, &nvme.ICRequest{PDUFormatVersion: 0, PDUMaxR2T: 1}, 120); err != nil { + t.Fatal(err) + } + h, err := r.Dequeue() + if err != nil || h.Type != 1 { + t.Fatalf("NVMe IC response: %+v %v", h, err) + } + var ic nvme.ICResponse + if err := r.Receive(&ic); err != nil { + t.Fatal(err) + } + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 0x7f, FCType: 1, CID: c.cid, D10: uint32(q) << 16} + data := make([]byte, 1024) + (&nvme.ConnectData{HostID: [16]byte{1, 2, 3, 4}, CNTLID: controller, SubNQN: nqn, HostNQN: "nqn.2026-11.test:gap1-host"}).Marshal(data) + if err := w.SendWithData(4, 0, &cmd, 64, data); err != nil { + t.Fatal(err) + } + reply := gap1NVMeReply(t, r, c.cid) + if q == 0 { + controller = uint16(reply.DW0) + if controller == 0 { + t.Fatal("no controller assigned") + } + } + if q == 1 { + c.r, c.w = r, w + } + } + return c +} + +func (c *gap1NVMe) close() { + if c.io != nil { + _ = c.io.Close() + } + if c.admin != nil { + _ = c.admin.Close() + } +} + +func gap1NVMeReply(t *testing.T, r *nvme.Reader, cid uint16) nvme.CapsuleResponse { + t.Helper() + h, err := r.Dequeue() + if err != nil || h.Type != 5 { + t.Fatalf("NVMe capsule header: %+v %v", h, err) + } + var reply nvme.CapsuleResponse + if err := r.Receive(&reply); err != nil { + t.Fatal(err) + } + if reply.CID != cid || reply.Status != 0 { + t.Fatalf("NVMe CID %d: %+v", cid, reply) + } + return reply +} + +func (c *gap1NVMe) writeFlush(t *testing.T, lba uint64, payload []byte) { + t.Helper() + if len(payload) != 4096 { + t.Fatal("harness writes exactly one block") + } + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 1, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)} + if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil { + t.Fatal(err) + } + h, err := c.r.Dequeue() + if err != nil || h.Type != 9 { + t.Fatalf("NVMe R2T: %+v %v", h, err) + } + var r2t nvme.R2THeader + if err := c.r.Receive(&r2t); err != nil { + t.Fatal(err) + } + if r2t.CCCID != c.cid || r2t.DATAO != 0 || r2t.DATAL != uint32(len(payload)) { + t.Fatalf("wrong R2T %+v", r2t) + } + data := nvme.H2CDataHeader{CCCID: c.cid, TAG: r2t.TAG, DATAO: 0, DATAL: uint32(len(payload))} + if err := c.w.SendWithData(6, 0, &data, 16, payload); err != nil { + t.Fatal(err) + } + gap1NVMeReply(t, c.r, c.cid) + c.cid++ + flush := nvme.CapsuleCommand{OpCode: 0, CID: c.cid, NSID: 1} + if err := c.w.SendHeaderOnly(4, &flush, 64); err != nil { + t.Fatal(err) + } + gap1NVMeReply(t, c.r, c.cid) // only this completed Flush makes the record durable +} + +func (c *gap1NVMe) readExact(t *testing.T, lba uint64, want []byte) { + t.Helper() + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 2, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)} + if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil { + t.Fatal(err) + } + h, err := c.r.Dequeue() + if err != nil || h.Type != 7 { + t.Fatalf("NVMe read data: %+v %v", h, err) + } + var header nvme.C2HDataHeader + if err := c.r.Receive(&header); err != nil { + t.Fatal(err) + } + if header.CCCID != c.cid || header.DATAO != 0 || header.DATAL != uint32(len(want)) || c.r.Length() != uint32(len(want)) { + t.Fatalf("wrong read frame %+v length%d", header, c.r.Length()) + } + got := make([]byte, c.r.Length()) + if err := c.r.ReceiveData(got); err != nil { + t.Fatal(err) + } + gap1NVMeReply(t, c.r, c.cid) + if !bytes.Equal(got, want) { + t.Fatal("fsync-acknowledged NVMe record changed after supervised restart") + } +} diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go index c47da75939..938d736167 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go @@ -103,6 +103,51 @@ func sealedHeadLSN(out string, e, g uint64) (uint64, error) { return h.RemoteLSN, nil } +// The layout HEAD exposes the committed position and the master-minted +// holder identity. The old storage HEAD's DetachedBy proof is not a field of +// this format; a detached layout HEAD itself is the committed stop image. +type layoutHeadRecord struct { + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + ClaimID string `json:"claimID"` + Position uint64 `json:"position"` + State string `json:"state"` + Current json.RawMessage `json:"current"` +} + +func parseLayoutHead(out string) (layoutHeadRecord, error) { + var shown struct { + Head *layoutHeadRecord `json:"head"` + } + if err := json.Unmarshal([]byte(out), &shown); err != nil || shown.Head == nil { + return layoutHeadRecord{}, fmt.Errorf("layout show stdout has no head: %v: %q", err, out) + } + return *shown.Head, nil +} + +func sealedLayoutHeadPosition(out string, epoch, gen uint64) (uint64, error) { + h, err := parseLayoutHead(out) + if err != nil { + return 0, err + } + if h.Gen != gen || h.Epoch != epoch || h.Holder != "s1/r1" || h.ClaimID == "" || h.State != "detached" || len(h.Current) == 0 || string(h.Current) == "null" { + return 0, fmt.Errorf("layout HEAD after seal %+v; want committed detached image at gen %d epoch %d holder s1/r1", h, gen, epoch) + } + return h.Position, nil +} + +func checkLayoutHeadReopened(out string, epoch, sealedGen, position uint64) error { + h, err := parseLayoutHead(out) + if err != nil { + return err + } + if h.Gen <= sealedGen || h.Epoch != epoch || h.Holder != "s1/r1" || h.ClaimID == "" || h.State != "" || h.Position != position || len(h.Current) == 0 || string(h.Current) == "null" { + return fmt.Errorf("layout HEAD after claim %+v; want live image above gen %d at epoch %d position %d holder s1/r1", h, sealedGen, epoch, position) + } + return nil +} + func checkRevoke(out string, e, g uint64) error { if !strings.HasPrefix(out, fmt.Sprintf("revocation requested: volume v1 holder r1@%d expiry_ns ", e)) { return fmt.Errorf("revoke stdout %q", out) diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index f59ac9ef37..0b84820d0e 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -22,6 +22,9 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "google.golang.org/grpc" ) // TestStandalonePlannedHandoffToTheSameHost runs the planned hand-over back @@ -39,7 +42,6 @@ func TestStandalonePlannedHandoffToTheSameHost(t *testing.T) { // 4. blockvolume adopts the volume. vol1 := h.start(t, "blockvolume-1", h.volume, volArgs...) e := mustU(adoptedEpoch(vol1.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@"))) - vol1.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in") h.waitPrimary(t, e) // 5. The lease. @@ -59,9 +61,9 @@ func TestStandalonePlannedHandoffToTheSameHost(t *testing.T) { g := mustU(sealedGen(out, errOut, e)) // 9. The seal is in the object store. - chunkShow := []string{"ops", "chunk", "show", "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath} + chunkShow := []string{"ops", "chunk", "show", "--master", h.masterAddr, "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath} out, _ = h.command(t, chunkShow...) - l := mustU(sealedHeadLSN(out, e, g)) + l := mustU(sealedLayoutHeadPosition(out, e, g)) // 10. Revoke with the sealed generation. out, _ = h.command(t, "ops", "workspace", "revoke", "--master", h.masterAddr, "--volume", "v1", "--replica", "r1", @@ -99,8 +101,6 @@ func TestStandalonePlannedHandoffToTheSameHost(t *testing.T) { // 14. Start again with the same root, within the new lease (30 s). vol2 := h.start(t, "blockvolume-2", h.volume, volArgs...) - vol2.waitLog(t, 60*time.Second, fmt.Sprintf(`durable: HEAD claim for volume=v1 starting: target epoch=%d holder="s1/r1"`, e2)) - must(checkClaimDone(vol2.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2)) vol2.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume v1 adopted as PRIMARY at r1@%d", e2)) for _, bad := range []string{"refusing to attach volume=v1", "assignment unavailable, not serving"} { if vol2.has(bad) { @@ -115,7 +115,7 @@ func TestStandalonePlannedHandoffToTheSameHost(t *testing.T) { // 16. The new epoch claimed HEAD. out, _ = h.command(t, chunkShow...) - must(checkHeadReopened(out, e2, g, l)) + must(checkLayoutHeadReopened(out, e2, g, l)) // 17. The block written before the hand-over reads back unchanged. c = dialNVMe(t, h.nvmeAddr, nqn) @@ -143,8 +143,8 @@ func TestStandaloneCleanMoveWithoutTheACKIsRefused(t *testing.T) { c.close() out, errOut := h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", h.statusAddr, "--timeout", "120s") g := mustU(sealedGen(out, errOut, e)) - out, _ = h.command(t, "ops", "chunk", "show", "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath) - mustU(sealedHeadLSN(out, e, g)) // HEAD is sealed: only the ACK is missing + out, _ = h.command(t, "ops", "chunk", "show", "--master", h.masterAddr, "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath) + mustU(sealedLayoutHeadPosition(out, e, g)) // HEAD is sealed: only the ACK is missing vol.kill(t) out, _ = h.command(t, "ops", "workspace", "revoke", "--master", h.masterAddr, "--volume", "v1", "--replica", "r1", @@ -185,6 +185,8 @@ type handoffEnv struct { // A crash test restarts exactly this owned master with the same stores. masterProcess *daemon masterArgs []string + layoutMu sync.Mutex + layoutIDs map[string]string // tls, when set, runs every process with mutual TLS (procedure_tls_harness_test.go). tls *procedureTLS } @@ -223,6 +225,13 @@ func startHandoffEnvWith(t *testing.T, n int, targets []string, masterArgs ...st // startHandoffEnvTLS is startHandoffEnvWith with mutual TLS when tlsNotAfter // is non-nil (it overrides chosen node certificates' expiry). func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[string]time.Time, masterArgs ...string) *handoffEnv { + return startHandoffEnvConfigured(t, n, targets, tlsNotAfter, true, masterArgs...) +} + +// startHandoffEnvConfigured can reserve target placement without importing a +// VolumeRecord. The restore-create test uses that form so the master creates +// the target's identity and restored image in one request. +func startHandoffEnvConfigured(t *testing.T, n int, targets []string, tlsNotAfter map[string]time.Time, precreateTargets bool, masterArgs ...string) *handoffEnv { t.Helper() h := newPlannedHandoffHarness(t) env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/handoff-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}} @@ -252,16 +261,20 @@ func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[s node := func(b bvHost) { fmt.Fprintf(&nodes, " - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", b.id, b.data, b.ctrl) } - volume := func(v, server string) { - fmt.Fprintf(&volumes, " - id: %s\n size_bytes: 268435456\n replication_factor: 1\n placements:\n - server_id: %s\n replica_id: r1\n", v, server) + volume := func(v, server string, create bool) { + size := "" + if create { + size = " size_bytes: 268435456\n" + } + fmt.Fprintf(&volumes, " - id: %s\n%s replication_factor: 1\n placements:\n - server_id: %s\n replica_id: r1\n", v, size, server) } for i := 1; i <= n; i++ { node(env.hosts[fmt.Sprintf("s%d", i)]) } - volume("v1", "s1") + volume("v1", "s1", true) for _, v := range targets { node(env.hosts["n-"+v]) - volume(v, "n-"+v) + volume(v, "n-"+v, precreateTargets) } spec := filepath.Join(h.dir, "cluster-spec.yaml") must(os.WriteFile(spec, []byte("nodes:\n"+nodes.String()+"volumes:\n"+volumes.String()), 0o644)) @@ -272,6 +285,7 @@ func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[s "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), "--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, "--workspace-rpc", "--workspace-head-base-url", "http://" + cluster.filerHTTP + chunkPath}, masterArgs...) + env.masterArgs = append(env.masterArgs, "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath) master := h.start(t, "blockmaster", h.master, env.masterArgs...) env.masterProcess = master if l := master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded="); !strings.Contains(l, "listen="+h.masterAddr) { @@ -285,12 +299,44 @@ func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[s env.show = []string{"ops", "workspace", "show", "--master", h.masterAddr, "--volume", "v1"} out, _ := h.command(t, env.show...) must(checkShowBeforeStart(out)) + // Cache the identities imported by the master while it is available. Some + // tests assemble restart arguments after deliberately stopping the master. + env.layoutIDs = make(map[string]string) + env.layoutID("v1") + if precreateTargets { + for _, v := range targets { + env.layoutID(v) + } + } return env } // volArgs is the chapter's blockvolume command for one host. func (env *handoffEnv) volArgs(id string) []string { return env.volArgsFor(env.hosts[id]) } +func (env *handoffEnv) layoutID(volume string) string { + t := env.h.t + t.Helper() + env.layoutMu.Lock() + defer env.layoutMu.Unlock() + if id := env.layoutIDs[volume]; id != "" { + return id + } + conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, "admin")) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + id, err := lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume) + if err != nil { + t.Fatalf("resolve layout identity for %s: %v", volume, err) + } + env.layoutIDs[volume] = id.String() + return id.String() +} + // volArgsFor is the chapter's blockvolume command for b. The default // scheduled snapshot (daily:7, at a per-volume offset) stays on, as the page // says; a snapshot inside a test could only make a test fail, never pass. @@ -308,6 +354,7 @@ func (env *handoffEnv) volArgsFor(b bvHost) []string { replica = "r1" } return append([]string{"--volume-lock-dir-test-only", lockDir, "--master", env.h.masterAddr, "--server-id", server, "--volume-id", vol, "--replica-id", replica, + "--layout-id", env.layoutID(vol), "--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status, "--durable-root", b.root, "--durable-impl", "walstore-chunk", "--durable-blocks", "65536", "--durable-blocksize", "4096", diff --git a/seaweed-block/cmd/blockvolume/procedure_plain_detach_crash_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_plain_detach_crash_integration_test.go index 9433cb7c88..d4d681de15 100644 --- a/seaweed-block/cmd/blockvolume/procedure_plain_detach_crash_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_plain_detach_crash_integration_test.go @@ -12,7 +12,7 @@ import ( "testing" "time" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) // P12.6 / INV-WS-SEAL-REPLAY-001: a SIGKILL during plain-seal upload @@ -114,10 +114,9 @@ func TestProcedureKillDuringPlainDetachThenCompleteHandoff(t *testing.T) { verified, _ := env.h.command(t, "ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "60s", "--bytes-per-sec", "0") - var result chunkstore.VerifyResult + var result layout.VerifyResult if err := json.Unmarshal([]byte(verified), &result); err != nil || !result.Complete || - result.Depth != chunkstore.VerifyData || len(result.Findings) != 0 || result.ChunksNotRead != 0 || - result.DistinctChunksRead == 0 { + len(result.Findings) != 0 || result.Chunks == 0 { t.Fatalf("post-move data verify incomplete or corrupt: %s: %v", verified, err) } } diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go index 2a0a0bb49c..7559846027 100644 --- a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -5,6 +5,8 @@ import ( "context" "errors" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/host/volume" control "github.com/seaweedfs/seaweed-block/core/rpc/control" @@ -267,14 +269,13 @@ func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) { t.Fatalf("startup overrode the pending real drain: %+v", out) default: } - remote := storage.NewMemChunkRemote() - _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Epoch: 1, Holder: "s/r", Gen: 1}}) - if err != nil { - t.Fatal(err) - } - gen, err := workspaceDetachedGeneration(ctx, func(string) (storage.ChunkRemote, error) { return remote, nil }, request.id, "s/r") - if err != nil { - t.Fatal(err) + // The real proof reader supplies the generation to the real lease + // worker; a constant here would not join the two safety checks. + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + st := layoutProofStore{h: layout.Head{Gen: 1, Epoch: 1, Holder: "s/r", ClaimID: "k", State: layout.StateDetached, Activity: layout.Activity{Kind: layout.ActIdle}}, found: true} + gen, proofErr := workspaceLayoutDetachedGeneration(request.ctx, st, request.id, me) + if proofErr != nil { + t.Fatal(proofErr) } request.reply <- workspaceStopResult{gen: gen} finishWorkspaceLease(e, f, h, leaseDone) @@ -295,84 +296,132 @@ func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) { // The real provider must carry the claim's filer proof to the process owner, // even when the master stream has never reported another replica. -type claimExitView struct{ assigned atomic.Bool } +type claimExitView struct { + assigned atomic.Bool + epoch uint64 +} func (v *claimExitView) Projection() frontend.Projection { if !v.assigned.Load() { return frontend.Projection{VolumeID: "v"} } - return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true} + epoch := v.epoch + if epoch == 0 { + epoch = 1 + } + return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: epoch, Healthy: true} } + +// A layout HEAD held by another server at the granted epoch is a final +// refusal. The master has not delivered a newer foreign assignment, so the +// process must derive its exit from the provider's observed HEAD. func TestWorkspaceForeignHeadClaimChoosesNoRetry(t *testing.T) { - for _, deferred := range []bool{false, true} { - for _, tc := range []struct { - name, holder string - want int - }{ - {"foreign holder", "other", 78}, {"same holder higher epoch", "r", 75}, - } { - t.Run(tc.name+map[bool]string{false: "/immediate", true: "/waiting"}[deferred], func(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - h, _ := exitAuthorityHost(t) - remote := storage.NewMemChunkRemote() - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: tc.holder, State: storage.ChunkHeadActive}); err != nil { - t.Fatal(err) - } - view := &claimExitView{} - view.assigned.Store(!deferred) - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := p.Close(); err != nil { - t.Error(err) - } - }) - if _, err = p.EnsureStorage("v"); err != nil { - t.Fatal(err) - } - _, err = p.RecoverVolume(ctx, "v") - if deferred { - if err != nil { - t.Fatal(err) - } - view.assigned.Store(true) - } else if !errors.Is(err, storage.ErrChunkLayerFenced) { - t.Fatalf("claim refusal=%v", err) - } - select { - case <-p.ChunkStartupUpdates(): - case <-ctx.Done(): - t.Fatal(ctx.Err()) - } - if h.LastOtherLine() != nil { - t.Fatal("fixture unexpectedly supplied master supersede evidence") - } - e := newProcessExit(ctx) - if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { - t.Fatal("claim refusal did not select an exit") - } - select { - case out := <-e.decision: - if out.code != tc.want { - t.Fatalf("claim exit=%+v want %d", out, tc.want) - } - case <-ctx.Done(): - t.Fatal(ctx.Err()) - } - head, err := remote.GetHead(ctx) - if err != nil || head.Gen != 1 || head.Holder != tc.holder || remote.Puts() != 0 { - t.Fatalf("refused claim mutated remote: %+v puts=%d err=%v", head, remote.Puts(), err) - } - for _, status := range p.DurableStatuses() { - if status.Operational { - t.Fatal("refused claim became operational") - } - } - }) + for _, tc := range []struct { + name string + headEpoch uint64 + grantEpoch uint64 + deferred bool + wantExit bool + }{ + {"foreign holder at granted epoch", 1, 1, false, true}, + {"foreign holder above granted epoch", 2, 1, false, true}, + {"foreign holder after assignment", 1, 1, true, true}, + {"foreign holder below granted epoch", 1, 2, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + testWorkspaceLayoutForeignClaimExit(t, tc.headEpoch, tc.grantEpoch, tc.deferred, tc.wantExit) + }) + } +} + +func testWorkspaceLayoutForeignClaimExit(t *testing.T, headEpoch, grantEpoch uint64, deferred, wantExit bool) { + t.Helper() + ctx := context.Background() + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v", ID: id} + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &maintenanceBlobs{d: map[string][]byte{}}, "/exit-layout") + if err != nil { + t.Fatal(err) + } + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + st, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } + foreign, found, err := st.ReadHead(ctx) + if err != nil || !found { + t.Fatalf("initial HEAD: found=%v err=%v", found, err) + } + foreign.Epoch, foreign.Holder, foreign.ClaimID = headEpoch, "other/r", "other-claim" + if err := st.UpdateHead(ctx, foreign.Gen, foreign); err != nil { + t.Fatal(err) + } + foreign, _, err = st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + view := &claimExitView{epoch: grantEpoch} + view.assigned.Store(!deferred) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + }, + } + p, err := durable.NewDurableProvider(cfg, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + _, err = p.RecoverVolume(ctx, "v") + if deferred { + if err != nil { + t.Fatalf("recovery before assignment: %v", err) } + view.assigned.Store(true) + select { + case <-p.ChunkStartupUpdates(): + case <-time.After(3 * time.Second): + t.Fatal("foreign layout HEAD did not end deferred startup") + } + } else if wantExit && !errors.Is(err, layout.ErrNotHolder) && !errors.Is(err, layout.ErrStaleEpoch) { + t.Fatalf("layout Start refusal: %v; want not-holder or stale-epoch", err) + } + if !wantExit { + if err != nil { + t.Fatalf("newer grant did not claim: %v", err) + } + if _, ended := p.ChunkStartupOutcome("v"); ended { + t.Fatal("newer grant ended startup") + } + claimed, _, err := st.ReadHead(ctx) + if err != nil || claimed.Epoch != grantEpoch || claimed.Holder != "s/r" || claimed.Gen <= foreign.Gen { + t.Fatalf("newer grant did not claim HEAD: %+v err=%v", claimed, err) + } + return + } + if _, ended := p.ChunkStartupOutcome("v"); !ended { + t.Fatal("foreign layout HEAD did not end startup") + } + h, _ := exitAuthorityHost(t) + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { + t.Fatal("foreign layout HEAD did not select an exit") + } + if out := <-e.decision; out.code != 78 { + t.Fatalf("foreign layout HEAD chose %+v; want 78", out) + } + after, _, err := st.ReadHead(ctx) + if err != nil || after.Gen != foreign.Gen || after.Holder != foreign.Holder || after.ClaimID != foreign.ClaimID { + t.Fatalf("refused Start changed HEAD: before=%+v after=%+v err=%v", foreign, after, err) } } @@ -385,12 +434,34 @@ func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) { defer cancel() h, _ := exitAuthorityHost(t) root := t.TempDir() - remote := storage.NewMemChunkRemote() + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v", ID: id} + blobs := &maintenanceBlobs{d: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), blobs, "/exit-layout") + if err != nil { + t.Fatal(err) + } + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + st, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } view := &claimExitView{} view.assigned.Store(true) open := func() *durable.DurableProvider { t.Helper() - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + }, + } + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } @@ -414,11 +485,13 @@ func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) { if err := first.Close(); err != nil { t.Fatal(err) } - before, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) + before, found, err := st.ReadHead(ctx) + if err != nil || !found { + t.Fatalf("claimed layout HEAD: found=%v err=%v", found, err) } - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: before.Gen, Epoch: before.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "other", State: storage.ChunkHeadActive}); err != nil { + foreign := before + foreign.Epoch, foreign.Holder, foreign.ClaimID = 2, "other/r", "other-claim" + if err := st.UpdateHead(ctx, before.Gen, foreign); err != nil { t.Fatal(err) } view.assigned.Store(!deferred) @@ -434,7 +507,7 @@ func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) { case <-ctx.Done(): t.Fatal(ctx.Err()) } - } else if !errors.Is(err, storage.ErrChunkLayerFenced) { + } else if !errors.Is(err, layout.ErrStaleEpoch) { t.Fatalf("old root refusal=%v", err) } e := newProcessExit(ctx) @@ -447,94 +520,118 @@ func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) { if got, err := second.LogicalStorage("v").Read(0); err != nil || !bytes.Equal(got, want) { t.Fatalf("refusal lost local acknowledged bytes: %v", err) } - after, err := remote.GetHead(ctx) - if err != nil || after.Gen != before.Gen+1 || after.Holder != "other" || remote.Puts() != 0 { - t.Fatalf("refusal mutated HEAD/payload: %+v puts=%d err=%v", after, remote.Puts(), err) + after, found, err := st.ReadHead(ctx) + if err != nil || !found || after.Gen != before.Gen+1 || after.Holder != "other/r" || after.ClaimID != "other-claim" || blobs.n != 0 { + t.Fatalf("refusal mutated HEAD/payload: %+v found=%v puts=%d err=%v", after, found, blobs.n, err) } }) } } -// The real claim reads E1/A; a late E2/C wins before E3/B's CAS. -// The displaced HEAD is a fence for this attempt, not proof E3 was superseded. -type displacedClaimExitRemote struct { - storage.ChunkRemote - epoch uint64 - raced bool -} - -func (r *displacedClaimExitRemote) CASHead(ctx context.Context, prev storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { - if !r.raced { - r.raced = true - late := storage.ChunkHead{Epoch: r.epoch, Holder: "C", State: storage.ChunkHeadActive} - if _, err := r.ChunkRemote.CASHead(ctx, prev, late); err != nil { - return 0, err - } - } - return r.ChunkRemote.CASHead(ctx, prev, next) -} - type displacedClaimExitView struct{} func (displacedClaimExitView) Projection() frontend.Projection { return frontend.Projection{VolumeID: "v", ReplicaID: "B", Epoch: 3, Healthy: true} } + +type displacedLayoutClaimStore struct { + layout.StartStore + epoch uint64 + raced bool +} + +func (s *displacedLayoutClaimStore) UpdateHead(ctx context.Context, expected uint64, next layout.Head) error { + if !s.raced { + s.raced = true + current, found, err := s.StartStore.ReadHead(ctx) + if err != nil || !found { + return errors.New("racing layout HEAD unavailable") + } + late := current + late.Epoch, late.Holder, late.ClaimID = s.epoch, "C", "late-claim" + if err := s.StartStore.UpdateHead(ctx, current.Gen, late); err != nil { + return err + } + } + return s.StartStore.UpdateHead(ctx, expected, next) +} + +// The claim's conditional update loses to another holder. A re-read at or +// above the grant proves a final exit; below it, a new Start can claim. func TestWorkspaceDisplacedClaimUsesAssignedEpoch(t *testing.T) { for _, tc := range []struct { name string epoch uint64 - want int + final bool }{ - {"late lower epoch", 2, 75}, {"equal epoch foreign holder", 3, 78}, {"higher epoch foreign holder", 4, 78}, + {"late lower epoch", 2, false}, + {"equal epoch foreign holder", 3, true}, + {"higher epoch foreign holder", 4, true}, } { t.Run(tc.name, func(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - h, _ := exitAuthorityHost(t) - base := storage.NewMemChunkRemote() - if _, err := base.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "A", State: storage.ChunkHeadActive}); err != nil { - t.Fatal(err) - } - remote := &displacedClaimExitRemote{ChunkRemote: base, epoch: tc.epoch} - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, displacedClaimExitView{}) + id, err := layout.NewVolumeID() if err != nil { t.Fatal(err) } - t.Cleanup(func() { - if err := p.Close(); err != nil { - t.Error(err) - } - }) - if _, err = p.EnsureStorage("v"); err != nil { + ref := chunkstore.VolumeRef{Name: "v", ID: id} + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &maintenanceBlobs{d: map[string][]byte{}}, "/exit-layout") + if err != nil { t.Fatal(err) } - if _, err = p.RecoverVolume(ctx, "v"); !errors.Is(err, storage.ErrChunkLayerFenced) { - t.Fatalf("claim error=%v", err) + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) } - if !remote.raced { - t.Fatal("controlled CAS did not run") + base, err := cat.Store(ref) + if err != nil { + t.Fatal(err) } - e := newProcessExit(ctx) - if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { - t.Fatal("fenced claim did not choose an exit") + initial, found, err := base.ReadHead(ctx) + if err != nil || !found { + t.Fatalf("initial HEAD: found=%v err=%v", found, err) } - select { - case out := <-e.decision: - if out.code != tc.want { - t.Fatalf("displaced E%d/C at assigned E3/B chose %+v, want %d", tc.epoch, out, tc.want) + initial.Epoch, initial.Holder, initial.ClaimID = 1, "A", "first-claim" + if err := base.UpdateHead(ctx, initial.Gen, initial); err != nil { + t.Fatal(err) + } + store := &displacedLayoutClaimStore{StartStore: base, epoch: tc.epoch} + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "B", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return store, nil }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + }, + } + p, err := durable.NewDurableProvider(cfg, displacedClaimExitView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "v"); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("claim race: %v; want HEAD precondition", err) + } + if !store.raced { + t.Fatal("controlled HEAD race did not run") + } + if tc.final { + h, _ := exitAuthorityHost(t) + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { + t.Fatal("displaced layout claim did not choose an exit") } - case <-ctx.Done(): - t.Fatal(ctx.Err()) - } - head, err := base.GetHead(ctx) - if err != nil || head.Gen != 2 || head.Epoch != tc.epoch || head.Holder != "C" || base.Puts() != 0 { - t.Fatalf("refused claim mutated HEAD/payload: %+v puts=%d err=%v", head, base.Puts(), err) - } - for _, status := range p.DurableStatuses() { - if status.Operational { - t.Fatal("displaced claim served I/O") + if out := <-e.decision; out.code != 78 { + t.Fatalf("displaced claim chose %+v; want 78", out) } + } else if _, ended := p.ChunkStartupOutcome("v"); ended { + t.Fatal("a lower racing epoch ended startup") + } + after, found, err := base.ReadHead(ctx) + if err != nil || !found || after.Gen != initial.Gen+2 || after.Epoch != tc.epoch || after.Holder != "C" { + t.Fatalf("refused claim changed racing HEAD: %+v found=%v err=%v", after, found, err) } }) } diff --git a/seaweed-block/cmd/blockvolume/start_any_test.go b/seaweed-block/cmd/blockvolume/start_any_test.go new file mode 100644 index 0000000000..a6d3255409 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/start_any_test.go @@ -0,0 +1,7 @@ +package main + +import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + +// anyStart is a local root that can start from any HEAD: these tests do +// not model the local store. +func anyStart(layout.Head) error { return nil } diff --git a/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go b/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go index e743064263..e7640e49c1 100644 --- a/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go @@ -4,9 +4,7 @@ package main_test import ( "bytes" - "net" "testing" - "time" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" @@ -16,149 +14,6 @@ import ( // This small initiator uses the same exported wire types and admin/IO queue // handshake as core/frontend/nvme/client_support_test.go. It talks only to the // real blockvolume in this harness; no kernel device or unrelated NQN is used. -type gap1NVMe struct { - admin, io net.Conn - r *nvme.Reader - w *nvme.Writer - cid uint16 -} - -func gap1ConnectNVMe(t *testing.T, addr, nqn string) *gap1NVMe { - t.Helper() - c := &gap1NVMe{} - t.Cleanup(c.close) - var controller uint16 = 0xffff - for q := uint16(0); q < 2; q++ { - conn, err := net.DialTimeout("tcp", addr, 5*time.Second) - if err != nil { - t.Fatal(err) - } - if q == 0 { - c.admin = conn - } else { - c.io = conn - } - _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) - r, w := nvme.NewReader(conn), nvme.NewWriter(conn) - if err := w.SendHeaderOnly(0, &nvme.ICRequest{PDUFormatVersion: 0, PDUMaxR2T: 1}, 120); err != nil { - t.Fatal(err) - } - h, err := r.Dequeue() - if err != nil || h.Type != 1 { - t.Fatalf("NVMe IC response: %+v %v", h, err) - } - var ic nvme.ICResponse - if err := r.Receive(&ic); err != nil { - t.Fatal(err) - } - c.cid++ - cmd := nvme.CapsuleCommand{OpCode: 0x7f, FCType: 1, CID: c.cid, D10: uint32(q) << 16} - data := make([]byte, 1024) - (&nvme.ConnectData{HostID: [16]byte{1, 2, 3, 4}, CNTLID: controller, SubNQN: nqn, HostNQN: "nqn.2026-11.test:gap1-host"}).Marshal(data) - if err := w.SendWithData(4, 0, &cmd, 64, data); err != nil { - t.Fatal(err) - } - reply := gap1NVMeReply(t, r, c.cid) - if q == 0 { - controller = uint16(reply.DW0) - if controller == 0 { - t.Fatal("no controller assigned") - } - } - if q == 1 { - c.r, c.w = r, w - } - } - return c -} - -func (c *gap1NVMe) close() { - if c.io != nil { - _ = c.io.Close() - } - if c.admin != nil { - _ = c.admin.Close() - } -} - -func gap1NVMeReply(t *testing.T, r *nvme.Reader, cid uint16) nvme.CapsuleResponse { - t.Helper() - h, err := r.Dequeue() - if err != nil || h.Type != 5 { - t.Fatalf("NVMe capsule header: %+v %v", h, err) - } - var reply nvme.CapsuleResponse - if err := r.Receive(&reply); err != nil { - t.Fatal(err) - } - if reply.CID != cid || reply.Status != 0 { - t.Fatalf("NVMe CID %d: %+v", cid, reply) - } - return reply -} - -func (c *gap1NVMe) writeFlush(t *testing.T, lba uint64, payload []byte) { - t.Helper() - if len(payload) != 4096 { - t.Fatal("harness writes exactly one block") - } - c.cid++ - cmd := nvme.CapsuleCommand{OpCode: 1, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)} - if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil { - t.Fatal(err) - } - h, err := c.r.Dequeue() - if err != nil || h.Type != 9 { - t.Fatalf("NVMe R2T: %+v %v", h, err) - } - var r2t nvme.R2THeader - if err := c.r.Receive(&r2t); err != nil { - t.Fatal(err) - } - if r2t.CCCID != c.cid || r2t.DATAO != 0 || r2t.DATAL != uint32(len(payload)) { - t.Fatalf("wrong R2T %+v", r2t) - } - data := nvme.H2CDataHeader{CCCID: c.cid, TAG: r2t.TAG, DATAO: 0, DATAL: uint32(len(payload))} - if err := c.w.SendWithData(6, 0, &data, 16, payload); err != nil { - t.Fatal(err) - } - gap1NVMeReply(t, c.r, c.cid) - c.cid++ - flush := nvme.CapsuleCommand{OpCode: 0, CID: c.cid, NSID: 1} - if err := c.w.SendHeaderOnly(4, &flush, 64); err != nil { - t.Fatal(err) - } - gap1NVMeReply(t, c.r, c.cid) // only this completed Flush makes the record durable -} - -func (c *gap1NVMe) readExact(t *testing.T, lba uint64, want []byte) { - t.Helper() - c.cid++ - cmd := nvme.CapsuleCommand{OpCode: 2, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)} - if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil { - t.Fatal(err) - } - h, err := c.r.Dequeue() - if err != nil || h.Type != 7 { - t.Fatalf("NVMe read data: %+v %v", h, err) - } - var header nvme.C2HDataHeader - if err := c.r.Receive(&header); err != nil { - t.Fatal(err) - } - if header.CCCID != c.cid || header.DATAO != 0 || header.DATAL != uint32(len(want)) || c.r.Length() != uint32(len(want)) { - t.Fatalf("wrong read frame %+v length%d", header, c.r.Length()) - } - got := make([]byte, c.r.Length()) - if err := c.r.ReceiveData(got); err != nil { - t.Fatal(err) - } - gap1NVMeReply(t, c.r, c.cid) - if !bytes.Equal(got, want) { - t.Fatal("fsync-acknowledged NVMe record changed after supervised restart") - } -} - // Calibration of the witness client only, not a systemd/re-grant proof. func TestGAP1NVMeWitnessRoundTripsAcknowledgedBlock(t *testing.T) { backend := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1}) diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index 898a44e6ec..a9cce04ef7 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -20,9 +20,12 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" "github.com/seaweedfs/seaweed-block/core/rpc/link" "github.com/seaweedfs/seaweed-block/core/storage" "google.golang.org/grpc" @@ -87,7 +90,9 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { "--listen", masterListen, "--tls-cert", filepath.Join(tlsDir, "master.crt"), "--tls-key", filepath.Join(tlsDir, "master.key"), "--tls-client-ca", filepath.Join(tlsDir, "ca.crt"), "--role-file", filepath.Join(tlsDir, "roles"), "--audit-log", filepath.Join(tlsDir, "audit.log"), "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"), "--cluster-spec", spec, "--lifecycle-product-loop-interval", "200ms", "--expected-slots-per-volume", "1", - "--workspace-rpc", "--workspace-head-base-url", "http://"+cluster.filerHTTP+base) + "--workspace-rpc", "--workspace-head-base-url", "http://"+cluster.filerHTTP+base, + // A workspace master writes the layout VOLUME and unclaimed HEAD itself. + "--chunk-filer", cluster.filerGRPC, "--chunk-path", base) w4WaitTCP(t, masterAddr, 20*time.Second) admin, err := link.ClientCredentials(link.TLSFiles{Cert: filepath.Join(tlsDir, "admin.crt"), Key: filepath.Join(tlsDir, "admin.key"), CA: filepath.Join(tlsDir, "ca.crt")}, "") if err != nil { @@ -99,8 +104,19 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { } t.Cleanup(func() { _ = conn.Close() }) ws := control.NewWorkspaceServiceClient(conn) + // The master mints the volume's layout identity; the holder and every + // HEAD read name it. + var layoutID layout.VolumeID + waitGAP1(t, "master never resolved the volume's layout identity", 20*time.Second, func() bool { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + id, e := lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume) + layoutID = id + return e == nil + }) args := []string{"--master", masterAddr, "--server-id", "s1", - "--master-tls-cert", filepath.Join(tlsDir, "s1.crt"), "--master-tls-key", filepath.Join(tlsDir, "s1.key"), "--master-ca", filepath.Join(tlsDir, "ca.crt"), "--volume-id", volume, "--replica-id", "r1", + "--master-tls-cert", filepath.Join(tlsDir, "s1.crt"), "--master-tls-key", filepath.Join(tlsDir, "s1.key"), "--master-ca", filepath.Join(tlsDir, "ca.crt"), + "--volume-id", volume, "--replica-id", "r1", "--layout-id", layoutID.String(), "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--heartbeat-interval", "200ms", "--t1-readiness", "--status-addr", statusAddr, "--durable-root", filepath.Join(root, "store"), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", @@ -142,13 +158,19 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { t.Logf("acknowledged NVMe record: lba=8 bytes=%d sha256=%x", len(want), sha256.Sum256(want)) client.readExact(t, 8, want) client.close() - remote := cluster.remote(t, base+"/"+volume) + remote := cluster.remote(t, base, chunkstore.VolumeRef{Name: volume, ID: layoutID}) before, err := gap1ReadHead(t, remote) if err != nil || before.Gen == 0 { t.Fatalf("bootstrap HEAD: %+v %v", before, err) } gap1Systemctl(t, "kill", "--signal=KILL", "--kill-who=main", bootstrap) waitGAP1(t, "bootstrap still running", 10*time.Second, func() bool { return gap1Unit(t, bootstrap)["MainPID"] == "0" }) + // HEAD as the killed holder left it (no process can move it now). + ref := chunkstore.VolumeRef{Name: volume, ID: layoutID} + atKill := layoutHead(t, cluster, base, ref) + if atKill.Holder != "s1/r1" || atKill.ClaimID == "" || atKill.State != layout.StateLive { + t.Fatalf("HEAD at the kill: %+v; want live, held by s1/r1 under a claim", atKill) + } // QueryWorkspace is read-only. These real binaries and this test share // one WSL kernel wall clock. Use the reported MASTER expiry timestamp, // not ValidForNs (which ends half a skew earlier and could renew live). @@ -207,10 +229,20 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { } return true }) - after, err := gap1ReadHead(t, remote) - if err != nil || after.Gen <= before.Gen || after.Holder != before.Holder || after.Epoch != before.Epoch { - t.Fatalf("return did not claim HEAD: before%+v after%+v err%v", before, after, err) + // The holder returns with its own claim at the same epoch: over an idle + // HEAD it resumes with no HEAD write; a session of its claim left open at + // the kill is aborted (a HEAD write) before it serves. + after := layoutHead(t, cluster, base, ref) + if after.Holder != atKill.Holder || after.Epoch != atKill.Epoch || after.ClaimID != atKill.ClaimID || after.State != layout.StateLive || after.Activity.Kind != layout.ActIdle { + t.Fatalf("return did not resume its claim: at kill %+v, after %+v", atKill, after) } + switch { + case atKill.Activity.Kind == layout.ActIdle && after.Gen != atKill.Gen: + t.Fatalf("return over an idle HEAD wrote it: gen %d -> %d", atKill.Gen, after.Gen) + case atKill.Activity.Kind != layout.ActIdle && after.Gen <= atKill.Gen: + t.Fatalf("return left the open %s session %q: gen %d -> %d", atKill.Activity.Kind, atKill.Activity.Session, atKill.Gen, after.Gen) + } + t.Logf("return resumed claim %s at epoch %d: activity at kill %s, gen %d -> %d", after.ClaimID, after.Epoch, atKill.Activity.Kind, atKill.Gen, after.Gen) returned := gap1ConnectNVMe(t, nvmeAddr, "nqn.2026-11.test:"+stem) returned.readExact(t, 8, want) returned.writeFlush(t, 9, want) diff --git a/seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go b/seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go new file mode 100644 index 0000000000..4d591c600f --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go @@ -0,0 +1,299 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + master "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// moveHost is one blockvolume process of the move test: its addresses and +// the running binary. +type moveHost struct { + server, data, ctrl, status, nvme, nqn string + cmd *exec.Cmd + done chan error + exited bool +} + +func newMoveHost(t *testing.T, server, nqn string) *moveHost { + return &moveHost{server: server, data: leaseBinaryAddress(t), ctrl: leaseBinaryAddress(t), status: leaseBinaryAddress(t), + nvme: leaseBinaryAddress(t), nqn: nqn} +} + +// start runs the blockvolume binary for vol-a as replica r1 on this host, +// with the master-minted layout identity, and kills it at cleanup. +func (m *moveHost) start(t *testing.T, exe, masterAddr, filerGRPC, base string, layoutID layout.VolumeID) { + t.Helper() + logPath := filepath.Join(t.TempDir(), m.server+".log") + log, err := os.Create(logPath) + if err != nil { + t.Fatal(err) + } + m.cmd = exec.Command(exe, "--master", masterAddr, "--server-id", m.server, "--volume-id", "vol-a", "--replica-id", "r1", + "--data-addr", m.data, "--ctrl-addr", m.ctrl, "--t1-readiness", "--status-addr", m.status, + "--durable-root", t.TempDir(), "--layout-id", layoutID.String(), "--volume-lock-dir-test-only", t.TempDir(), + "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", filerGRPC, "--chunk-path", base, + "--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", m.nvme, "--nvme-subsysnqn", m.nqn) + stripSystemdForTestLockDir(m.cmd) + m.cmd.Stdout, m.cmd.Stderr = log, log + if err := m.cmd.Start(); err != nil { + t.Fatal(err) + } + m.done = make(chan error, 1) + go func() { m.done <- m.cmd.Wait() }() + t.Cleanup(func() { + if !m.exited { + _ = m.cmd.Process.Kill() + select { + case <-m.done: + case <-time.After(5 * time.Second): + t.Errorf("%s did not exit after kill", m.server) + } + } + log.Close() + if t.Failed() { + b, _ := os.ReadFile(logPath) + if len(b) > 14000 { + b = b[len(b)-14000:] + } + t.Logf("%s log: %s", m.server, b) + } + }) +} + +// wait waits for the process to end on its own within d. +func (m *moveHost) wait(t *testing.T, d time.Duration) { + t.Helper() + select { + case <-m.done: + m.exited = true + case <-time.After(d): + t.Fatalf("%s did not exit", m.server) + } +} + +// projection is the volume's status as this host reports it. +func (m *moveHost) projection() (frontend.Projection, bool) { + c := &http.Client{Timeout: time.Second} + resp, err := c.Get("http://" + m.status + "/status?volume=vol-a") + if err != nil { + return frontend.Projection{}, false + } + defer resp.Body.Close() + var p frontend.Projection + return p, json.NewDecoder(resp.Body).Decode(&p) == nil +} + +// layoutHead reads ref's HEAD as stored (claim id included). +func layoutHead(t *testing.T, cluster *w4WeedCluster, base string, ref chunkstore.VolumeRef) layout.Head { + t.Helper() + cl := cluster.client(t, base) + cat, err := chunkstore.NewBCatalog(cl, cl, base) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + h, found, err := cat.ReadHead(ctx, ref) + if err != nil || !found { + t.Fatalf("HEAD of %s: found %v, %v", ref.Name, found, err) + } + return h +} + +// A move on the content-named layout with real processes: the master in +// process, SeaweedFS and two blockvolume binaries. Clean: the source writes, +// cuts and stops (HEAD detached by the source's claim), the master moves the +// volume, the target claims HEAD at the higher epoch and reads back every +// acknowledged write. Forced: the source is killed after its cut and one more +// acknowledged write; after the master's barrier the forced move is issued +// with its lost range recorded, and the target claims and reads back what the +// cut published. HEAD's state, epoch, holder and claim are asserted at each +// step. +func TestIntegrationWorkspaceLayoutMove(t *testing.T) { + if os.Getenv("CHUNKSTORE_WEED") == "" { + t.Skip("CHUNKSTORE_WEED not set") + } + exe := filepath.Join(t.TempDir(), "blockvolume") + if out, err := exec.Command("go", "build", "-race", "-p", "4", "-o", exe, ".").CombinedOutput(); err != nil { + t.Fatalf("build: %v %s", err, out) + } + cluster := startWorkspaceWeed(t) + for _, kind := range []string{"clean", "forced"} { + t.Run(kind, func(t *testing.T) { layoutMove(t, exe, cluster, kind) }) + } +} + +func layoutMove(t *testing.T, exe string, cluster *w4WeedCluster, kind string) { + base := fmt.Sprintf("/workspace-move-%s-%d", kind, time.Now().UnixNano()) + var h *master.Host + reader, err := master.NewLayoutWorkspaceHEADReader("http://"+cluster.filerHTTP+base, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { + return h.WorkspaceLayoutVolume(ctx, name) + }) + if err != nil { + t.Fatal(err) + } + h, err = master.New(master.Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", + WorkspaceRPC: true, WorkspaceHeadReader: reader, WorkspaceMaxClockSkew: 100 * time.Millisecond, + LayoutCreateVolume: layoutMasterWriter(t, cluster, base)}) + if err != nil { + t.Fatal(err) + } + h.Start() + t.Cleanup(func() { + ctx, c := context.WithTimeout(context.Background(), 5*time.Second) + defer c() + _ = h.Close(ctx) + }) + src, dst := newMoveHost(t, "node-a", "nqn.2026-11.test:move-src-"+kind), newMoveHost(t, "node-b", "nqn.2026-11.test:move-dst-"+kind) + // The master's create writes VOLUME and the unclaimed HEAD, then marks + // the record store-ready; only a store-ready volume gets a placement. + layoutID := createStoreReadyVolume(t, h, "vol-a", 64*4096) + ref := chunkstore.VolumeRef{Name: "vol-a", ID: layoutID} + for _, n := range []*moveHost{src, dst} { + if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n.server, DataAddr: n.data, CtrlAddr: n.ctrl}); err != nil { + t.Fatal(err) + } + } + if _, err = h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "vol-a", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{ + {VolumeID: "vol-a", ServerID: src.server, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + if err = h.ObservationHost().Ingest(authority.Observation{ServerID: src.server, ObservedAt: time.Now().UTC(), + Slots: []authority.SlotFact{{VolumeID: "vol-a", ReplicaID: "r1", DataAddr: src.data, CtrlAddr: src.ctrl}}}); err != nil { + t.Fatal(err) + } + if _, err = h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + leaseBinaryPoll(t, "no initial authority", func() bool { line, ok := h.Publisher().VolumeAuthorityLine("vol-a"); return ok && line.Epoch > 0 }) + line, _ := h.Publisher().VolumeAuthorityLine("vol-a") + remote := cluster.remote(t, base, ref) + + // The source serves, takes acknowledged writes, cuts. + src.start(t, exe, h.Addr(), cluster.filerGRPC, base, layoutID) + leaseBinaryPoll(t, "source did not serve", func() bool { p, ok := src.projection(); return ok && p.Healthy && p.Epoch == line.Epoch }) + want, late := bytes.Repeat([]byte{0xD7}, 4096), bytes.Repeat([]byte{0x5A}, 4096) + nv := gap1ConnectNVMe(t, src.nvme, src.nqn) + nv.writeFlush(t, 8, want) + nv.writeFlush(t, 9, want) + leaseBinaryPoll(t, "source cut", func() bool { code, _, e := leaseBinaryPost(src.status, "cut"); return e == nil && code == 200 }) + cut := layoutHead(t, cluster, base, ref) + if cut.Epoch != line.Epoch || cut.Holder != src.server+"/r1" || cut.ClaimID == "" || cut.State != layout.StateLive || cut.Current == nil { + t.Fatalf("HEAD after the source's cut: %+v; want live, held by %s/r1 at epoch %d with a claim", cut, src.server, line.Epoch) + } + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ws := control.NewWorkspaceServiceClient(conn) + ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second) + defer cancel() + q := &control.WorkspaceMove{RequestId: kind + "-move", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, + TargetReplicaId: "r1", TargetServerId: dst.server, TargetDataAddr: dst.data, TargetCtrlAddr: dst.ctrl, Kind: kind, Force: kind == "forced"} + if kind == "clean" { + nv.close() + code, b, e := leaseBinaryPost(src.status, "detach") + if e != nil || code != 200 { + t.Fatalf("detach: %d %s %v", code, b, e) + } + sealed := layoutHead(t, cluster, base, ref) + if sealed.State != layout.StateDetached || sealed.Epoch != line.Epoch || sealed.Holder != cut.Holder || sealed.ClaimID != cut.ClaimID { + t.Fatalf("HEAD after the detach: %+v; want detached by the source's claim %q at epoch %d", sealed, cut.ClaimID, line.Epoch) + } + if _, err = ws.RevokeWorkspace(ctx, &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r1", Epoch: line.Epoch}); err != nil { + t.Fatal(err) + } + leaseBinaryPoll(t, "source did not ACK its drained stop", func() bool { s := h.Publisher().WorkspaceState("vol-a"); return s != nil && s.Ack != nil }) + src.wait(t, 15*time.Second) + } else { + // One more acknowledged write after the cut, then the source dies + // without a stop: the forced move records it as possibly lost. + nv.writeFlush(t, 10, late) + nv.close() + if err = src.cmd.Process.Signal(syscall.SIGKILL); err != nil { + t.Fatal(err) + } + src.wait(t, 10*time.Second) + killed := layoutHead(t, cluster, base, ref) + if killed.State != layout.StateLive || killed.Epoch != line.Epoch || killed.ClaimID != cut.ClaimID { + t.Fatalf("HEAD after the kill: %+v; want still the source's live claim", killed) + } + // The master owns the barrier: wait for its affirmative preview. + for { + pv, err := ws.PreviewWorkspaceMove(ctx, q) + if err != nil { + t.Fatal(err) + } + if pv.Admitted { + break + } + select { + case <-time.After(200 * time.Millisecond): + case <-ctx.Done(): + t.Fatalf("forced preview never admitted: %v (last reason %q)", ctx.Err(), pv.Reason) + } + } + } + before := layoutHead(t, cluster, base, ref) + grant, err := ws.MoveWorkspace(ctx, q) + if err != nil { + t.Fatal(err) + } + if !grant.Issued || grant.NewEpoch <= line.Epoch || grant.OldHost != src.server || grant.NewHost != dst.server || grant.HeadGen != before.Gen || grant.RemoteLsn != before.Position { + t.Fatalf("grant %v not bound to HEAD %+v", grant, before) + } + if after := layoutHead(t, cluster, base, ref); after.Gen != before.Gen || after.Epoch != before.Epoch || after.ClaimID != before.ClaimID { + t.Fatalf("the grant itself changed HEAD: %+v -> %+v", before, after) + } + if kind == "forced" { + if grant.LostRange == nil || grant.LostRange.NewEpoch != grant.NewEpoch || grant.LostRange.OldEpoch != line.Epoch || grant.LostRange.LostAfterLsn != before.Position { + t.Fatalf("forced grant lost range %v; want after LSN %d, epochs %d -> %d", grant.LostRange, before.Position, line.Epoch, grant.NewEpoch) + } + lr, err := ws.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-a", RequestId: q.RequestId}) + if err != nil || len(lr.GetRanges()) != 1 || lr.GetRanges()[0].GetLostAfterLsn() != before.Position { + t.Fatalf("recorded lost range: %v %v", lr, err) + } + } else if grant.LostRange != nil { + t.Fatalf("clean grant carries a lost range %v", grant.LostRange) + } + + // The target claims HEAD at the new epoch and serves what was published. + dst.start(t, exe, h.Addr(), cluster.filerGRPC, base, layoutID) + leaseBinaryPoll(t, "target did not serve", func() bool { p, ok := dst.projection(); return ok && p.Healthy && p.Epoch == grant.NewEpoch }) + claimed := layoutHead(t, cluster, base, ref) + if claimed.Epoch != grant.NewEpoch || claimed.Holder != dst.server+"/r1" || claimed.State != layout.StateLive || claimed.ClaimID == "" || claimed.ClaimID == cut.ClaimID || claimed.Gen <= before.Gen { + t.Fatalf("HEAD after the target's start: %+v; want live, held by %s/r1 at epoch %d under a new claim", claimed, dst.server, grant.NewEpoch) + } + if eh, err := remote.GetHead(ctx); err != nil || eh.Epoch != grant.NewEpoch || eh.State != "active" || eh.DetachedBy != nil { + t.Fatalf("engine view of HEAD after the claim: %+v %v", eh, err) + } + tv := gap1ConnectNVMe(t, dst.nvme, dst.nqn) + tv.readExact(t, 8, want) + tv.readExact(t, 9, want) + tv.writeFlush(t, 11, want) + tv.readExact(t, 11, want) + tv.close() + t.Logf("%s move on the layout: claim %s@%d -> %s@%d, HEAD gen %d -> %d", kind, cut.ClaimID, line.Epoch, claimed.ClaimID, grant.NewEpoch, before.Gen, claimed.Gen) +} diff --git a/seaweed-block/cmd/blockvolume/workspace_layout_proof_test.go b/seaweed-block/cmd/blockvolume/workspace_layout_proof_test.go new file mode 100644 index 0000000000..1e9c94b916 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_layout_proof_test.go @@ -0,0 +1,74 @@ +package main + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +type layoutProofStore struct { + h layout.Head + found bool + err error +} + +func (s layoutProofStore) ReadHead(context.Context) (layout.Head, bool, error) { + return s.h, s.found, s.err +} +func (s layoutProofStore) UpdateHead(context.Context, uint64, layout.Head) error { + return errors.New("proof must not write") +} + +func TestWorkspaceLayoutDetachedProof(t *testing.T) { + for _, tc := range []struct { + name string + mutate func(*layoutProofStore, *control.WorkspaceIdentity, *layout.HolderID) + want bool + }{ + {"exact", nil, true}, + {"absent", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.found = false }, false}, + {"unknown", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { + s.err = errors.New("read lost") + }, false}, + {"live", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { + s.h.State = layout.StateLive + }, false}, + {"deleting", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { + s.h.State = layout.StateDeleting + }, false}, + {"deleted", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { + s.h.State = layout.StateDeleted + }, false}, + {"open activity", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { + s.h.Activity = layout.Activity{Kind: layout.ActSnap, Session: "old"} + }, false}, + {"zero generation", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Gen = 0 }, false}, + {"other claim", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.ClaimID = "other" }, false}, + {"older HEAD epoch", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Epoch-- }, false}, + {"newer HEAD epoch", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Epoch++ }, false}, + {"other HEAD holder", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Holder = "other/r" }, false}, + {"zero request epoch", func(_ *layoutProofStore, id *control.WorkspaceIdentity, _ *layout.HolderID) { id.Epoch = 0 }, false}, + {"zero epoch everywhere", func(s *layoutProofStore, id *control.WorkspaceIdentity, me *layout.HolderID) { + s.h.Epoch, id.Epoch, me.Epoch = 0, 0, 0 + }, false}, + {"other request server", func(_ *layoutProofStore, id *control.WorkspaceIdentity, _ *layout.HolderID) { id.ServerId = "other" }, false}, + {"other request replica", func(_ *layoutProofStore, id *control.WorkspaceIdentity, _ *layout.HolderID) { id.ReplicaId = "other" }, false}, + {"empty local claim", func(_ *layoutProofStore, _ *control.WorkspaceIdentity, me *layout.HolderID) { me.ClaimID = "" }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + me := layout.HolderID{Epoch: 2, Holder: "s/r", ClaimID: "k"} + id := &control.WorkspaceIdentity{VolumeId: "v", ServerId: "s", ReplicaId: "r", Epoch: 2} + st := layoutProofStore{h: layout.Head{Gen: 7, Epoch: 2, Holder: "s/r", ClaimID: "k", State: layout.StateDetached, Activity: layout.Activity{Kind: layout.ActIdle}}, found: true} + if tc.mutate != nil { + tc.mutate(&st, id, &me) + } + gen, err := workspaceLayoutDetachedGeneration(context.Background(), st, id, me) + if (err == nil) != tc.want || (tc.want && gen != 7) || (!tc.want && gen != 0) { + t.Fatalf("gen=%d err=%v", gen, err) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/workspace_lease.go b/seaweed-block/cmd/blockvolume/workspace_lease.go index 4362b51e82..523417c5d0 100644 --- a/seaweed-block/cmd/blockvolume/workspace_lease.go +++ b/seaweed-block/cmd/blockvolume/workspace_lease.go @@ -3,9 +3,9 @@ package main import ( "context" "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/host/volume" control "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/storage" ) type workspaceStopResult struct { @@ -47,22 +47,23 @@ func startWorkspaceLease(ctx context.Context, h *volume.Host) (<-chan workspaceS return requests, done } -// CLEAN requires a prior Detach while the lease was valid. This is read-only: -// revocation, expiry and cancellation never manufacture a final cut/proof. -func workspaceDetachedGeneration(ctx context.Context, remoteFor func(string) (storage.ChunkRemote, error), id *control.WorkspaceIdentity, holder string) (uint64, error) { - if err := ctx.Err(); err != nil { - return 0, err +// workspaceLayoutDetachedGeneration accepts only the attached Start identity's +// exact detached HEAD. Missing, foreign or unknown evidence never yields ACK. +// The returned generation is diagnostic readout, not the clean-move identity: +// the master reads this detached epoch/holder/position when recording the ACK. +func workspaceLayoutDetachedGeneration(ctx context.Context, st layout.HeadStore, id *control.WorkspaceIdentity, me layout.HolderID) (uint64, error) { + if id == nil || me.Epoch == 0 || id.Epoch != me.Epoch || me.Holder == "" || id.ServerId+"/"+id.ReplicaId != me.Holder || me.ClaimID == "" { + return 0, layout.ErrNotHolder } - if remoteFor == nil || id == nil { - return 0, fmt.Errorf("workspace remote/identity missing") - } - remote, err := remoteFor(id.VolumeId) + h, found, err := st.ReadHead(ctx) if err != nil { return 0, err } - head, err := storage.ReadDetachedChunkHead(ctx, remote, id.Epoch, holder) - if err != nil { - return 0, err + if !found { + return 0, layout.ErrHeadAbsent } - return head.Gen, nil + if !layout.DetachedBy(h, me) { + return 0, fmt.Errorf("workspace: no detached proof for the attached claim") + } + return h.Gen, nil } diff --git a/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go b/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go index 0ae40371a6..7a8cd22f34 100644 --- a/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go +++ b/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go @@ -9,6 +9,7 @@ import ( "fmt" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" master "github.com/seaweedfs/seaweed-block/core/host/master" "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" @@ -69,11 +70,15 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) { for _, enabled := range []bool{false, true} { t.Run(fmt.Sprintf("workspace-rpc-%v", enabled), func(t *testing.T) { base := fmt.Sprintf("/workspace-lease-%d", time.Now().UnixNano()) - reader, err := master.NewWorkspaceHEADReader("http://" + cluster.filerHTTP + base) + var h *master.Host + reader, err := master.NewLayoutWorkspaceHEADReader("http://"+cluster.filerHTTP+base, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { + return h.WorkspaceLayoutVolume(ctx, name) + }) if err != nil { t.Fatal(err) } - h, err := master.New(master.Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: enabled, WorkspaceHeadReader: reader}) + h, err = master.New(master.Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: enabled, WorkspaceHeadReader: reader, + LayoutCreateVolume: layoutMasterWriter(t, cluster, base)}) if err != nil { t.Fatal(err) } @@ -84,9 +89,9 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) { _ = h.Close(ctx) }) dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t) - if _, err = h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 64 * 4096, ReplicationFactor: 1}); err != nil { - t.Fatal(err) - } + // The master's create writes VOLUME and the unclaimed HEAD, then + // marks the record store-ready; only a store-ready volume gets a placement. + layoutID := createStoreReadyVolume(t, h, "vol-a", 64*4096) if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: dataAddr, CtrlAddr: ctrlAddr}); err != nil { t.Fatal(err) } @@ -106,7 +111,7 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) { if err != nil { t.Fatal(err) } - cmd := exec.Command(exe, "--master", h.Addr(), "--server-id", "node-a", "--volume-id", "vol-a", "--replica-id", "r1", "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--t1-readiness", "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--volume-lock-dir-test-only", t.TempDir(), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:workspace-lease") + cmd := exec.Command(exe, "--master", h.Addr(), "--server-id", "node-a", "--volume-id", "vol-a", "--replica-id", "r1", "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--t1-readiness", "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--layout-id", layoutID.String(), "--volume-lock-dir-test-only", t.TempDir(), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:workspace-lease") stripSystemdForTestLockDir(cmd) cmd.Stdout, cmd.Stderr = log, log if err = cmd.Start(); err != nil { @@ -144,7 +149,7 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) { e = json.NewDecoder(resp.Body).Decode(&p) return p, e == nil } - remote := cluster.remote(t, base+"/vol-a") + remote := cluster.remote(t, base, chunkstore.VolumeRef{Name: "vol-a", ID: layoutID}) if !enabled { leaseBinaryPoll(t, "unleased host did not adopt assignment", func() bool { p, ok := projection(); return ok && p.Epoch == line.Epoch }) // Exercise an actual cut request, not just the status presentation. @@ -206,9 +211,18 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) { t.Fatal("NVMe frontend still accepts after shutdown") } if !enabled { - head, e := remote.GetHead(context.Background()) - if e != nil || head.Gen != 0 { - t.Fatal("unleased binary changed HEAD", head, e) + // No claim was ever made: HEAD is absent, or the unclaimed + // HEAD the create wrote (no holder, epoch 0). + cl := cluster.client(t, base) + cat, e := chunkstore.NewBCatalog(cl, cl, base) + if e != nil { + t.Fatal(e) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + head, found, e := cat.ReadHead(ctx, chunkstore.VolumeRef{Name: "vol-a", ID: layoutID}) + cancel() + if e != nil || found && (head.Holder != "" || head.Epoch != 0 || head.ClaimID != "") { + t.Fatal("unleased binary changed HEAD", head, found, e) } } }) diff --git a/seaweed-block/cmd/blockvolume/workspace_proof_test.go b/seaweed-block/cmd/blockvolume/workspace_proof_test.go deleted file mode 100644 index 3ecf940654..0000000000 --- a/seaweed-block/cmd/blockvolume/workspace_proof_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -import ( - "context" - "errors" - control "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/storage" - "testing" -) - -type workspaceProofRemote struct { - storage.ChunkRemote - head storage.ChunkHead - err error - reads int -} - -func (r *workspaceProofRemote) GetHead(context.Context) (storage.ChunkHead, error) { - r.reads++ - return r.head, r.err -} - -func TestWorkspaceRevocationUsesExactStoredSeal(t *testing.T) { - for _, name := range []string{"valid", "zero-epoch", "empty-holder", "active", "missing-proof", "proof-gen", "proof-epoch", "proof-holder", "foreign-holder", "foreign-epoch", "zero-gen", "read-error"} { - t.Run(name, func(t *testing.T) { - h := storage.ChunkHead{Gen: 7, Epoch: 2, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Gen: 7, Epoch: 2, Holder: "s/r"}} - id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2} - holder := "s/r" - r := &workspaceProofRemote{head: h} - switch name { - case "zero-epoch": - id.Epoch = 0 - r.head.Epoch = 0 - r.head.DetachedBy.Epoch = 0 - case "empty-holder": - holder = "" - r.head.Holder = "" - r.head.DetachedBy.Holder = "" - case "active": - r.head.State = storage.ChunkHeadActive - case "missing-proof": - r.head.DetachedBy = nil - case "zero-gen": - r.head.Gen = 0 - r.head.DetachedBy.Gen = 0 - case "proof-epoch": - r.head.DetachedBy.Epoch = 1 - case "proof-holder": - r.head.DetachedBy.Holder = "other/r" - case "foreign-epoch": - r.head.Epoch = 1 - case "proof-gen": - r.head.DetachedBy.Gen = 6 - case "foreign-holder": - r.head.Holder = "other/r" - case "read-error": - r.err = errors.New("HEAD answer lost") - } - gen, err := workspaceDetachedGeneration(context.Background(), func(string) (storage.ChunkRemote, error) { return r, nil }, id, holder) - if name == "valid" { - if err != nil || gen != 7 || r.reads != 1 { - t.Fatalf("stored seal: gen%d reads%d err%v", gen, r.reads, err) - } - } else if err == nil || gen != 0 { - t.Fatalf("unproven ACK gen%d err%v", gen, err) - } - }) - } -} diff --git a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go index 525a919f10..f3236fbc38 100644 --- a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go +++ b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go @@ -8,6 +8,8 @@ import ( "context" "fmt" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "math" "math/rand" "net" "os" @@ -225,9 +227,17 @@ func (c *w4WeedCluster) client(t *testing.T, assignPath string) *chunkstore.SWFS return cl } -func (c *w4WeedCluster) remote(t *testing.T, root string) *chunkstore.ChunkRemote { +// remote reads ref's HEAD under base as the chunk engine sees it, through the +// layout remote of an observer that holds nothing: its epoch, holder and +// claim match no HEAD, so it never rolls a session back or writes. +func (c *w4WeedCluster) remote(t *testing.T, base string, ref chunkstore.VolumeRef) *chunkstore.LayoutRemote { t.Helper() - r, err := chunkstore.NewSWFSChunkRemote(c.client(t, root), root) + cl := c.client(t, base) + cat, err := chunkstore.NewBCatalog(cl, cl, base) + if err != nil { + t.Fatal(err) + } + r, err := chunkstore.NewLayoutRemote(cat, ref, layout.HolderID{Epoch: math.MaxUint64, Holder: "test-observer", ClaimID: "observer"}) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 793f613a04..de2902aaa9 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -23,8 +23,8 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/ops" - "github.com/seaweedfs/seaweed-block/core/storage" ) const ( @@ -73,11 +73,9 @@ func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Durat func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { - return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|verify|volume-delete|restore", false) + return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|detach|show|usage|verify|volume-delete|restore|release|retain", false) } switch args[0] { - case "gc": - return chunkGC(args[1:], stdout, stderr) case "cut": return chunkCut(args[1:], stdout, stderr) case "snapshot": @@ -88,12 +86,12 @@ func runOpsChunk(args []string, stdout, stderr io.Writer) int { return chunkSnapshots(args[1:], stdout, stderr) case "snapshot-delete": return chunkSnapshotDelete(args[1:], stdout, stderr) - case "fork": - return chunkFork(args[1:], stdout, stderr) case "show": return chunkShow(args[1:], stdout, stderr) case "usage": return chunkUsage(args[1:], stdout, stderr) + case "release": + return chunkRelease(args[1:], stdout, stderr) case "retain": return chunkRetain(args[1:], stdout, stderr) case "verify": @@ -233,10 +231,10 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int { return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume, --status-addr and --name are required", false) } if pin { - if class != "" && class != chunkstore.SnapshotClassPinned { + if class != "" && class != layout.ClassPinned { return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--pin conflicts with --class "+class, false) } - class = chunkstore.SnapshotClassPinned + class = layout.ClassPinned } if expires < 0 || expires > 0 && expiresAtNs != 0 { return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--expires must be positive and does not combine with --expires-at-ns", false) @@ -300,32 +298,6 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int { return chunkPost("detach", statusAddr, "/chunk/detach", timeout, body, stdout, stderr) } -// chunkCatalog opens the catalog under --chunk-path on --chunk-filer. -// It returns exit -1 on success, else the exit code after reporting. -// chunkCatalog dials the filer and opens the catalog; a command that writes -// (writes) first passes the single-filer start check. -func chunkCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { - if filer == "" { - return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false) - } - f, closeFn, err := dialChunkFiler(filer) - if err != nil { - return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) - } - if writes { - if exit := refuseUnlessSingleFiler(name, f, timeout, stdout, stderr); exit >= 0 { - _ = closeFn() - return nil, nil, exit - } - } - cat, err := chunkstore.NewCatalog(f, base) - if err != nil { - _ = closeFn() - return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) - } - return cat, closeFn, -1 -} - // chunkResult prints v as JSON, or err as ": ". func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int { if err != nil { @@ -335,6 +307,8 @@ func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int { return chunkFail(name, stdout, stderr, chunkExitFailed, ce.Code, ce.Detail(), ce.Retryable) case errors.Is(err, context.DeadlineExceeded): return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true) + case layoutCode(err) != "": + return chunkFail(name, stdout, stderr, chunkExitFailed, layoutCode(err), err.Error(), errors.Is(err, layout.ErrPrecondition)) default: return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false) } @@ -392,143 +366,3 @@ func writeAll(w io.Writer, p []byte) error { } return err } - -func chunkSnapshots(args []string, stdout, stderr io.Writer) int { - fs := chunkFlagSet("snapshots", stderr) - var ( - volumeID, filer, base, prefix, startAfter string - limit int - includeDeleting bool - timeout time.Duration - ) - fs.StringVar(&volumeID, "volume", "", "volume id") - fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") - fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") - fs.StringVar(&prefix, "prefix", "", "only names with this prefix") - fs.StringVar(&startAfter, "start-after", "", "list after this name (the previous page's next)") - fs.IntVar(&limit, "limit", 0, "page size (0: the default)") - fs.BoolVar(&includeDeleting, "include-deleting", false, "also list snapshots marked deleting") - fs.DurationVar(&timeout, "timeout", 30*time.Second, "filer timeout") - if err := fs.Parse(args); err != nil { - return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) - } - if volumeID == "" { - return chunkFail("snapshots", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) - } - cat, closeFn, exit := chunkCatalog("snapshots", filer, base, false, timeout, stdout, stderr) - if exit >= 0 { - return exit - } - defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - list, next, err := cat.ListSnapshots(ctx, volumeID, chunkstore.ListOptions{Prefix: prefix, StartAfter: startAfter, Limit: limit, IncludeDeleting: includeDeleting}) - return chunkResult("snapshots", chunkstore.NewSnapshotListBody(volumeID, list, next), err, stdout, stderr) -} - -func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { - fs := chunkFlagSet("snapshot-delete", stderr) - var ( - volumeID, filer, base, name string - timeout time.Duration - ) - fs.StringVar(&volumeID, "volume", "", "volume id") - fs.StringVar(&name, "name", "", "snapshot name") - fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") - fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") - fs.DurationVar(&timeout, "timeout", 30*time.Second, "filer timeout") - if err := fs.Parse(args); err != nil { - return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) - } - if volumeID == "" || name == "" { - return chunkFail("snapshot-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --name are required", false) - } - cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, true, timeout, stdout, stderr) - if exit >= 0 { - return exit - } - defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - state, err := cat.DeleteSnapshot(ctx, volumeID, name) - return chunkResult("snapshot-delete", chunkstore.SnapshotDeleteBody{VolumeID: volumeID, Name: name, State: state}, err, stdout, stderr) -} - -func chunkFork(args []string, stdout, stderr io.Writer) int { - fs := chunkFlagSet("fork", stderr) - var ( - filer, base, source, snapshot, target, requestID string - timeout time.Duration - ) - labels := labelFlags{} - fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") - fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") - fs.StringVar(&source, "source", "", "source volume id") - fs.StringVar(&snapshot, "snapshot", "", "source snapshot name") - fs.StringVar(&target, "target", "", "new volume id") - fs.StringVar(&requestID, "request-id", "", "idempotency id; generated and printed when empty (reuse it to retry)") - fs.Var(labels, "label", "key=value label (repeatable)") - fs.DurationVar(&timeout, "timeout", 6*time.Minute, "filer timeout (the fork's own HEAD deadline is OpDeadline)") - if err := fs.Parse(args); err != nil { - return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) - } - if source == "" || snapshot == "" || target == "" { - return chunkFail("fork", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--source, --snapshot and --target are required", false) - } - if requestID == "" { - requestID = newRequestID() - fmt.Fprintf(stderr, "sw-block ops chunk fork: request id %s (reuse it to retry)\n", requestID) - } - cat, closeFn, exit := chunkCatalog("fork", filer, base, true, timeout, stdout, stderr) - if exit >= 0 { - return exit - } - defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - res, err := cat.Fork(ctx, chunkstore.ForkRequest{Source: source, Snapshot: snapshot, Target: target, RequestID: requestID, Labels: map[string]string(labels)}) - return chunkResult("fork", res, err, stdout, stderr) -} - -// chunkShow prints one volume's VOLUME entry and HEAD from the filer (§0.1). -func chunkShow(args []string, stdout, stderr io.Writer) int { - fs := chunkFlagSet("show", stderr) - var ( - volumeID, filer, base string - timeout time.Duration - ) - fs.StringVar(&volumeID, "volume", "", "volume id") - fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") - fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") - fs.DurationVar(&timeout, "timeout", 30*time.Second, "filer timeout") - if err := fs.Parse(args); err != nil { - return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) - } - if volumeID == "" { - return chunkFail("show", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) - } - cat, closeFn, exit := chunkCatalog("show", filer, base, false, timeout, stdout, stderr) - if exit >= 0 { - return exit - } - defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - v, hasVolume, err := cat.ReadVolume(ctx, volumeID) - if err != nil { - return chunkResult("show", nil, err, stdout, stderr) - } - h, hasHead, err := cat.ReadHead(ctx, volumeID) - if err != nil { - return chunkResult("show", nil, err, stdout, stderr) - } - var vp *chunkstore.VolumeInfo - if hasVolume { - vp = &v - } - var hp *storage.ChunkHead - if hasHead { - hp = &h - } - return chunkResult("show", chunkstore.NewVolumeShowBody(volumeID, vp, hp), nil, stdout, stderr) -} diff --git a/seaweed-block/cmd/sw-block/chunk_b.go b/seaweed-block/cmd/sw-block/chunk_b.go new file mode 100644 index 0000000000..202a683224 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_b.go @@ -0,0 +1,401 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "flag" + "fmt" + "io" + "sort" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain" + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// restoreCreateRPC is the one master transition for a restore. Tests replace +// it with an in-process master; the CLI never creates a target in the filer. +var restoreCreateRPC = func(ctx context.Context, master string, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + conn, err := link.DialMasterFromEnv(master) + if err != nil { + return nil, err + } + defer conn.Close() + return control.NewLifecycleServiceClient(conn).CreateVolume(ctx, req) +} + +// bCatalog dials the filer and opens the volume catalog; a command that +// writes first passes the single-filer start check. It returns exit -1 on +// success, else the exit code after reporting. +func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.BCatalog, func() error, int) { + if filer == "" { + return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false) + } + f, closeFn, err := dialChunkFiler(filer) + if err != nil { + return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + fail := func(msg string) (*chunkstore.BCatalog, func() error, int) { + _ = closeFn() + return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, msg, false) + } + if writes { + if exit := refuseUnlessSingleFiler(name, f, timeout, stdout, stderr); exit >= 0 { + _ = closeFn() + return nil, nil, exit + } + } + blobs, ok := f.(chunkstore.Blobs) + if !ok { + return fail("the filer client does not reach the volume servers") + } + cat, err := chunkstore.NewBCatalog(f, blobs, base) + if err != nil { + return fail(err.Error()) + } + return cat, closeFn, -1 +} + +// volumeFlags name a volume; its layout id is resolved through the +// master's volume record (never minted, never read from the filer). +type volumeFlags struct { + name string + cmd *bCommand +} + +// resolveVolumeID resolves a volume name to its layout id at the master. +// Tests replace it. +var resolveVolumeID = func(ctx context.Context, master, name string) (layout.VolumeID, error) { + conn, err := link.DialMasterFromEnv(master) + if err != nil { + return layout.VolumeID{}, err + } + defer conn.Close() + return lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), name) +} + +func (c *bCommand) bindVolume(v *volumeFlags, flagName, what string) { + v.cmd = c + c.fs.StringVar(&v.name, flagName, "", what+" name") +} + +func (v volumeFlags) ref(flagName string) (chunkstore.VolumeRef, error) { + if v.name == "" { + return chunkstore.VolumeRef{}, errors.New("--" + flagName + " is required") + } + if v.cmd.master == "" { + return chunkstore.VolumeRef{}, errors.New("--master is required (it resolves the volume's layout id)") + } + ctx, cancel := context.WithTimeout(context.Background(), v.cmd.timeout) + defer cancel() + id, err := resolveVolumeID(ctx, v.cmd.master, v.name) + if err != nil { + return chunkstore.VolumeRef{}, fmt.Errorf("resolve --%s %q at the master: %w", flagName, v.name, err) + } + return chunkstore.VolumeRef{Name: v.name, ID: id}, nil +} + +// bCommand parses a catalog command's flags (with --chunk-filer, +// --chunk-path and --timeout) and opens the catalog. +type bCommand struct { + fs *flag.FlagSet + filer, base, master string + timeout time.Duration + stdout, stderr io.Writer +} + +func newBCommand(name string, timeout time.Duration, stdout, stderr io.Writer) *bCommand { + c := &bCommand{fs: chunkFlagSet(name, stderr), stdout: stdout, stderr: stderr} + c.fs.StringVar(&c.filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + c.fs.StringVar(&c.base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + c.fs.DurationVar(&c.timeout, "timeout", timeout, "filer timeout") + c.fs.StringVar(&c.master, "master", "", "blockmaster gRPC address (resolves each volume's layout id)") + return c +} + +// run parses args, resolves the refs, opens the catalog and calls do. +func (c *bCommand) run(args []string, writes bool, refs func() error, do func(context.Context, *chunkstore.BCatalog) (any, error)) int { + name := chunkName(c.fs) + if err := c.fs.Parse(args); err != nil { + return chunkFail(name, c.stdout, c.stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if err := refs(); err != nil { + return chunkFail(name, c.stdout, c.stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + cat, closeFn, exit := bCatalog(name, c.filer, c.base, writes, c.timeout, c.stdout, c.stderr) + if exit >= 0 { + return exit + } + defer closeFn() + ctx, cancel := context.WithTimeout(context.Background(), c.timeout) + defer cancel() + v, err := do(ctx, cat) + return chunkResult(name, v, err, c.stdout, c.stderr) +} + +// SnapshotEntry is one named snapshot of a volume's HEAD. +type SnapshotEntry struct { + Name string `json:"name"` + Root string `json:"root"` + Dependents []string `json:"dependents,omitempty"` +} + +// chunkSnapshots lists a volume's named snapshots, in name order. +func chunkSnapshots(args []string, stdout, stderr io.Writer) int { + c := newBCommand("snapshots", 30*time.Second, stdout, stderr) + var vol volumeFlags + var prefix string + c.bindVolume(&vol, "volume", "volume") + c.fs.StringVar(&prefix, "prefix", "", "only names with this prefix") + var ref chunkstore.VolumeRef + return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + h, found, err := cat.ReadHead(ctx, ref) + if err != nil { + return nil, err + } + if !found { + return nil, layout.ErrHeadAbsent + } + out := []SnapshotEntry{} + for n, s := range h.Snapshots { + if !strings.HasPrefix(n, prefix) { + continue + } + e := SnapshotEntry{Name: n, Root: s.Root.String()} + for _, d := range s.Dependents { + e.Dependents = append(e.Dependents, layout.VolumeDir(d.Target, d.TargetID)) + } + out = append(out, e) + } + sort.Slice(out, func(a, b int) bool { return out[a].Name < out[b].Name }) + return out, nil + }) +} + +// chunkSnapshotDelete removes a named snapshot; refused while a restore +// target depends on it. +func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { + c := newBCommand("snapshot-delete", 30*time.Second, stdout, stderr) + var vol volumeFlags + var name string + c.bindVolume(&vol, "volume", "volume") + c.fs.StringVar(&name, "name", "", "snapshot name") + var ref chunkstore.VolumeRef + return c.run(args, true, func() (err error) { + if name == "" { + return errors.New("--name is required") + } + ref, err = vol.ref("volume") + return err + }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + if _, err := cat.DeleteSnapshot(ctx, ref, name); err != nil { + return nil, err + } + return map[string]string{"volume": ref.Dir(), "name": name, "state": "absent"}, nil + }) +} + +// chunkShow prints a volume's VOLUME record and HEAD. +func chunkShow(args []string, stdout, stderr io.Writer) int { + c := newBCommand("show", 30*time.Second, stdout, stderr) + var vol volumeFlags + c.bindVolume(&vol, "volume", "volume") + var ref chunkstore.VolumeRef + return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + s, err := cat.Store(ref) + if err != nil { + return nil, err + } + body := struct { + Volume *layout.Volume `json:"volume"` + Head *layout.Head `json:"head"` + }{} + if v, ok, err := s.ReadVolumeRecord(ctx); err != nil { + return nil, err + } else if ok { + body.Volume = &v + } + if h, ok, err := s.ReadHead(ctx); err != nil { + return nil, err + } else if ok { + body.Head = &h + } + return body, nil + }) +} + +// chunkUsage prints a volume's snapshots, dependents and the chunks its +// current image names. +func chunkUsage(args []string, stdout, stderr io.Writer) int { + c := newBCommand("usage", 60*time.Second, stdout, stderr) + var vol volumeFlags + c.bindVolume(&vol, "volume", "volume") + var ref chunkstore.VolumeRef + return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + return cat.Usage(ctx, ref) + }) +} + +// chunkRestore creates a restore target from a source snapshot: the +// target reads the snapshot's chunks from the source's pool until its own +// writes replace them; the snapshot cannot be deleted while it depends on +// it. The target's layout id comes from its master record. +func chunkRestore(args []string, stdout, stderr io.Writer) int { + c := newBCommand("restore", 6*time.Minute, stdout, stderr) + var source, target, snapshot, requestID string + c.fs.StringVar(&source, "source", "", "source volume name") + c.fs.StringVar(&target, "target", "", "new volume name") + c.fs.StringVar(&snapshot, "snapshot", "", "source snapshot name") + c.fs.StringVar(&requestID, "request-id", "", "stable identity for retries of this restore") + if err := c.fs.Parse(args); err != nil { + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if source == "" || target == "" || snapshot == "" || c.master == "" || source == target { + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--source, --target, --snapshot and --master are required; source and target must differ", false) + } + if requestID == "" { + sum := sha256.Sum256([]byte(target + "\x00" + source + "\x00" + snapshot)) + requestID = "restore-" + hex.EncodeToString(sum[:16]) + } + ctx, cancel := context.WithTimeout(context.Background(), c.timeout) + defer cancel() + resp, err := restoreCreateRPC(ctx, c.master, &control.CreateVolumeRequest{ + VolumeId: target, SourceVolume: source, SourceSnapshot: snapshot, CreateRequestId: requestID, + }) + if err != nil { + switch status.Code(err) { + case codes.NotFound: + return chunkFail("restore", stdout, stderr, chunkExitFailed, "snapshot_not_found", err.Error(), false) + case codes.AlreadyExists: + return chunkFail("restore", stdout, stderr, chunkExitFailed, "target_exists", err.Error(), false) + case codes.InvalidArgument: + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + case codes.FailedPrecondition: + return chunkFail("restore", stdout, stderr, chunkExitFailed, "not_admitted", err.Error(), false) + case codes.Unavailable, codes.DeadlineExceeded: + return chunkFail("restore", stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true) + default: + return chunkResult("restore", nil, err, stdout, stderr) + } + } + if resp.GetVolumeId() != target || !resp.GetStoreReady() { + return chunkFail("restore", stdout, stderr, chunkExitFailed, codeUnavailableCLI, "master did not confirm the restored target is store-ready", true) + } + id, err := layout.ParseVolumeID(resp.GetLayoutId()) + if err != nil { + return chunkResult("restore", nil, err, stdout, stderr) + } + return chunkResult("restore", map[string]string{"source": source, "snapshot": snapshot, "target": (chunkstore.VolumeRef{Name: target, ID: id}).Dir(), "request_id": requestID}, nil, stdout, stderr) +} + +// chunkRelease removes a restore target from its source snapshot's +// dependents once the target is deleted or no longer names the source's +// chunks; a target without HEAD (a restore that never finished) is +// tombstoned first so it can never be created later. +func chunkRelease(args []string, stdout, stderr io.Writer) int { + c := newBCommand("release", 30*time.Second, stdout, stderr) + var src, tgt volumeFlags + c.bindVolume(&src, "source", "source volume") + c.bindVolume(&tgt, "target", "restore target") + var sref, tref chunkstore.VolumeRef + return c.run(args, true, func() (err error) { + if sref, err = src.ref("source"); err != nil { + return err + } + tref, err = tgt.ref("target") + return err + }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + if _, err := cat.ReleaseTarget(ctx, sref, tref); err != nil { + return nil, err + } + return map[string]string{"source": sref.Dir(), "target": tref.Dir(), "state": "released"}, nil + }) +} + +// layoutCode is the error code of a layout kernel refusal ("" for any +// other error); a lost conditional update is the one retryable code. +func layoutCode(err error) string { + for _, c := range []struct { + err error + code string + }{ + {layout.ErrNoSnapshot, "snapshot_not_found"}, + {layout.ErrHasDependents, "snapshot_has_dependents"}, + {layout.ErrForeignSource, "restore_source_not_own"}, + {layout.ErrHeadAbsent, "volume_not_found"}, + {layout.ErrExists, "target_exists"}, + {layout.ErrVolumeDeleting, "volume_deleting"}, + {layout.ErrHolderActive, "not_admitted"}, + {chunkstore.ErrNotAdmitted, "not_admitted"}, + {layout.ErrTargetLive, "target_live"}, + {layout.ErrIdentity, "identity_mismatch"}, + {layout.ErrGeometryMismatch, "geometry_mismatch"}, + {layout.ErrPrecondition, "conflict"}, + {retain.ErrInvalidPolicy, "invalid_policy"}, + } { + if errors.Is(err, c.err) { + return c.code + } + } + return "" +} + +// chunkRetain: sw-block ops chunk retain --volume v --master m +// --chunk-filer host:port [--dry-run] applies the volume's retention policy: +// it deletes the expired snapshots by the automatic snapshot delete, which +// refuses a pinned snapshot or one a restore target depends on. With +// --set-policy it stores the policy given by the --keep-* flags in the +// volume's RETENTION entry instead; a policy change applies from the next +// pass. +func chunkRetain(args []string, stdout, stderr io.Writer) int { + c := newBCommand("retain", 5*time.Minute, stdout, stderr) + var vol volumeFlags + var keepYounger time.Duration + var dryRun, setPolicy bool + var keepNewest, keepHourly, keepDaily, keepWeekly int + c.bindVolume(&vol, "volume", "volume") + c.fs.BoolVar(&dryRun, "dry-run", false, "list what would be deleted; write nothing") + c.fs.BoolVar(&setPolicy, "set-policy", false, "store the --keep-* policy on the volume instead of applying it") + c.fs.IntVar(&keepNewest, "keep-newest", retain.DefaultKeepNewest, "with --set-policy: keep the newest N unpinned snapshots") + c.fs.DurationVar(&keepYounger, "keep-younger", retain.DefaultKeepYounger, "with --set-policy: keep every snapshot younger than this") + c.fs.IntVar(&keepHourly, "keep-hourly", 0, "with --set-policy: keep the newest snapshot of each of the last N hours") + c.fs.IntVar(&keepDaily, "keep-daily", 0, "with --set-policy: keep the newest snapshot of each of the last N days") + c.fs.IntVar(&keepWeekly, "keep-weekly", 0, "with --set-policy: keep the newest snapshot of each of the last N weeks") + var ref chunkstore.VolumeRef + // The start check runs only for a pass that writes. + writes := true + for _, a := range args { + if a == "--dry-run" || a == "-dry-run" || a == "--dry-run=true" { + writes = false + } + } + return c.run(args, writes, func() (err error) { + if setPolicy && dryRun { + return errors.New("--set-policy and --dry-run do not combine") + } + ref, err = vol.ref("volume") + return err + }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + if setPolicy { + p := retain.Policy{KeepNewest: keepNewest, KeepYoungerNs: int64(keepYounger), KeepHourly: keepHourly, KeepDaily: keepDaily, KeepWeekly: keepWeekly} + if err := cat.SetRetention(ctx, ref, p); err != nil { + return nil, err + } + return map[string]any{"volume": ref.Dir(), "policy": p, "policySet": true}, nil + } + return cat.Retain(ctx, ref, chunkRetainNow(), dryRun) + }) +} + +// chunkRetainNow is the wall clock retention decides by. Tests replace it. +var chunkRetainNow = time.Now diff --git a/seaweed-block/cmd/sw-block/chunk_b_test.go b/seaweed-block/cmd/sw-block/chunk_b_test.go new file mode 100644 index 0000000000..60f36b922b --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_b_test.go @@ -0,0 +1,431 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "net" + "strings" + "sync" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// memChunkStore is a filer with its volume servers: entries in memory, +// needle payloads by fid. +type memChunkStore struct { + *chunkstore.MemFiler + mu sync.Mutex + blobs map[string][]byte +} + +func newMemChunkStore() *memChunkStore { + return &memChunkStore{MemFiler: chunkstore.NewMemFiler(), blobs: map[string][]byte{}} +} + +func (m *memChunkStore) Put(_ context.Context, data []byte) (string, error) { + m.mu.Lock() + defer m.mu.Unlock() + fid := fmt.Sprintf("1,%x", len(m.blobs)+1) + m.blobs[fid] = append([]byte(nil), data...) + return fid, nil +} + +func (m *memChunkStore) Get(_ context.Context, fid string) ([]byte, error) { + m.mu.Lock() + defer m.mu.Unlock() + b, ok := m.blobs[fid] + if !ok { + return nil, chunkstore.ErrBlobNotFound + } + return append([]byte(nil), b...), nil +} + +// testIDs is the master's volume records the commands resolve against: +// every volume a test names through volArgs. +var testIDs sync.Map + +// useMemChunkStore makes every ops chunk command dial store and resolve +// names against testIDs. +func useMemChunkStore(t *testing.T, store *memChunkStore) { + t.Helper() + prev, prevResolve, prevRestore := dialChunkFiler, resolveVolumeID, restoreCreateRPC + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } + resolveVolumeID = testResolve + restoreCreateRPC = func(ctx context.Context, _ string, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + sid, err := testResolve(ctx, "", req.GetSourceVolume()) + if err != nil { + return nil, err + } + tid, err := testResolve(ctx, "", req.GetVolumeId()) + if err != nil { + return nil, err + } + cat, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if err != nil { + return nil, err + } + _, err = cat.Restore(ctx, chunkstore.VolumeRef{Name: req.GetSourceVolume(), ID: sid}, req.GetSourceSnapshot(), chunkstore.VolumeRef{Name: req.GetVolumeId(), ID: tid}) + if err != nil { + return nil, err + } + return &control.CreateVolumeResponse{VolumeId: req.GetVolumeId(), LayoutId: tid.String(), StoreReady: true}, nil + } + t.Cleanup(func() { dialChunkFiler, resolveVolumeID, restoreCreateRPC = prev, prevResolve, prevRestore }) +} + +func testResolve(_ context.Context, _ string, name string) (layout.VolumeID, error) { + if id, ok := testIDs.Load(name); ok { + return id.(layout.VolumeID), nil + } + return layout.VolumeID{}, status.Error(codes.NotFound, "volume not found") +} + +type okLease struct{} + +func (okLease) OldLeaseEnded(context.Context, uint64) error { return nil } + +// cliVolume creates v with one chunk and a snapshot named snap of it, +// through the layout kernel's own steps. +func cliVolume(t *testing.T, store *memChunkStore, name, snap string) chunkstore.VolumeRef { + t.Helper() + ctx := context.Background() + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + v := chunkstore.VolumeRef{Name: name, ID: id} + cat, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + s, _ := cat.Store(v) + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + if _, err := layout.Start(ctx, s, okLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + if _, err := layout.RunBegin(ctx, s, me, "s1"); err != nil { + t.Fatal(err) + } + data := []byte("chunk of " + name) + ch := layout.NameChunk(1, data) + next := map[uint64]layout.Ref{1: {Owner: name, OwnerID: id, Chunk: ch}} + root, segs, _ := layout.Build(next) + rn, rb, _ := layout.NameRoot(root) + objs := map[string][]byte{ch.Path(): data, rn.Path(): rb} + for n, b := range segs { + objs[n.Path()] = b + } + for rel, b := range objs { + if err := layout.EnsureObject(ctx, s, rel, b, "s1"); err != nil { + t.Fatal(err) + } + } + if _, err := layout.RunCommit(ctx, s, s, name, me, layout.CommitRequest{Session: "s1", Next: next, Position: 1, Snapshot: snap}); err != nil { + t.Fatal(err) + } + return v +} + +func volArgs(flag string, v chunkstore.VolumeRef) []string { + testIDs.Store(v.Name, v.ID) + return []string{"--" + flag, v.Name} +} + +func cliArgs(cmd string, parts ...[]string) []string { + out := []string{cmd, "--chunk-filer", "filer:18888", "--master", "m:1"} + for _, p := range parts { + out = append(out, p...) + } + return out +} + +// The catalog commands on the layout: list, show, usage, restore, release +// refused while the target names the source, snapshot delete refused while +// depended on, and their error codes. +func TestOpsChunk_CatalogCommands(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + src := cliVolume(t, store, "src", "daily") + tid, _ := layout.NewVolumeID() + tgt := chunkstore.VolumeRef{Name: "t", ID: tid} + + code, out, errs := runChunk(cliArgs("snapshots", volArgs("volume", src))...) + var list []SnapshotEntry + if code != 0 || json.Unmarshal([]byte(out), &list) != nil || len(list) != 1 || list[0].Name != "daily" { + t.Fatalf("snapshots: %d %q %q", code, out, errs) + } + if code, out, _ := runChunk(cliArgs("show", volArgs("volume", src))...); code != 0 || !strings.Contains(out, `"Name":"src"`) || !strings.Contains(out, `"Epoch":1`) { + t.Fatalf("show: %d %q", code, out) + } + if code, out, errs := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "daily"})...); code != 0 || !strings.Contains(out, tgt.Dir()) { + t.Fatalf("restore: %d %q %q", code, out, errs) + } + if code, out, _ := runChunk(cliArgs("usage", volArgs("volume", tgt))...); code != 0 || !strings.Contains(out, `"foreign_chunks":1`) { + t.Fatalf("target usage: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", src), []string{"--name", "daily"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_has_dependents" { + t.Fatalf("delete a depended-on snapshot: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("release", volArgs("source", src), volArgs("target", tgt))...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "target_live" { + t.Fatalf("release of a target still naming the source: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "weekly"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_not_found" { + t.Fatalf("restore of a missing snapshot: %d %q", code, out) + } + if code, out, _ := runChunk("snapshots", "--chunk-filer", "f:1", "--volume", "src"); code != 2 || !strings.Contains(out, "--master is required") { + t.Fatalf("snapshots without --master: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("snapshots", []string{"--volume", "unknown-to-the-master"})...); code != 2 || !strings.Contains(out, "resolve --volume") { + t.Fatalf("snapshots of a volume the master does not know: %d %q", code, out) + } +} + +// fakeLifecycle is the blockmaster's delete authority: the reservation is +// refused while held (a live line); leaseAfterReserve grants a lease right +// after the reservation is committed (a grant racing the admission), which +// the master's check then reports; every call is recorded. +type fakeLifecycle struct { + control.UnimplementedLifecycleServiceServer + mu sync.Mutex + held bool + leaseAfterReserve bool + reserved, leased bool + calls []string +} + +func (f *fakeLifecycle) record(name string) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, name) +} + +func (f *fakeLifecycle) ReserveVolumeDeletion(_ context.Context, r *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) { + f.record("reserve") + if f.held { + return nil, status.Error(codes.FailedPrecondition, "volume has a live authority line") + } + f.reserved = true + if f.leaseAfterReserve { + f.leased = true + } + return &control.MarkVolumeDeletingResponse{Known: true}, nil +} + +func (f *fakeLifecycle) CheckVolumeNoLiveLease(context.Context, *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) { + f.record("check") + if !f.reserved || f.leased { + return nil, status.Error(codes.FailedPrecondition, "a line of the volume holds a live lease") + } + return &control.MarkVolumeDeletingResponse{Known: true}, nil +} + +func startFakeLifecycle(t *testing.T, f *fakeLifecycle) string { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + control.RegisterLifecycleServiceServer(srv, f) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + return lis.Addr().String() +} + +// volume-delete: refused while the master holds the volume (nothing +// written); a volume whose snapshot has a dependent is refused and the +// permanent reservation retained; a restore target deletes and releases its source. +func TestOpsChunk_VolumeDeleteOnTheLayout(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + src := cliVolume(t, store, "src", "daily") + tid, _ := layout.NewVolumeID() + tgt := chunkstore.VolumeRef{Name: "t", ID: tid} + if code, out, errs := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "daily"})...); code != 0 { + t.Fatalf("restore: %d %q %q", code, out, errs) + } + del := func(lc *fakeLifecycle, v chunkstore.VolumeRef) (int, string) { + addr := startFakeLifecycle(t, lc) + code, out, _ := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "r1"})...) + return code, out + } + objects := func(v chunkstore.VolumeRef) int { + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + u, err := cat.Usage(context.Background(), v) + if err != nil { + return -1 + } + return u.OwnChunks + u.ForeignChunks + } + held := &fakeLifecycle{held: true} + if code, out := del(held, tgt); code != chunkExitFailed || chunkErrorOut(t, out).Code != "not_admitted" || strings.Join(held.calls, ",") != "reserve" { + t.Fatalf("delete of a held volume: %d %q calls %v", code, out, held.calls) + } + // A grant racing the reservation: the master's check between the HEAD + // read and the update refuses, and nothing is deleted. + race := &fakeLifecycle{leaseAfterReserve: true} + if code, out := del(race, tgt); code != chunkExitFailed || chunkErrorOut(t, out).Code != "not_admitted" || strings.Join(race.calls, ",") != "reserve,check" || objects(tgt) != 1 { + t.Fatalf("delete with a lease granted after the reservation: %d %q calls %v objects %d; want refused by the check, nothing deleted", code, out, race.calls, objects(tgt)) + } + if h, _, _ := func() (layout.Head, bool, error) { + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + return cat.ReadHead(context.Background(), tgt) + }(); h.State != layout.StateLive { + t.Fatalf("HEAD after the refused delete: %s; want live", h.State) + } + if code, out := del(&fakeLifecycle{}, src); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_has_dependents" { + t.Fatalf("delete of a depended-on source: %d %q", code, out) + } + ok := &fakeLifecycle{} + if code, out := del(ok, tgt); code != 0 || !strings.Contains(out, `"state":"deleted"`) || strings.Join(ok.calls, ",") != "reserve,check" { + t.Fatalf("delete of the target: %d %q calls %v", code, out, ok.calls) + } + if code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", src), []string{"--name", "daily"})...); code != 0 { + t.Fatalf("delete the released snapshot: %d %q", code, out) + } +} + +// A volume never created: snapshots refuses volume_not_found, show prints +// a null head, volume-delete refuses before asking the master. +func TestOpsChunk_AbsentVolume(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + id, _ := layout.NewVolumeID() + v := chunkstore.VolumeRef{Name: "never", ID: id} + if code, out, _ := runChunk(cliArgs("snapshots", volArgs("volume", v))...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" { + t.Fatalf("snapshots of an absent volume: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("show", volArgs("volume", v))...); code != 0 || !strings.Contains(out, `"head":null`) { + t.Fatalf("show of an absent volume: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("retain", volArgs("volume", v))...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" { + t.Fatalf("retain of an absent volume: %d %q", code, out) + } + lc := &fakeLifecycle{} + addr := startFakeLifecycle(t, lc) + if code, out, _ := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "r"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" || len(lc.calls) != 0 { + t.Fatalf("delete of an absent volume: %d %q calls %v; want volume_not_found before any admission", code, out, lc.calls) + } +} + +// addSnapshot names v's current image again as snapshot name (a new +// snapshot transaction with no new chunks). +func addSnapshot(t *testing.T, store *memChunkStore, v chunkstore.VolumeRef, name string, meta layout.SnapshotMeta, session string, position uint64) { + t.Helper() + ctx := context.Background() + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + s, _ := cat.Store(v) + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + h, _, _ := s.ReadHead(ctx) + r, _ := layout.NewReader(defaultChunkPathCLI, v.Dir(), s.Fetch) + img, err := r.Open(ctx, *h.Current) + if err != nil { + t.Fatal(err) + } + ref, _, _ := img.Resolve(ctx, 1) + m := map[uint64]layout.Ref{1: ref} + if _, err := layout.RunBegin(ctx, s, me, session); err != nil { + t.Fatal(err) + } + root, segs, _ := layout.Build(m) + rn, rb, _ := layout.NameRoot(root) + objs := map[string][]byte{rn.Path(): rb} + for n, b := range segs { + objs[n.Path()] = b + } + for rel, b := range objs { + if err := layout.EnsureObject(ctx, s, rel, b, session); err != nil { + t.Fatal(err) + } + } + if _, err := layout.RunCommit(ctx, s, s, v.Name, me, layout.CommitRequest{Session: session, Prev: m, Next: m, Position: position, Snapshot: name, Meta: meta}); err != nil { + t.Fatal(err) + } +} + +// retain stores a policy with --set-policy and applies it: the newest +// unpinned snapshots by creation time are kept, the expired ones deleted, +// a pinned one kept, one a restore target depends on refused and +// reported; --dry-run writes nothing. +func TestOpsChunk_Retain(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "v", "") + now := time.Unix(20_000_000, 0) + prevNow := chunkRetainNow + chunkRetainNow = func() time.Time { return now } + t.Cleanup(func() { chunkRetainNow = prevNow }) + for i, f := range []struct { + name string + hours int + class string + }{{"n1", 1, layout.ClassSemantic}, {"n2", 2, layout.ClassSemantic}, {"n3", 3, layout.ClassSemantic}, {"n4", 4, layout.ClassSemantic}, {"keep", 9, layout.ClassPinned}} { + addSnapshot(t, store, v, f.name, layout.SnapshotMeta{CreatedNs: now.Add(-time.Duration(f.hours) * time.Hour).UnixNano(), Class: f.class}, fmt.Sprintf("s%d", i+2), uint64(i+2)) + } + tid, _ := layout.NewVolumeID() + if code, out, errs := runChunk(cliArgs("restore", volArgs("source", v), volArgs("target", chunkstore.VolumeRef{Name: "t", ID: tid}), []string{"--snapshot", "n4"})...); code != 0 { + t.Fatalf("restore: %d %q %q", code, out, errs) + } + if code, out, errs := runChunk(cliArgs("retain", volArgs("volume", v), []string{"--set-policy", "--keep-newest", "2", "--keep-younger", "0s"})...); code != 0 || !strings.Contains(out, `"policySet":true`) { + t.Fatalf("set policy: %d %q %q", code, out, errs) + } + run := func(extra ...string) chunkstore.RetainResult { + t.Helper() + code, out, errs := runChunk(cliArgs("retain", volArgs("volume", v), extra)...) + var r chunkstore.RetainResult + if code != 0 || json.Unmarshal([]byte(out), &r) != nil { + t.Fatalf("retain %v: %d %q %q", extra, code, out, errs) + } + return r + } + if dry := run("--dry-run"); strings.Join(dry.Deleted, ",") != "n3,n4" { + t.Fatalf("dry run: %+v", dry) + } + got := run() + if strings.Join(got.Deleted, ",") != "n3" || strings.Join(got.Refused, ",") != "n4" { + t.Fatalf("retain: deleted %v refused %v; want n3 and n4 refused", got.Deleted, got.Refused) + } + code, out, _ := runChunk(cliArgs("snapshots", volArgs("volume", v))...) + var list []SnapshotEntry + if code != 0 || json.Unmarshal([]byte(out), &list) != nil || len(list) != 4 { + t.Fatalf("after retain: %d %q; want keep,n1,n2,n4", code, out) + } + if code, out, _ := runChunk(cliArgs("retain", volArgs("volume", v), []string{"--set-policy", "--dry-run"})...); code != 2 { + t.Fatalf("--set-policy with --dry-run: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("retain", volArgs("volume", v), []string{"--set-policy", "--keep-newest", "-1"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "invalid_policy" { + t.Fatalf("negative policy: %d %q", code, out) + } +} + +func TestOpsChunkVolumeDeleteRequiresTheMastersLeaseProof(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "leased", "daily") + lc := &fakeLifecycle{leased: true} + addr := startFakeLifecycle(t, lc) + code, out, _ := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "delete-v"})...) + if code == 0 { + t.Fatalf("deleted a volume with live lease: %q calls=%v", out, lc.calls) + } + if got := strings.Join(lc.calls, ","); got != "reserve,check" { + t.Fatalf("authority path=%s", got) + } + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + h, found, err := cat.ReadHead(context.Background(), v) + if err != nil || !found || h.State != layout.StateLive { + t.Fatalf("HEAD changed despite refused proof: %+v %v %v", h, found, err) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_delete_authority_guard_test.go b/seaweed-block/cmd/sw-block/chunk_delete_authority_guard_test.go new file mode 100644 index 0000000000..e832c2956b --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_delete_authority_guard_test.go @@ -0,0 +1,53 @@ +package main + +import ( + "go/ast" + "go/parser" + "go/token" + "testing" +) + +// The operator must never replace the master's proof with local admission. +func TestChunkVolumeDeleteAuthorityRPCSites(t *testing.T) { + for _, tc := range []struct { + file string + want map[string]int + }{ + {"chunk_volume_delete.go", map[string]int{"ReserveVolumeDeletion": 1, "CheckVolumeNoLiveLease": 1, "DialMasterFromEnv": 1}}, + // resolveVolumeID reads the name binding; restoreCreateRPC makes the + // restore's one master CreateVolume call (TestOpsChunkRestoreUsesOnlyMasterCreate). + {"chunk_b.go", map[string]int{"DialMasterFromEnv": 2}}, + {"../../core/host/master/volume_delete_authority.go", map[string]int{"VolumeDeleteAuthority": 2, "Reserve": 1, "NoLiveLease": 1}}, + } { + f, err := parser.ParseFile(token.NewFileSet(), tc.file, nil, 0) + if err != nil { + t.Fatal(err) + } + got := map[string]int{} + ast.Inspect(f, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + switch sel.Sel.Name { + case "Dial", "DialMasterFromEnv", "ReserveVolumeDeletion", "CheckVolumeNoLiveLease", "MarkVolumeDeleting", "AbortVolumeDeleting", "CommitVolumeDeleting", "VolumeDeleteAuthority", "Reserve", "NoLiveLease": + got[sel.Sel.Name]++ + } + return true + }) + for site, n := range got { + if tc.want[site] != n { + t.Errorf("%s: authority site %s=%d, want %d", tc.file, site, n, tc.want[site]) + } + } + for site, n := range tc.want { + if got[site] != n { + t.Errorf("%s: missing authority site %s=%d, want %d", tc.file, site, got[site], n) + } + } + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go deleted file mode 100644 index 0b323b1304..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ /dev/null @@ -1,109 +0,0 @@ -package main - -import ( - "context" - "errors" - "fmt" - "io" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/ops" - "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/rpc/link" -) - -// Same clock seam as GCConfig; production always uses wall time. Tests can -// advance grace without sleeping while using actual master/store services. -var chunkGCNow = time.Now - -func chunkGC(args []string, stdout, stderr io.Writer) int { - fs := chunkFlagSet("gc", stderr) - var filer, base, master string - var apply bool - var grace, ttl, timeout time.Duration - fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address") - fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "chunk catalog namespace") - fs.StringVar(&master, "master", "", "authoritative blockmaster gRPC address") - fs.BoolVar(&apply, "apply", false, "settle intents, save completed marks and reclaim eligible chunks; default is read-only") - fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (at least the operation deadline + clock skew + CAS apply bound, and more than the operation deadline plus mark time)") - fs.DurationVar(&ttl, "intent-ttl", time.Hour, "minimum capture-intent age before authoritative epoch expiry") - fs.DurationVar(&timeout, "timeout", time.Minute, "bound for this pass, including master/filer/blob calls") - if e := fs.Parse(args); e != nil { - return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, e.Error(), false) - } - if fs.NArg() != 0 || filer == "" || master == "" || timeout <= 0 || ttl <= 0 || grace <= chunkstore.DefaultOpDeadline { - return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer and --master are required; durations must be positive and grace must exceed the operation deadline", false) - } - f, closeFn, e := dialChunkFiler(filer) - if e != nil { - return chunkResult("gc", nil, e, stdout, stderr) - } - defer closeFn() - if apply { - if exit := refuseUnlessSingleFiler("gc", f, timeout, stdout, stderr); exit >= 0 { - return exit - } - } - blobs, ok := f.(chunkstore.BlobDeleter) - if !ok { - return chunkFail("gc", stdout, stderr, chunkExitFailed, codeInternalCLI, "chunk store cannot delete immutable blobs", false) - } - cat, e := chunkstore.NewCatalog(f, base) - if e != nil { - return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, e.Error(), false) - } - evidence, closeMaster, e := masterEvidence(master) - if e != nil { - return chunkResult("gc", nil, e, stdout, stderr) - } - defer closeMaster() - issuedEpoch := func(ctx context.Context, vol string) (uint64, error) { - reply, e := evidence.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: vol}) - if e != nil { - return 0, e - } - if reply.GetVolumeId() != vol || !reply.GetAssigned() || reply.GetEpoch() == 0 { - return 0, fmt.Errorf("blockmaster has no issued authority for %s", vol) - } - return reply.Epoch, nil - } - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - out, e := cat.ExecuteGC(ctx, blobs, chunkstore.GCConfig{Grace: grace, IntentTTL: ttl, Now: chunkGCNow, IssuedEpoch: issuedEpoch}, apply) - return chunkGCResult(out, e, stdout, stderr) -} - -// masterEvidence dials the blockmaster's evidence service (gc and -// volume-delete read volume status from it). -func masterEvidence(master string) (control.EvidenceServiceClient, func() error, error) { - conn, e := link.DialMasterFromEnv(master) - if e != nil { - return nil, nil, e - } - return control.NewEvidenceServiceClient(conn), conn.Close, nil -} - -// Error status and code remain failures, but a failure must not erase known -// effects or imply that a lost write response means the write did not commit. -func chunkGCResult(out chunkstore.GCExecution, err error, stdout, stderr io.Writer) int { - if err == nil { - return chunkResult("gc", out, nil, stdout, stderr) - } - body := struct { - chunkErrBody - GC chunkstore.GCExecution `json:"gc"` - }{GC: out} - body.Code, body.Message = codeInternalCLI, err.Error() - var ce *chunkstore.CatalogError - switch { - case errors.As(err, &ce): - body.Code, body.Message, body.Retryable = ce.Code, ce.Detail(), ce.Retryable - case errors.Is(err, context.DeadlineExceeded): - body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true - } - fmt.Fprintf(stderr, "sw-block ops chunk gc: %s: %s\n", body.Code, body.Message) - // chunkResult also propagates output errors; either outcome remains FAIL. - chunkResult("gc", body, nil, stdout, stderr) - return chunkExitFailed -} diff --git a/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go b/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go deleted file mode 100644 index 2215732638..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_gc_integration_test.go +++ /dev/null @@ -1,379 +0,0 @@ -//go:build chunkstore_integration - -package main - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/json" - "fmt" - "io" - "net" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/authority" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/host/master" - "github.com/seaweedfs/seaweed-block/core/lifecycle" - "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/storage" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" -) - -// No mocked filer, needle service or authority RPC. Only the GC clock is -// advanced so the test exercises two grace-separated marks without a long soak. -func TestIntegration_OpsChunkGC_RealMasterAndStore(t *testing.T) { - weed := os.Getenv("CHUNKSTORE_WEED") - if weed == "" { - t.Fatal("CHUNKSTORE_WEED required: real-service acceptance must not silently skip") - } - filer := startGCWeed(t, weed) - ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) - defer cancel() - const base = "/swblock/gc-cli-test" - s, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: filer, Collection: "swblock", AssignPath: base}) - if err != nil { - t.Fatal(err) - } - defer s.Close() - // Wait for the real volume registration/assign path, bounded by ctx. - var unboundFID string - for { - unboundFID, err = s.Put(ctx, []byte("readiness")) - if err == nil { - break - } - select { - case <-ctx.Done(): - t.Fatal(err) - case <-time.After(200 * time.Millisecond): - } - } - // Verify persisted configuration, not shell exit alone. SaveInsideFiler - // stores this small configuration inline in the actual filer. - conf, err := s.LookupEntry(ctx, "/etc/seaweedfs", "filer.conf") - if err != nil || len(conf.GetChunks()) != 0 { - t.Fatalf("fsync configuration unavailable: %v %v", conf, err) - } - var persisted struct { - Locations []struct { - LocationPrefix string `json:"locationPrefix"` - Collection string `json:"collection"` - Fsync bool `json:"fsync"` - } `json:"locations"` - } - if err := json.Unmarshal(conf.Content, &persisted); err != nil || len(persisted.Locations) != 1 { - t.Fatalf("invalid filer configuration: %s %v", conf.Content, err) - } - rule := persisted.Locations[0] - if rule.LocationPrefix != "/swblock/" || rule.Collection != "swblock" || !rule.Fsync { - t.Fatalf("unexpected filer configuration: %s", conf.Content) - } - t.Logf("verified filer configuration: %s", conf.Content) - cat, err := chunkstore.NewCatalog(s, base) - if err != nil { - t.Fatal(err) - } - if _, err = cat.EnsureVolume(ctx, "vol-a", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } - remote, err := chunkstore.NewSWFSChunkRemote(s, base+"/vol-a") - if err != nil { - t.Fatal(err) - } - data := []byte("exact reachable bytes") - for _, key := range []string{"live", "held", "copy", "orphan"} { - if err = remote.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - } - h, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - h.Epoch = 1 - h.Holder = "holder-a" - h.RemoteLSN = 1 - h.Chunks = map[uint64]storage.ChunkRef{0: {Key: "live", SHA256: sha256.Sum256(data)}} - flat := h - segmented, segmentIntents, err := remote.PrepareManifest(ctx, flat, h, 8*4096) - if err != nil { - t.Fatal(err) - } - h = segmented - h.Gen, err = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 0}, h) - if err == nil { - for _, id := range segmentIntents { - if err = remote.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - } - if h.Segments == nil || len(h.Segments) != 1 { - t.Fatal("real-service acceptance requires a segmented root") - } - - if err != nil { - t.Fatal(err) - } - if _, err = cat.CreateSnapshot(ctx, "vol-a", chunkstore.SnapshotRequest{Name: "saved", RequestID: "gc-snapshot"}, h); err != nil { - t.Fatal(err) - } - if _, err = remote.PutIntent(ctx, storage.ChunkIntent{Gen: h.Gen, Epoch: 1, Holder: "holder-a", Keys: []string{"held"}}); err != nil { - t.Fatal(err) - } - // Old-format copy intents have no deadline: they must remain roots. - if _, err = remote.PutIntent(ctx, storage.ChunkIntent{Gen: h.Gen, Epoch: 1, Holder: "snapshot:vol-a/pending/attempt", Keys: []string{"copy"}}); err != nil { - t.Fatal(err) - } - cfg := gcTestMasterConfig(t) - cfg.LifecycleStoreDir = t.TempDir() - m, err := master.New(cfg) - if err != nil { - t.Fatal(err) - } - m.Start() - t.Cleanup(func() { - c, stop := context.WithTimeout(context.Background(), 5*time.Second) - defer stop() - if err := m.Close(c); err != nil { - t.Error(err) - } - }) - // The remote catalog VOLUME is distinct from the master's desired-volume - // registry. Register the live RF1 volume before observations mint authority. - if _, err = m.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 64 * 4096, ReplicationFactor: 1}); err != nil { - t.Fatal(err) - } - if _, err = m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "vol-a", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "vol-a", ServerID: "node-a", ReplicaID: "r2", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { - t.Fatal(err) - } - if err = m.ObservationHost().Ingest(authority.Observation{ServerID: "node-a", ObservedAt: time.Now().UTC(), Slots: []authority.SlotFact{{VolumeID: "vol-a", ReplicaID: "r2", DataAddr: "127.0.0.1:9202", CtrlAddr: "127.0.0.1:9102"}}}); err != nil { - t.Fatal(err) - } - if _, err = m.RunLifecycleProductTick(); err != nil { - t.Fatal(err) - } - conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - t.Fatal(err) - } - defer conn.Close() - status, err := control.NewEvidenceServiceClient(conn).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: "vol-a"}) - if err != nil || !status.GetAssigned() || status.GetEpoch() != 1 { - t.Fatalf("real authority: %v %v", status, err) - } - oldClock := chunkGCNow - defer func() { chunkGCNow = oldClock }() - now := time.Now().Add(2 * time.Hour) - chunkGCNow = func() time.Time { return now } - call := func(apply bool) chunkstore.GCExecution { - t.Helper() - args := []string{"gc", "--master", m.Addr(), "--chunk-filer", filer, "--chunk-path", base} - if apply { - args = append(args, "--apply") - } - rc, out, stderr := runChunk(args...) - if rc != 0 { - t.Fatalf("gc rc=%d %s %s", rc, out, stderr) - } - var result chunkstore.GCExecution - if err := json.Unmarshal([]byte(out), &result); err != nil { - t.Fatal(err) - } - t.Logf("apply=%v %s", apply, out) - return result - } - preview := call(false) - for _, kind := range []string{"HEAD", "snapshot", "capture_intent", "retained_copy_intent"} { - found := false - for _, r := range preview.Roots { - found = found || r.Kind == kind - } - if !found { - t.Fatalf("missing root %s: %+v", kind, preview) - } - } - if preview.MarkSaved || preview.Reclaimed != 0 || len(preview.WouldDelete) != 0 { - t.Fatalf("first preview: %+v", preview) - } - first := call(true) - if !first.MarkSaved || first.Reclaimed != 0 { - t.Fatalf("first mark: %+v", first) - } - now = now.Add(time.Hour + chunkstore.DefaultGCClockSkew + time.Second) - preview = call(false) - if preview.Reclaimed != 0 || len(preview.WouldDelete) != 1 || preview.WouldDelete[0].Key != "orphan" { - t.Fatalf("mature preview: %+v", preview) - } - if got, err := remote.Get(ctx, "orphan"); err != nil || !bytes.Equal(got, data) { - t.Fatalf("preview deleted blob: %q %v", got, err) - } - if got, err := s.Get(ctx, preview.WouldDelete[0].FID); err != nil || !bytes.Equal(got, data) { - t.Fatalf("raw orphan before delete: %q %v", got, err) - } - applied := call(true) - if applied.Reclaimed != 1 || applied.ExpiredIntents != 0 || !applied.MarkSaved { - t.Fatalf("apply: %+v", applied) - } - if _, err := s.Get(ctx, preview.WouldDelete[0].FID); err == nil { - t.Fatal("raw orphan needle still readable after DELETE") - } - if _, err = remote.Get(ctx, "orphan"); err == nil { - t.Fatal("orphan still readable") - } - for _, key := range []string{"live", "held", "copy"} { - if got, err := remote.Get(ctx, key); err != nil || !bytes.Equal(got, data) { - t.Fatalf("lost root %s: %q %v", key, got, err) - } - } - intents, err := remote.ListIntents(ctx) - if err != nil || len(intents) != 2 { - t.Fatalf("lost intent: %v %v", intents, err) - } - snaps, _, err := cat.ListSnapshots(ctx, "vol-a", chunkstore.ListOptions{}) - if err != nil || len(snaps) != 1 { - t.Fatalf("lost snapshot: %v %v", snaps, err) - } - if err = remote.Put(ctx, "orphan", data); err == nil { - t.Fatal("GC removed permanent binding tombstone") - } - - // The real authority runtime issues a higher epoch; the actual remote HEAD - // must also advance before the capture intent can be retired. No lease clock - // or fabricated epoch callback is used by the CLI. - if _, err := m.FailbackAuthorityRuntime().ExecuteFailback(ctx, authority.FailbackRuntimeRequest{ - VolumeID: "vol-a", ReplicaID: "r1", TargetDataAddr: "127.0.0.1:9201", TargetCtrlAddr: "127.0.0.1:9101", - ExpectedCurrentReplicaID: "r2", ExpectedCurrentEpoch: 1, AckEligible: true, FrontendFencedBeforeFailback: true, - DurableFrontierCovered: true, NoCrossVolumeIdentityChange: true, - }); err != nil { - t.Fatal(err) - } - issued, err := control.NewEvidenceServiceClient(conn).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: "vol-a"}) - if err != nil || issued.GetEpoch() <= 1 { - t.Fatalf("higher issued epoch: %v %v", issued, err) - } - stillHeld := call(false) - if len(stillHeld.WouldExpireIntents) != 0 { - t.Fatal("issued epoch without HEAD fence expired intent") - } - cur, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - next := cur - next.Epoch = issued.Epoch - next.Holder = "holder-b" - if _, err = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil { - t.Fatal(err) - } - expired := call(true) - if expired.ExpiredIntents != 1 || expired.Reclaimed != 0 { - t.Fatalf("fenced intent admission: %+v", expired) - } - now = now.Add(time.Hour + chunkstore.DefaultGCClockSkew + time.Second) - reclaimed := call(true) - if reclaimed.Reclaimed != 1 || len(reclaimed.WouldDelete) != 1 || reclaimed.WouldDelete[0].Key != "held" { - t.Fatalf("expired capture: %+v", reclaimed) - } - if got, err := s.Get(ctx, unboundFID); err != nil || string(got) != "readiness" { - t.Fatalf("unbound needle reclaimed: %q %v", got, err) - } - for _, key := range []string{"live", "copy"} { - if got, err := remote.Get(ctx, key); err != nil || !bytes.Equal(got, data) { - t.Fatalf("lost surviving root %s: %q %v", key, got, err) - } - } -} - -func startGCWeed(t *testing.T, weed string) string { - t.Helper() - dir := t.TempDir() - used := map[int]bool{} - port := func() int { - t.Helper() - for p := 21000; p < 40000; p++ { - if used[p] || used[p+10000] { - continue - } - a, e := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p)) - if e != nil { - continue - } - b, e := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p+10000)) - a.Close() - if e != nil { - continue - } - b.Close() - used[p] = true - used[p+10000] = true - return p - } - t.Fatal("no free ports") - return 0 - } - mp, vp, fp := port(), port(), port() - run := func(args ...string) { - t.Helper() - cmd := exec.Command(weed, args...) - cmd.Dir = dir - cmd.Stdout = io.Discard - cmd.Stderr = io.Discard - if err := cmd.Start(); err != nil { - t.Fatal(err) - } - done := make(chan error, 1) - go func() { done <- cmd.Wait() }() - t.Cleanup(func() { - _ = cmd.Process.Kill() - select { - case <-done: - case <-time.After(5 * time.Second): - t.Error("weed child did not settle") - } - }) - } - for _, name := range []string{"m", "v", "f"} { - if err := os.MkdirAll(filepath.Join(dir, name), 0700); err != nil { - t.Fatal(err) - } - } - masterAddr := fmt.Sprintf("127.0.0.1:%d", mp) - run("master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000") - wait := func(p int) { - t.Helper() - deadline := time.Now().Add(20 * time.Second) - for time.Now().Before(deadline) { - c, e := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", p), 100*time.Millisecond) - if e == nil { - c.Close() - return - } - time.Sleep(100 * time.Millisecond) - } - t.Fatalf("weed port %d not ready", p) - } - wait(mp) - run("volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+masterAddr, "-max=32") - run("filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+masterAddr, "-defaultStoreDir="+filepath.Join(dir, "f")) - wait(fp + 10000) - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - defer cancel() - configure := exec.CommandContext(ctx, weed, "shell", "-master="+masterAddr, fmt.Sprintf("-filer=127.0.0.1:%d", fp)) - configure.Dir = dir - configure.Stdin = strings.NewReader("fs.configure -locationPrefix=/swblock/ -collection=swblock -fsync -apply\n") - configure.Stdout, configure.Stderr = io.Discard, io.Discard - configure.WaitDelay = 2 * time.Second - if err := configure.Run(); err != nil { - t.Fatalf("configure filer durability: %v", err) - } - return fmt.Sprintf("127.0.0.1:%d", fp+10000) -} diff --git a/seaweed-block/cmd/sw-block/chunk_gc_master_test.go b/seaweed-block/cmd/sw-block/chunk_gc_master_test.go deleted file mode 100644 index 10485b69ef..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_gc_master_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "github.com/seaweedfs/seaweed-block/core/host/master" - "testing" -) - -// Centralize the temporary authority runtime configuration separately from -// chunk-upload callers. Authority is issued by the real master runtime; -// callers never seed durable authority records directly. -func gcTestMasterConfig(t *testing.T) master.Config { - t.Helper() - return master.Config{AuthorityStoreDir: t.TempDir(), Listen: "127.0.0.1:0"} -} diff --git a/seaweed-block/cmd/sw-block/chunk_gc_test.go b/seaweed-block/cmd/sw-block/chunk_gc_test.go deleted file mode 100644 index c8d49708c0..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_gc_test.go +++ /dev/null @@ -1,284 +0,0 @@ -package main - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/host/master" -) - -type gcCLIStore struct { - writes int - blobs map[string][]byte - failDeleteAt int - afterUpdate func(*filerpb.Entry) error - *chunkstore.MemFiler - deletes int -} - -func (s *gcCLIStore) Put(_ context.Context, data []byte) (string, error) { - if s.blobs == nil { - s.blobs = map[string][]byte{} - } - fid := fmt.Sprintf("1,%d", len(s.blobs)+1) - s.blobs[fid] = append([]byte{}, data...) - return fid, nil -} -func (s *gcCLIStore) Get(_ context.Context, fid string) ([]byte, error) { - b, ok := s.blobs[fid] - if !ok { - return nil, errors.New("missing blob") - } - return b, nil -} -func (s *gcCLIStore) DeleteBlob(_ context.Context, fid string) error { - s.deletes++ - delete(s.blobs, fid) - if s.deletes == s.failDeleteAt { - return errors.New("delete response lost") - } - return nil -} - -func TestOpsChunkGC_DefaultIsReadOnly(t *testing.T) { - h, e := master.New(gcTestMasterConfig(t)) - if e != nil { - t.Fatal(e) - } - h.Start() - defer func() { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if e := h.Close(ctx); e != nil { - t.Error(e) - } - }() - store := &gcCLIStore{MemFiler: chunkstore.NewMemFiler()} - old := dialChunkFiler - defer func() { dialChunkFiler = old }() - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } - code, out, errs := runChunk("gc", "--master", h.Addr(), "--chunk-filer", "local-test", "--chunk-path", "/gc-test") - if code != 0 { - t.Fatalf("missing safe GC entrypoint: exit=%d out=%s stderr=%s", code, out, errs) - } - var report struct { - DryRun bool `json:"dry_run"` - Roots []any `json:"roots"` - WouldDelete []any `json:"would_delete"` - } - if e := json.Unmarshal([]byte(out), &report); e != nil || !report.DryRun || report.Roots == nil || report.WouldDelete == nil { - t.Fatalf("incomplete dry-run report: %s %v", out, e) - } - entries, e := store.ListEntries(context.Background(), "/gc-test", "", "", 100) - if e != nil || len(entries) != 0 || store.deletes != 0 || store.writes != 0 { - t.Fatalf("default GC mutated store: entries=%d deletes=%d err=%v", len(entries), store.deletes, e) - } -} - -func (s *gcCLIStore) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, excl bool) error { - s.writes++ - return s.MemFiler.CreateEntry(ctx, dir, e, excl) -} -func (s *gcCLIStore) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { - s.writes++ - if err := s.MemFiler.UpdateEntry(ctx, dir, e, expected); err != nil { - return err - } - if s.afterUpdate != nil { - return s.afterUpdate(e) - } - return nil -} -func (s *gcCLIStore) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { - s.writes++ - return s.MemFiler.DeleteEntry(ctx, dir, name, expected) -} - -func TestOpsChunkGC_InvalidAdmissionHasNoStoreEffects(t *testing.T) { - old := dialChunkFiler - defer func() { dialChunkFiler = old }() - calls := 0 - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { - calls++ - t.Fatal("invalid request reached store") - return nil, nil, nil - } - for _, args := range [][]string{ - {"gc"}, - {"gc", "--chunk-filer", "store", "--master", "master", "--grace", "5m"}, - {"gc", "--chunk-filer", "store", "--master", "master", "--intent-ttl", "0"}, - {"gc", "--chunk-filer", "store", "--master", "master", "--timeout", "0"}, - {"gc", "--chunk-filer", "store", "--master", "master", "unexpected"}, - } { - rc, _, _ := runChunk(args...) - if rc != 2 { - t.Fatalf("invalid %v: exit=%d", args, rc) - } - } - if calls != 0 { - t.Fatalf("invalid admission dialed %d times", calls) - } -} - -func gcPartialFixture(t *testing.T) (*gcCLIStore, *time.Time) { - t.Helper() - store := &gcCLIStore{MemFiler: chunkstore.NewMemFiler()} - oldDial, oldClock := dialChunkFiler, chunkGCNow - t.Cleanup(func() { dialChunkFiler = oldDial; chunkGCNow = oldClock }) - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } - now := time.Now().Add(2 * time.Hour) - chunkGCNow = func() time.Time { return now } - ctx := context.Background() - if err := store.CreateEntry(ctx, "/gc-partial", &filerpb.Entry{Name: "v1", IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - cat, err := chunkstore.NewCatalog(store, "/gc-partial") - if err != nil { - t.Fatal(err) - } - if _, err = cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } - remote, err := chunkstore.NewChunkRemote(store, store, "/gc-partial/v1") - if err != nil { - t.Fatal(err) - } - for _, key := range []string{"orphan-a", "orphan-b"} { - if err = remote.Put(ctx, key, []byte(key)); err != nil { - t.Fatal(err) - } - } - return store, &now -} -func runPartialGC() (int, string, string) { - return runChunk("gc", "--master", "127.0.0.1:1", "--chunk-filer", "local", "--chunk-path", "/gc-partial", "--apply") -} -func TestOpsChunkGC_FinalWriteResponseLostReportsUnknown(t *testing.T) { - store, now := gcPartialFixture(t) - store.afterUpdate = func(e *filerpb.Entry) error { - if e.Name == "_GC_MARK" && strings.Contains(string(e.Content), `"ready":true`) { - return errors.New("final write response lost") - } - return nil - } - rc, out, _ := runPartialGC() - if rc != 1 { - t.Fatalf("lost response must fail: rc=%d %s", rc, out) - } - entry, err := store.LookupEntry(context.Background(), "/gc-partial", "_GC_MARK") - if err != nil || !strings.Contains(string(entry.Content), `"ready":true`) { - t.Fatalf("fixture did not commit completed mark: %v %v", entry, err) - } - var body struct { - Code string `json:"code"` - GC struct { - MarkOutcome string `json:"mark_outcome"` - Unknown []string `json:"unknown_outcomes"` - } `json:"gc"` - } - if err = json.Unmarshal([]byte(out), &body); err != nil || body.Code == "" || body.GC.MarkOutcome != "unknown" || len(body.GC.Unknown) != 1 || body.GC.Unknown[0] != "completed_mark_write" { - t.Fatalf("lost committed outcome discarded: %s %v", out, err) - } - store.afterUpdate = nil - *now = now.Add(2 * time.Hour) - rc, out, _ = runPartialGC() - var success chunkstore.GCExecution - if err = json.Unmarshal([]byte(out), &success); rc != 0 || err != nil || success.Reclaimed != 2 { - t.Fatalf("committed mark was not reusable despite error: %d %s %v", rc, out, err) - } -} -func TestOpsChunkGC_PartialReclaimReportsKnownAndUnknown(t *testing.T) { - store, now := gcPartialFixture(t) - if rc, out, _ := runPartialGC(); rc != 0 { - t.Fatalf("first mark: %d %s", rc, out) - } - *now = now.Add(2 * time.Hour) - store.failDeleteAt = 2 - rc, out, _ := runPartialGC() - if rc != 1 { - t.Fatalf("partial failure exit=%d %s", rc, out) - } - // Both requests took effect, but only the first was acknowledged. The - // second is UNKNOWN to the caller; it must not be counted as known success. - if store.deletes != 2 || len(store.blobs) != 0 { - t.Fatal("partial-effect fixture was not exercised") - } - var body struct { - Code string `json:"code"` - GC struct { - Reclaimed int - MarkOutcome string `json:"mark_outcome"` - Unknown []string `json:"unknown_outcomes"` - } `json:"gc"` - } - if err := json.Unmarshal([]byte(out), &body); err != nil || body.Code == "" || body.GC.Reclaimed != 1 || body.GC.MarkOutcome != "in_progress" || len(body.GC.Unknown) != 1 || body.GC.Unknown[0] != "reclamation" { - t.Fatalf("partial effects discarded or overclaimed: %s %v", out, err) - } -} - -type gcFailedMarkLookup struct { - *gcCLIStore - lookups int -} - -func (s *gcFailedMarkLookup) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { - if name == "_GC_MARK" { - s.lookups++ - return nil, errors.New("mark lookup unavailable") - } - return s.gcCLIStore.LookupEntry(ctx, dir, name) -} -func TestOpsChunkGC_FailedMarkLookupPreservesUnknownUnbound(t *testing.T) { - for _, apply := range []bool{false, true} { - name := "dry-run" - if apply { - name = "apply" - } - t.Run(name, func(t *testing.T) { - store := &gcFailedMarkLookup{gcCLIStore: &gcCLIStore{MemFiler: chunkstore.NewMemFiler()}} - old := dialChunkFiler - t.Cleanup(func() { dialChunkFiler = old }) - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } - args := []string{"gc", "--master", "127.0.0.1:1", "--chunk-filer", "local", "--chunk-path", "/gc-lookup"} - if apply { - args = append(args, "--apply") - } - rc, out, stderr := runChunk(args...) - var body struct { - Code string `json:"code"` - GC chunkstore.GCExecution `json:"gc"` - } - if err := json.Unmarshal([]byte(out), &body); err != nil { - t.Fatal(err) - } - if rc != 1 || body.Code == "" || !strings.Contains(stderr, "mark lookup unavailable") || !body.GC.UnknownUnbound || body.GC.MarkOutcome != "not_attempted" || body.GC.DryRun == apply || body.GC.MarkSaved || store.lookups != 1 || store.writes != 0 || store.deletes != 0 { - t.Fatalf("failed lookup misreported/mutated: rc=%d out=%s stderr=%s lookups=%d writes=%d deletes=%d", rc, out, stderr, store.lookups, store.writes, store.deletes) - } - }) - } -} - -func TestOpsChunkGC_PermanentDeleteReportsFailureWithSavedCoverage(t *testing.T) { - var stdout, stderr bytes.Buffer - out := chunkstore.GCExecution{MarkOutcome: "complete", MarkSaved: true, GCResult: chunkstore.GCResult{ - Reclaimed: 1, FailedDeletes: []chunkstore.GCDeleteFailure{{GCObject: chunkstore.GCObject{Volume: "v1", Key: "bad", FID: "3,bad"}, Error: "http 400"}}, - }} - rc := chunkGCResult(out, chunkstore.ErrBlobDeleteRejected, &stdout, &stderr) - var body struct { - GC chunkstore.GCExecution `json:"gc"` - } - if err := json.Unmarshal(stdout.Bytes(), &body); err != nil { - t.Fatal(err) - } - if rc != 1 || !body.GC.MarkSaved || body.GC.MarkOutcome != "complete" || body.GC.Reclaimed != 1 || len(body.GC.FailedDeletes) != 1 || body.GC.FailedDeletes[0].FID != "3,bad" { - t.Fatalf("partial failure lost saved coverage or object identity: rc=%d body=%s", rc, stdout.String()) - } -} diff --git a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go index 99dd726bf2..99044cebdb 100644 --- a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go +++ b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go @@ -4,10 +4,8 @@ import ( "context" "fmt" "sync" - "testing" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/storage" ) type manifestFixtureFiler struct { @@ -37,24 +35,3 @@ func (f *manifestFixtureFiler) Get(_ context.Context, id string) ([]byte, error) } return append([]byte(nil), b...), nil } - -func prepareFixtureHead(t *testing.T, f *manifestFixtureFiler, h storage.ChunkHead) storage.ChunkHead { - t.Helper() - ctx := context.Background() - r, err := chunkstore.NewChunkRemote(f, f, defaultChunkPathCLI+"/v1") - if err != nil { - t.Fatal(err) - } - h, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, h, 8*4096) - if err != nil { - t.Fatal(err) - } - // These fixtures hand the completed cut directly to the catalog; the - // snapshot/fork operations establish their own reachability intents. - for _, id := range intents { - if err := r.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - return h -} diff --git a/seaweed-block/cmd/sw-block/chunk_output_test.go b/seaweed-block/cmd/sw-block/chunk_output_test.go index 47844a5ff8..7badc1e765 100644 --- a/seaweed-block/cmd/sw-block/chunk_output_test.go +++ b/seaweed-block/cmd/sw-block/chunk_output_test.go @@ -6,7 +6,6 @@ package main import ( "bytes" - "context" "errors" "io" "net/http" @@ -14,7 +13,6 @@ import ( "strings" "testing" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" ) type failWriter struct{} @@ -60,20 +58,12 @@ func TestOpsChunk_OversizedResponseIsRefused(t *testing.T) { func TestOpsChunk_LostResultFailsTheCommand(t *testing.T) { srv, _ := chunkServer(t, 200, `{"volumeID":"v1","cutLSN":9}`) - mem := chunkstore.NewMemFiler() - prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } - t.Cleanup(func() { dialChunkFiler = prev }) - cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) - if err != nil { - t.Fatal(err) - } - if _, err := cat.EnsureVolume(context.Background(), "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "v1", "s1") commands := map[string][]string{ "cut (HTTP)": {"ops", "chunk", "cut", "--volume", "v1", "--status-addr", srv.URL}, - "snapshots (filer)": {"ops", "chunk", "snapshots", "--volume", "v1", "--chunk-filer", "filer:18888"}, + "snapshots (filer)": append([]string{"ops"}, append([]string{"chunk"}, cliArgs("snapshots", volArgs("volume", v))...)...), } for name, args := range commands { for wname, w := range map[string]io.Writer{"failing": failWriter{}, "short": shortWriter{}} { diff --git a/seaweed-block/cmd/sw-block/chunk_restore.go b/seaweed-block/cmd/sw-block/chunk_restore.go deleted file mode 100644 index bd845e68ba..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_restore.go +++ /dev/null @@ -1,92 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "fmt" - "io" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/ops" -) - -// chunkRestore restores a snapshot into a new independent volume, or drives -// an existing restore. -// -// With --source, --snapshot and --target it creates the target volume from -// the snapshot (Catalog.Restore, idempotent by --request-id) and, when -// --status-addr names the blockvolume serving the target, starts the restore -// driver there and prints its status (the create result goes to stderr). With --volume and --status-addr it -// starts (or joins) the driver of an existing restore and prints its status; -// --status only prints the status. The driver runs in blockvolume and -// outlives this call. -func chunkRestore(args []string, stdout, stderr io.Writer) int { - fs := chunkFlagSet("restore", stderr) - var ( - volumeID, statusAddr string - filer, base, source, snapshot, target, requestID string - statusOnly bool - timeout time.Duration - ) - fs.StringVar(&volumeID, "volume", "", "restored volume id (drive an existing restore)") - fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL serving the restored volume (with --chunk-control-endpoint)") - fs.BoolVar(&statusOnly, "status", false, "print the restore status without starting a run") - fs.StringVar(&source, "source", "", "source volume id (create a restore)") - fs.StringVar(&snapshot, "snapshot", "", "source snapshot name (create a restore)") - fs.StringVar(&target, "target", "", "new volume id (create a restore)") - fs.StringVar(&requestID, "request-id", "", "idempotency id for the create; generated and printed when empty (reuse it to retry)") - fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port (create a restore)") - fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") - fs.DurationVar(&timeout, "timeout", 6*time.Minute, "filer timeout for the create") - if err := fs.Parse(args); err != nil { - return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) - } - create := source != "" || snapshot != "" || target != "" - switch { - case create && volumeID != "": - return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "use --source/--snapshot/--target to create a restore, or --volume to drive one, not both", false) - case create && (source == "" || snapshot == "" || target == ""): - return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--source, --snapshot and --target are required to create a restore", false) - case create && statusOnly: - return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--status reads an existing restore: use it with --volume", false) - case !create && (volumeID == "" || statusAddr == ""): - return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required (or --source, --snapshot and --target to create a restore)", false) - } - if !create { - body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly} - return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) - } - - if requestID == "" { - requestID = newRequestID() - fmt.Fprintf(stderr, "sw-block ops chunk restore: request id %s (reuse it to retry)\n", requestID) - } - cat, closeFn, exit := chunkCatalog("restore", filer, base, true, timeout, stdout, stderr) - if exit >= 0 { - return exit - } - defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - res, err := cat.Restore(ctx, chunkstore.ForkRequest{Source: source, Snapshot: snapshot, Target: target, RequestID: requestID}) - if err != nil || statusAddr == "" { - if err == nil { - fmt.Fprintf(stderr, "sw-block ops chunk restore: %s created; attach it, then run: sw-block ops chunk restore --volume %s --status-addr \n", target, target) - } - return chunkResult("restore", res, err, stdout, stderr) - } - created, err := json.Marshal(res) - if err != nil { - return chunkFail("restore", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false) - } - // stdout stays one JSON document (the driver status); the create result - // goes to stderr. - fmt.Fprintf(stderr, "sw-block ops chunk restore: created %s\n", created) - body := map[string]any{"volumeID": target} - code := chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) - if code != ops.VolumeStatusExitOK { - fmt.Fprintf(stderr, "sw-block ops chunk restore: %s was created, but the restore did not start at %s (is the target attached there?); once it is, run: sw-block ops chunk restore --volume %s --status-addr \n", target, statusAddr, target) - } - return code -} diff --git a/seaweed-block/cmd/sw-block/chunk_restore_test.go b/seaweed-block/cmd/sw-block/chunk_restore_test.go deleted file mode 100644 index 6cbd132249..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_restore_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package main - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/json" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) { - var got []map[string]any - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/chunk/restore" || r.Method != http.MethodPost { - http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, http.StatusNotFound) - return - } - var body map[string]any - _ = json.NewDecoder(r.Body).Decode(&body) - got = append(got, body) - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"volumeID":"v2","phase":"owning","running":true,"foreign":3}`)) - })) - defer srv.Close() - for _, args := range [][]string{{"restore", "--volume", "v2", "--status-addr", srv.URL}, {"restore", "--volume", "v2", "--status-addr", srv.URL, "--status"}} { - var out, errb bytes.Buffer - if code := runOpsChunk(args, &out, &errb); code != 0 || !strings.Contains(out.String(), `"phase":"owning"`) { - t.Fatalf("%v: exit %d out %q err %q", args, code, out.String(), errb.String()) - } - } - if len(got) != 2 || got[0]["volumeID"] != "v2" || got[0]["statusOnly"] != false || got[1]["statusOnly"] != true { - t.Fatalf("requests %v: want a start, then a status-only call", got) - } - var out, errb bytes.Buffer - if code := runOpsChunk([]string{"restore", "--status-addr", srv.URL}, &out, &errb); code == 0 { - t.Fatal("restore without --volume must be refused") - } -} - -// restoreSource publishes volume src with one chunk and snapshot s1 in a -// fresh store, and routes the CLI's filer dial to it. -func restoreSource(t *testing.T, base string) (*gcCLIStore, *chunkstore.Catalog) { - t.Helper() - ctx := context.Background() - store := &gcCLIStore{MemFiler: chunkstore.NewMemFiler()} - old := dialChunkFiler - t.Cleanup(func() { dialChunkFiler = old }) - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } - cat, err := chunkstore.NewCatalog(store, base) - if err != nil { - t.Fatal(err) - } - geo := chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} - if _, err := cat.EnsureVolume(ctx, "src", geo); err != nil { - t.Fatal(err) - } - r, err := chunkstore.NewChunkRemote(store, store, base+"/src") - if err != nil { - t.Fatal(err) - } - cur, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - data := make([]byte, 8*4096) - data[0] = 0x7 - if err := r.Put(ctx, "chunks/e1/c0/k", data); err != nil { - t.Fatal(err) - } - h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k", SHA256: sha256.Sum256(data)}}} - h, ids, err := r.PrepareManifest(ctx, cur, h, 8*4096) - if err != nil { - t.Fatal(err) - } - if h.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { - t.Fatal(err) - } - for _, id := range ids { - _ = r.DeleteIntent(ctx, id) - } - if _, err := cat.CreateSnapshot(ctx, "src", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - return store, cat -} - -// --source/--snapshot/--target creates the restore volume (idempotent by -// request id); without --status-addr it says how to start the driver. -func TestOpsChunk_RestoreCreatesTheTarget(t *testing.T) { - _, cat := restoreSource(t, "/rs") - args := []string{"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs"} - code, out, errs := runChunk(args...) - if code != 0 || !strings.Contains(out, `"dst"`) || !strings.Contains(errs, "--volume dst") { - t.Fatalf("create: exit %d out %s err %s", code, out, errs) - } - v, ok, err := cat.ReadVolume(context.Background(), "dst") - if err != nil || !ok || v.Origin != chunkstore.OriginRestore { - t.Fatalf("target: %+v ok=%v %v, want a restore volume", v, ok, err) - } - if code, out, errs := runChunk(args...); code != 0 { - t.Fatalf("retry with the same request id: exit %d out %s err %s", code, out, errs) - } - for _, bad := range [][]string{ - {"restore", "--source", "src", "--target", "dst", "--chunk-filer", "x"}, - {"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--volume", "dst", "--chunk-filer", "x"}, - {"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--status", "--chunk-filer", "x"}, - } { - if code, _, _ := runChunk(bad...); code == 0 { - t.Fatalf("%v accepted", bad) - } - } -} - -// With --status-addr the create then starts the driver for the target on -// that blockvolume, in one command. -func TestOpsChunk_RestoreCreatesAndStartsTheDriver(t *testing.T) { - _, cat := restoreSource(t, "/rs2") - var got map[string]any - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _ = json.NewDecoder(r.Body).Decode(&got) - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"volumeID":"dst","phase":"hydrating","running":true}`)) - })) - defer srv.Close() - code, out, errs := runChunk("restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs2", "--status-addr", srv.URL) - if code != 0 || !strings.Contains(out, `"phase":"hydrating"`) || !strings.Contains(errs, "created ") { - t.Fatalf("create and start: exit %d out %s err %s", code, out, errs) - } - var one map[string]any - if err := json.Unmarshal([]byte(out), &one); err != nil { - t.Fatalf("stdout is not one JSON document: %v (%s)", err, out) - } - if got["volumeID"] != "dst" || got["statusOnly"] != nil { - t.Fatalf("driver request %v, want a start for dst", got) - } - if _, ok, _ := cat.ReadVolume(context.Background(), "dst"); !ok { - t.Fatal("the target was not created before the driver start") - } -} - -// A start that fails after the create (the target not attached there yet) -// says the target exists and how to start the restore later. -func TestOpsChunk_RestoreCreateThenStartRefusedSaysHowToResume(t *testing.T) { - _, cat := restoreSource(t, "/rs3") - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusConflict) - _, _ = w.Write([]byte(`{"code":"not_chunk_volume","message":"volume dst not open","retryable":false}`)) - })) - defer srv.Close() - code, _, errs := runChunk("restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs3", "--status-addr", srv.URL) - if code == 0 || !strings.Contains(errs, "dst was created") || !strings.Contains(errs, "--volume dst") { - t.Fatalf("refused start: exit %d err %s", code, errs) - } - if _, ok, _ := cat.ReadVolume(context.Background(), "dst"); !ok { - t.Fatal("the target must exist after the create") - } -} diff --git a/seaweed-block/cmd/sw-block/chunk_retain.go b/seaweed-block/cmd/sw-block/chunk_retain.go deleted file mode 100644 index dee26ad7a7..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_retain.go +++ /dev/null @@ -1,127 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/ops" -) - -// chunkUsage: sw-block ops chunk usage --volume v --chunk-filer host:port -// prints the volume's space accounting and retention policy (from -// manifests and filer listings; no chunk data reads). -func chunkUsage(args []string, stdout, stderr io.Writer) int { - fs := chunkFlagSet("usage", stderr) - var ( - volumeID, filer, base string - timeout time.Duration - ) - fs.StringVar(&volumeID, "volume", "", "volume id") - fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") - fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") - fs.DurationVar(&timeout, "timeout", 60*time.Second, "filer timeout") - if err := fs.Parse(args); err != nil { - return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) - } - if volumeID == "" { - return chunkFail("usage", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) - } - cat, closeFn, exit := chunkCatalog("usage", filer, base, false, timeout, stdout, stderr) - if exit >= 0 { - return exit - } - defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - u, err := cat.Usage(ctx, volumeID) - return chunkResult("usage", u, err, stdout, stderr) -} - -// chunkRetain: sw-block ops chunk retain --volume v --chunk-filer host:port -// [--dry-run] applies the volume's retention policy (deletes the expired -// snapshots; GC reclaims their chunks). With --set-policy it stores the -// policy given by the --keep-* flags on the VOLUME entry instead. -func chunkRetain(args []string, stdout, stderr io.Writer) int { - fs := chunkFlagSet("retain", stderr) - var ( - volumeID, filer, base string - timeout, keepYounger time.Duration - dryRun, setPolicy bool - keepNewest, keepHourly, keepDaily, keepWeekly int - ) - fs.StringVar(&volumeID, "volume", "", "volume id") - fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") - fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") - fs.DurationVar(&timeout, "timeout", 5*time.Minute, "bound for this pass") - fs.BoolVar(&dryRun, "dry-run", false, "list what would be deleted; write nothing") - fs.BoolVar(&setPolicy, "set-policy", false, "store the --keep-* policy on the volume instead of applying it") - fs.IntVar(&keepNewest, "keep-newest", chunkstore.DefaultKeepNewest, "with --set-policy: keep the newest N unpinned snapshots") - fs.DurationVar(&keepYounger, "keep-younger", chunkstore.DefaultKeepYounger, "with --set-policy: keep every snapshot younger than this") - fs.IntVar(&keepHourly, "keep-hourly", 0, "with --set-policy: keep the newest snapshot of each of the last N hours") - fs.IntVar(&keepDaily, "keep-daily", 0, "with --set-policy: keep the newest snapshot of each of the last N days") - fs.IntVar(&keepWeekly, "keep-weekly", 0, "with --set-policy: keep the newest snapshot of each of the last N weeks") - if err := fs.Parse(args); err != nil { - return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) - } - if volumeID == "" || timeout <= 0 { - return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required and --timeout must be positive", false) - } - if setPolicy && dryRun { - return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--set-policy and --dry-run do not combine", false) - } - cat, closeFn, exit := chunkCatalog("retain", filer, base, !dryRun, timeout, stdout, stderr) - if exit >= 0 { - return exit - } - defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - if setPolicy { - p := chunkstore.RetentionPolicy{KeepNewest: keepNewest, KeepYoungerNs: int64(keepYounger), KeepHourly: keepHourly, KeepDaily: keepDaily, KeepWeekly: keepWeekly} - if err := cat.SetRetentionPolicy(ctx, volumeID, p); err != nil { - return chunkResult("retain", nil, err, stdout, stderr) - } - return chunkResult("retain", map[string]any{"volumeID": volumeID, "policy": p, "policySet": true}, nil, stdout, stderr) - } - res, err := cat.Retain(ctx, volumeID, dryRun) - if err != nil && res.VolumeID != "" { - // The pass stopped part way: report what it did (confirmed - // deletions, the failing snapshot with whether its outcome is - // uncertain, what it never reached) with the error, and fail. - return retainPartial(res, err, stdout, stderr) - } - return chunkResult("retain", res, err, stdout, stderr) -} - -// retainOutput is a retention result together with the error that -// stopped it. -type retainOutput struct { - chunkstore.RetentionResult - Error *chunkErrBody `json:"error,omitempty"` -} - -func retainPartial(res chunkstore.RetentionResult, err error, stdout, stderr io.Writer) int { - body := chunkErrBody{Code: chunkstore.CodeOf(err), Message: err.Error(), Retryable: true} - var ce *chunkstore.CatalogError - if errors.As(err, &ce) { - body = chunkErrBody{Code: ce.Code, Message: ce.Detail(), Retryable: ce.Retryable} - } - if body.Code == "" { - body.Code = codeInternalCLI - } - fmt.Fprintf(stderr, "sw-block ops chunk retain: %s: %s (deleted %d, not attempted %d)\n", body.Code, body.Message, len(res.Deleted), len(res.NotAttempted)) - out, mErr := json.Marshal(retainOutput{RetentionResult: res, Error: &body}) - if mErr != nil { - fmt.Fprintf(stderr, "sw-block ops chunk retain: %v\n", mErr) - return chunkExitFailed - } - if wErr := writeAll(stdout, append(out, '\n')); wErr != nil { - fmt.Fprintf(stderr, "sw-block ops chunk retain: write the result: %v\n", wErr) - } - return chunkExitFailed -} diff --git a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go deleted file mode 100644 index b40b03134e..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// failingFiler fails the UpdateEntry calls fail picks, after or before -// applying them. -type failingFiler struct { - *chunkstore.MemFiler - fail func(dir, name string) bool - afterApply bool -} - -func (f *failingFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { - if f.fail != nil && f.fail(dir, e.GetName()) { - if f.afterApply { - if err := f.MemFiler.UpdateEntry(ctx, dir, e, expected); err != nil { - return err - } - return errors.New("response lost") - } - return errors.New("filer unavailable") - } - return f.MemFiler.UpdateEntry(ctx, dir, e, expected) -} - -// retain that fails part way prints what it confirmed, the failing -// snapshot (uncertain) and what it never reached, with the error, and -// exits nonzero; a lost response is finished by the next run. -func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) { - ctx := context.Background() - ff := &failingFiler{MemFiler: chunkstore.NewMemFiler()} - fm := newManifestFixtureFiler(ff) - prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return fm, func() error { return nil }, nil } - t.Cleanup(func() { dialChunkFiler = prev }) - cat, err := chunkstore.NewCatalog(fm, defaultChunkPathCLI) - if err != nil { - t.Fatal(err) - } - if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } - base := time.Now().Add(-48 * time.Hour) - head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, - Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} - head = prepareFixtureHead(t, fm, head) - for i := 0; i < 4; i++ { - at := base.Add(time.Duration(i) * time.Minute) - cat.SetClock(func() time.Time { return at }) - if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i)}, head); err != nil { - t.Fatal(err) - } - } - filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"} - if code, out, errs := runChunk(append([]string{"retain", "--set-policy", "--keep-newest", "0", "--keep-younger", "0s"}, filer...)...); code != 0 { - t.Fatalf("set policy: %d %q %q", code, out, errs) - } - // Expired newest first: s3, s2, s1, s0. The mark of s2 fails. - ff.fail = func(dir, _ string) bool { return strings.HasSuffix(dir, "/snaps/s2") } - type partial struct { - chunkstore.RetentionResult - Error *chunkErrBody `json:"error"` - } - code, out, errs := runChunk(append([]string{"retain"}, filer...)...) - var p partial - if code == 0 || json.Unmarshal([]byte(out), &p) != nil || p.Error == nil || p.Failed == nil { - t.Fatalf("failing retain: exit %d %q %q; want nonzero with the partial result", code, out, errs) - } - if strings.Join(p.Deleted, ",") != "s3" || p.Failed.Name != "s2" || !p.Failed.Uncertain || strings.Join(p.NotAttempted, ",") != "s1,s0" { - t.Fatalf("partial result: %+v", p) - } - if !strings.Contains(errs, "deleted 1, not attempted 2") { - t.Fatalf("stderr %q; want the counts", errs) - } - - ff.afterApply = true // the mark lands, its response is lost - code, out, _ = runChunk(append([]string{"retain"}, filer...)...) - if code == 0 || json.Unmarshal([]byte(out), &p) != nil || p.Failed == nil || p.Failed.Name != "s2" || !p.Failed.Uncertain { - t.Fatalf("lost response: exit %d %q", code, out) - } - ff.fail = nil - code, out, errs = runChunk(append([]string{"retain"}, filer...)...) - var done chunkstore.RetentionResult - if code != 0 || json.Unmarshal([]byte(out), &done) != nil || strings.Join(done.Deleted, ",") != "s1,s0,s2" { - t.Fatalf("rerun: %d %q %q; want s1, s0 and the half-deleted s2", code, out, errs) - } -} diff --git a/seaweed-block/cmd/sw-block/chunk_retain_test.go b/seaweed-block/cmd/sw-block/chunk_retain_test.go deleted file mode 100644 index 0dd4633cfd..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_retain_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "fmt" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// snapshot --pin / --class / --expires send the retention class and the -// expiry; conflicting flags are refused before any request. -func TestOpsChunk_SnapshotPinAndExpires(t *testing.T) { - srv, got := chunkServer(t, 200, `{"volumeID":"v1","name":"s1"}`) - before := time.Now() - if code, _, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "r", "--pin", "--expires", "1h"); code != 0 { - t.Fatalf("snapshot --pin --expires: %d %q", code, errs) - } - body := (*got)[0].body - exp, _ := body["expiresAtNs"].(float64) - if body["class"] != chunkstore.SnapshotClassPinned || exp < float64(before.Add(time.Hour).UnixNano())-1e9 { - t.Fatalf("pinned request: %+v", body) - } - for _, args := range [][]string{ - {"--pin", "--class", "semantic"}, - {"--expires", "1h", "--expires-at-ns", "5"}, - {"--expires", "-1s"}, - } { - a := append([]string{"snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s2"}, args...) - if code, out, _ := runChunk(a...); code == 0 || !strings.Contains(out, codeBadRequestCLI) { - t.Fatalf("snapshot %v: exit %d %q; want a bad request", args, code, out) - } - } - if len(*got) != 1 { - t.Fatalf("refused flags still sent requests: %d", len(*got)) - } -} - -// usage and retain run catalog-direct against the filer: set a policy, -// dry-run, apply, and see the accounting follow. -func TestOpsChunk_UsageAndRetain(t *testing.T) { - ctx := context.Background() - mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) - prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } - t.Cleanup(func() { dialChunkFiler = prev }) - cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) - if err != nil { - t.Fatal(err) - } - if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } - old := time.Now().Add(-48 * time.Hour) - cat.SetClock(func() time.Time { return old }) - head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, - Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} - head = prepareFixtureHead(t, mem, head) - for i := 0; i < 5; i++ { - if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i), Class: chunkstore.SnapshotClassSemantic}, head); err != nil { - t.Fatal(err) - } - } - - filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"} - if code, out, errs := runChunk(append([]string{"retain", "--set-policy", "--keep-newest", "2", "--keep-younger", "1m"}, filer...)...); code != 0 || !strings.Contains(out, `"policySet":true`) { - t.Fatalf("set policy: %d %q %q", code, out, errs) - } - code, out, errs := runChunk(append([]string{"retain", "--dry-run"}, filer...)...) - var dry chunkstore.RetentionResult - if code != 0 || json.Unmarshal([]byte(out), &dry) != nil || !dry.DryRun || dry.Expired != 3 || len(dry.Deleted) != 0 { - t.Fatalf("dry run: %d %q %q", code, out, errs) - } - code, out, errs = runChunk(append([]string{"retain"}, filer...)...) - var applied chunkstore.RetentionResult - if code != 0 || json.Unmarshal([]byte(out), &applied) != nil || len(applied.Deleted) != 3 || applied.Kept != 2 { - t.Fatalf("retain: %d %q %q", code, out, errs) - } - code, out, errs = runChunk(append([]string{"usage"}, filer...)...) - var u chunkstore.VolumeUsage - if code != 0 || json.Unmarshal([]byte(out), &u) != nil || len(u.Snapshots) != 2 || u.Policy.KeepNewest != 2 || !u.PolicySet { - t.Fatalf("usage: %d %q %q", code, out, errs) - } - if code, out, _ := runChunk("retain", "--volume", "v1", "--chunk-filer", "f:1", "--set-policy", "--dry-run"); code == 0 || !strings.Contains(out, codeBadRequestCLI) { - t.Fatalf("--set-policy --dry-run: %d %q; want a bad request", code, out) - } -} diff --git a/seaweed-block/cmd/sw-block/chunk_show_test.go b/seaweed-block/cmd/sw-block/chunk_show_test.go deleted file mode 100644 index 6a36ac02a5..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_show_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// ops chunk show prints a volume's VOLUME entry and HEAD from the filer; -// either is null when it does not exist (B9 W2 appendix). -func TestOpsChunk_Show(t *testing.T) { - ctx := context.Background() - mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) - prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } - t.Cleanup(func() { dialChunkFiler = prev }) - cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) - if err != nil { - t.Fatal(err) - } - geo := chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} - if _, err := cat.EnsureVolume(ctx, "v1", geo); err != nil { - t.Fatal(err) - } - head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive, - Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} - head = prepareFixtureHead(t, mem, head) - if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil { - t.Fatal(err) - } - if _, err := cat.Fork(ctx, chunkstore.ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil { - t.Fatal(err) - } - show := func(vol string) chunkstore.VolumeShowBody { - t.Helper() - code, out, errs := runChunk("show", "--volume", vol, "--chunk-filer", "f:1") - var b chunkstore.VolumeShowBody - if code != 0 || json.Unmarshal([]byte(out), &b) != nil { - t.Fatalf("show %s: %d %q %q", vol, code, out, errs) - } - return b - } - fork := show("v2") - if fork.Volume == nil || fork.Volume.Origin != chunkstore.OriginFork || fork.Volume.NumBlocks != 64 || fork.Volume.Parent == nil || - fork.Volume.Parent.VolumeID != "v1" || fork.Volume.Parent.Snapshot != "s1" { - t.Fatalf("show v2 VOLUME: %+v", fork.Volume) - } - if fork.Head == nil || fork.Head.Gen != 1 || fork.Head.Epoch != 0 || fork.Head.RemoteLSN != 42 || fork.Head.State != "active" || - fork.Head.ChunkCount != 1 || fork.Head.DetachedBy != nil { - t.Fatalf("show v2 HEAD: %+v", fork.Head) - } - // A created volume carries its initial HEAD (gen 1, epoch 0, no chunks). - if src := show("v1"); src.Volume == nil || src.Volume.Origin != chunkstore.OriginCreate || src.Head == nil || src.Head.Gen != 1 || - src.Head.Epoch != 0 || src.Head.RemoteLSN != 0 || src.Head.ChunkCount != 0 || src.Head.State != "active" { - t.Fatalf("show v1 (VOLUME and its initial HEAD): %+v %+v", src.Volume, src.Head) - } - if none := show("v9"); none.Volume != nil || none.Head != nil || none.VolumeID != "v9" { - t.Fatalf("show of a volume that does not exist: %+v", none) - } - if code, out, _ := runChunk("show", "--chunk-filer", "f:1"); code != 2 || chunkErrorOut(t, out).Code != "bad_request" { - t.Fatalf("show without --volume: exit %d %q", code, out) - } -} diff --git a/seaweed-block/cmd/sw-block/chunk_start_check_test.go b/seaweed-block/cmd/sw-block/chunk_start_check_test.go index 05ff3c2399..4d3dd47c4e 100644 --- a/seaweed-block/cmd/sw-block/chunk_start_check_test.go +++ b/seaweed-block/cmd/sw-block/chunk_start_check_test.go @@ -8,6 +8,10 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // Every ops chunk command that writes chunk metadata runs the @@ -15,10 +19,16 @@ import ( // when the filer is not the only one of its group; read-only commands (and // read-only modes) do not run it. func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) { - mem := chunkstore.NewMemFiler() + mem := newMemChunkStore() prevDial, prevCheck := dialChunkFiler, checkSingleFiler t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + prevResolve := resolveVolumeID + t.Cleanup(func() { resolveVolumeID = prevResolve }) + resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{1}, nil } + id := []string{"--master", "m:1"} + src := []string{"--source", "v1", "--master", "m:1"} + tgt := []string{"--target", "v2"} checks := 0 checkSingleFiler = func(context.Context, chunkstore.Filer) error { checks++ @@ -26,11 +36,10 @@ func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) { } filer := []string{"--chunk-filer", "filer:18888"} writing := map[string][]string{ - "snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, filer...), - "fork": append([]string{"ops", "chunk", "fork", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "r"}, filer...), - "retain": append([]string{"ops", "chunk", "retain", "--volume", "v1"}, filer...), - "volume-delete": append([]string{"ops", "chunk", "volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "r"}, filer...), - "gc --apply": append([]string{"ops", "chunk", "gc", "--master", "m:1", "--apply"}, filer...), + "snapshot-delete": append(append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, id...), filer...), + "release": append(append(append([]string{"ops", "chunk", "release"}, src...), tgt...), filer...), + "retain": append(append([]string{"ops", "chunk", "retain", "--volume", "v1"}, id...), filer...), + "volume-delete": append(append([]string{"ops", "chunk", "volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "r"}, id...), filer...), } for name, args := range writing { before := checks @@ -44,11 +53,10 @@ func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) { } } readOnly := map[string][]string{ - "snapshots": append([]string{"ops", "chunk", "snapshots", "--volume", "v1"}, filer...), - "show": append([]string{"ops", "chunk", "show", "--volume", "v1"}, filer...), - "usage": append([]string{"ops", "chunk", "usage", "--volume", "v1"}, filer...), - "retain --dry-run": append([]string{"ops", "chunk", "retain", "--volume", "v1", "--dry-run"}, filer...), - "gc (read-only)": append([]string{"ops", "chunk", "gc", "--master", "m:1"}, filer...), + "snapshots": append(append([]string{"ops", "chunk", "snapshots", "--volume", "v1"}, id...), filer...), + "show": append(append([]string{"ops", "chunk", "show", "--volume", "v1"}, id...), filer...), + "usage": append(append([]string{"ops", "chunk", "usage", "--volume", "v1"}, id...), filer...), + "retain --dry-run": append(append([]string{"ops", "chunk", "retain", "--volume", "v1", "--dry-run"}, id...), filer...), } for name, args := range readOnly { before := checks @@ -60,13 +68,57 @@ func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) { } } +// Restore has one master authority call. The master owns the filer check +// and target creation; the CLI must never write the filer independently. +func TestOpsChunkRestoreUsesOnlyMasterCreate(t *testing.T) { + prevDial, prevRestore := dialChunkFiler, restoreCreateRPC + t.Cleanup(func() { dialChunkFiler, restoreCreateRPC = prevDial, prevRestore }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + t.Fatal("restore CLI contacted the filer") + return nil, nil, nil + } + calls := 0 + var firstID string + restoreCreateRPC = func(_ context.Context, master string, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + calls++ + if master != "m:1" || req.GetVolumeId() != "v2" || req.GetSourceVolume() != "v1" || req.GetSourceSnapshot() != "s1" || req.GetCreateRequestId() == "" { + t.Fatalf("restore RPC: master=%q req=%+v", master, req) + } + if firstID == "" { + firstID = req.GetCreateRequestId() + } + if req.GetCreateRequestId() != firstID { + t.Fatal("retry changed request id") + } + return &control.CreateVolumeResponse{VolumeId: "v2", LayoutId: (layout.VolumeID{1}).String(), StoreReady: true}, nil + } + args := []string{"ops", "chunk", "restore", "--master", "m:1", "--source", "v1", "--target", "v2", "--snapshot", "s1"} + for i := 0; i < 2; i++ { + var out, errs bytes.Buffer + if code := run(args, &out, &errs); code != 0 { + t.Fatalf("restore replay: code=%d out=%q err=%q", code, out.String(), errs.String()) + } + } + if calls != 2 { + t.Fatalf("restore made %d RPCs; want one per invocation", calls) + } + restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + return nil, status.Error(codes.Unavailable, "filer unreachable") + } + var out, errs bytes.Buffer + if code := run(args, &out, &errs); code != chunkExitFailed || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) { + t.Fatalf("uncertain restore must be retryable: code=%d out=%q err=%q", code, out.String(), errs.String()) + } +} + // The start check runs within the command's own --timeout: a check stalled // on its filer or master (here one that blocks until its context ends) ends // the command at the timeout, as a retryable refusal. func TestOpsChunk_StartCheckIsBoundedByTheTimeout(t *testing.T) { mem := chunkstore.NewMemFiler() - prevDial, prevCheck := dialChunkFiler, checkSingleFiler - t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + prevDial, prevCheck, prevResolve := dialChunkFiler, checkSingleFiler, resolveVolumeID + t.Cleanup(func() { dialChunkFiler, checkSingleFiler, resolveVolumeID = prevDial, prevCheck, prevResolve }) + resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{1}, nil } dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error { <-ctx.Done() @@ -74,8 +126,7 @@ func TestOpsChunk_StartCheckIsBoundedByTheTimeout(t *testing.T) { } filer := []string{"--chunk-filer", "filer:18888", "--timeout", "200ms"} for name, args := range map[string][]string{ - "snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, filer...), - "gc --apply": append([]string{"ops", "chunk", "gc", "--master", "m:1", "--apply"}, filer...), + "snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--master", "m:1", "--name", "s1"}, filer...), } { done := make(chan struct{}) var out, errb bytes.Buffer diff --git a/seaweed-block/cmd/sw-block/chunk_test.go b/seaweed-block/cmd/sw-block/chunk_test.go index 39347d09fa..b2e9054945 100644 --- a/seaweed-block/cmd/sw-block/chunk_test.go +++ b/seaweed-block/cmd/sw-block/chunk_test.go @@ -2,7 +2,6 @@ package main import ( "bytes" - "context" "encoding/json" "io" "net/http" @@ -12,7 +11,7 @@ import ( "testing" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) type chunkRoute struct { @@ -130,71 +129,13 @@ func TestOpsChunk_ErrorsAreJSONOnStdout(t *testing.T) { t.Fatalf("unreachable blockvolume: %+v, want remote_unavailable and retryable", e) } - mem := chunkstore.NewMemFiler() - prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } - t.Cleanup(func() { dialChunkFiler = prev }) - if code, out, _ := runChunk("fork", "--chunk-filer", "f:1", "--source", "v1", "--snapshot", "s9", "--target", "v2", "--request-id", "r"); code != chunkExitFailed { - t.Fatalf("fork of a missing snapshot: exit %d %q", code, out) + store := newMemChunkStore() + useMemChunkStore(t, store) + src := cliVolume(t, store, "v1", "s1") + tid, _ := layout.NewVolumeID() + if code, out, _ := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", chunkstore.VolumeRef{Name: "v2", ID: tid}), []string{"--snapshot", "s9"})...); code != chunkExitFailed { + t.Fatalf("restore of a missing snapshot: exit %d %q", code, out) } else if e := chunkErrorOut(t, out); e.Code != "snapshot_not_found" || e.Retryable { - t.Fatalf("fork of a missing snapshot: %+v", e) - } -} - -// snapshots, snapshot-delete and fork go to the filer directly. -func TestOpsChunk_FilerCommands(t *testing.T) { - ctx := context.Background() - mem := chunkstore.NewMemFiler() - prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } - t.Cleanup(func() { dialChunkFiler = prev }) - cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) - if err != nil { - t.Fatal(err) - } - if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } - head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 42, State: storage.ChunkHeadActive, - Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} - manifestMem := newManifestFixtureFiler(mem) - cat, err = chunkstore.NewCatalog(manifestMem, defaultChunkPathCLI) - if err != nil { - t.Fatal(err) - } - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { - return manifestMem, func() error { return nil }, nil - } - head = prepareFixtureHead(t, manifestMem, head) - if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil { - t.Fatal(err) - } - - code, out, errs := runChunk("snapshots", "--volume", "v1", "--chunk-filer", "filer:18888") - var list chunkstore.SnapshotListBody - if code != 0 || json.Unmarshal([]byte(out), &list) != nil || len(list.Snapshots) != 1 || list.Snapshots[0].Name != "s1" || list.Snapshots[0].CutLSN != 42 { - t.Fatalf("snapshots: %d %q %q", code, out, errs) - } - code, out, errs = runChunk("fork", "--chunk-filer", "filer:18888", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "f1") - var fork chunkstore.ForkResult - if code != 0 || json.Unmarshal([]byte(out), &fork) != nil || fork.Target != "v2" || fork.HeadGen != 1 || fork.RemoteLSN != 42 || fork.Replayed || - !strings.Contains(out, `"remoteLSN":42`) { - t.Fatalf("fork: %d %q %q", code, out, errs) - } - if code, out, _ := runChunk("fork", "--chunk-filer", "filer:18888", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "f1"); code != 0 || !strings.Contains(out, `"replayed":true`) { - t.Fatalf("fork retry: %d %q", code, out) - } - if code, _, errs := runChunk("fork", "--chunk-filer", "filer:18888", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "other"); code != chunkExitFailed || !strings.Contains(errs, "target_exists") { - t.Fatalf("fork with another request id: %d %q", code, errs) - } - // The first delete frees the name; a repeated one finds it absent. - for i, want := range []string{`"state":"deleting"`, `"state":"absent"`} { - code, out, errs = runChunk("snapshot-delete", "--volume", "v1", "--name", "s1", "--chunk-filer", "filer:18888") - if code != 0 || !strings.Contains(out, want) { - t.Fatalf("snapshot-delete #%d: %d %q %q, want %s", i+1, code, out, errs, want) - } - } - if code, _, _ := runChunk("snapshots", "--volume", "v1"); code != 2 { - t.Fatalf("snapshots without --chunk-filer: exit %d, want 2", code) + t.Fatalf("restore of a missing snapshot: %+v", e) } } diff --git a/seaweed-block/cmd/sw-block/chunk_verify.go b/seaweed-block/cmd/sw-block/chunk_verify.go index 1d70e92f0d..b08d38f00b 100644 --- a/seaweed-block/cmd/sw-block/chunk_verify.go +++ b/seaweed-block/cmd/sw-block/chunk_verify.go @@ -11,19 +11,22 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/ops" ) // chunkVerify: sw-block ops chunk verify --volume v --chunk-filer host:port -// checks the volume's remote image against its HEAD (and, on request, its -// snapshots), read-only (chunkstore.Catalog.Verify). Exit 0: clean; 3: the -// pass completed with findings; 1: it could not complete (the partial result -// is printed with the error); 2: usage. +// checks the volume's store read-only: VOLUME, HEAD, every root HEAD names +// (the current image and every snapshot), their segments and chunks +// (chunkstore.VerifyLayout). --orphans also reports the volume's own names +// that no reachable root names (it never deletes them). Exit 0: clean; 3: +// the pass completed with findings; 1: it could not complete (the partial +// result is printed with the reason); 2: usage. func chunkVerify(args []string, stdout, stderr io.Writer) int { fs := chunkFlagSet("verify", stderr) var ( volumeID, filer, base, snapshot, depth string - allSnapshots bool + allSnapshots, orphans bool concurrency int bytesPerSec int64 timeout time.Duration @@ -31,11 +34,12 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { fs.StringVar(&volumeID, "volume", "", "volume id") fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") - fs.StringVar(&snapshot, "snapshot", "", "also check this snapshot") - fs.BoolVar(&allSnapshots, "all-snapshots", false, "also check every snapshot") - fs.StringVar(&depth, "depth", string(chunkstore.VerifyBindings), "meta, bindings or data (data reads every chunk once)") - fs.IntVar(&concurrency, "concurrency", chunkstore.DefaultVerifyConcurrency, "chunk reads in flight (depth data)") - fs.Int64Var(&bytesPerSec, "bytes-per-sec", chunkstore.DefaultVerifyBytesPerSecond, "pace chunk reads (depth data); 0 leaves them unpaced") + fs.StringVar(&snapshot, "snapshot", "", "accepted for compatibility: every snapshot HEAD names is always checked") + fs.BoolVar(&allSnapshots, "all-snapshots", false, "accepted for compatibility: every snapshot HEAD names is always checked") + fs.StringVar(&depth, "depth", "bindings", "meta or bindings: every named object exists; data: and every chunk's bytes hash to its name") + fs.BoolVar(&orphans, "orphans", false, "also report the volume's own names no reachable root names (report only)") + fs.IntVar(&concurrency, "concurrency", 1, "accepted for compatibility: chunks are read one at a time") + fs.Int64Var(&bytesPerSec, "bytes-per-sec", 0, "accepted for compatibility: chunk reads are not paced") fs.DurationVar(&timeout, "timeout", 10*time.Minute, "bound for the whole pass; required with --depth data") if err := fs.Parse(args); err != nil { return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) @@ -49,37 +53,37 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { usage := func(msg string) int { return chunkFail("verify", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, msg, false) } - d := chunkstore.VerifyDepth(depth) + d := map[string]string{"meta": layout.DepthNames, "bindings": layout.DepthNames, "data": layout.DepthFull}[depth] switch { case fs.NArg() != 0: return usage("unexpected arguments") case volumeID == "": return usage("--volume is required") - case d != chunkstore.VerifyMeta && d != chunkstore.VerifyBindings && d != chunkstore.VerifyData: + case filer == "": + return usage("--chunk-filer is required") + case d == "": return usage(fmt.Sprintf("--depth %q: meta, bindings or data", depth)) case snapshot != "" && allSnapshots: return usage("--snapshot and --all-snapshots do not combine") - case d == chunkstore.VerifyData && !timeoutSet: + case d == layout.DepthFull && !timeoutSet: return usage("--depth data reads every chunk: give an explicit --timeout for the pass") case timeout <= 0 || concurrency <= 0 || bytesPerSec < 0: return usage("--timeout and --concurrency must be positive and --bytes-per-sec not negative") } - // One bound for the whole pass, the single-filer start check included: - // the deadline starts before the check. Verify writes nothing, but it - // runs the check (writes=true): against a split filer view it would - // report false findings. + // One bound for the whole pass, the single-filer start check included. + // Verify writes nothing, but against a split filer view it would report + // false findings, so it runs the check. ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() - cat, closeFn, exit := chunkCatalog("verify", filer, base, true, timeout, stdout, stderr) - if exit >= 0 { - return exit + f, closeFn, err := dialChunkFiler(filer) + if err != nil { + return usage(err.Error()) } defer closeFn() - if bytesPerSec == 0 { - bytesPerSec = -1 // the library's "unpaced" + if exit := refuseUnlessSingleFiler("verify", f, timeout, stdout, stderr); exit >= 0 { + return exit } - res, err := cat.Verify(ctx, volumeID, chunkstore.VerifyOptions{Depth: d, Snapshot: snapshot, AllSnapshots: allSnapshots, - Concurrency: concurrency, BytesPerSecond: bytesPerSec}) + res, err := chunkstore.VerifyLayout(ctx, f, base, volumeID, layout.VerifyOptions{Depth: d, Orphans: orphans}) if err != nil { return verifyIncomplete(res, err, stdout, stderr) } @@ -92,12 +96,12 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { fmt.Fprintf(stderr, "sw-block ops chunk verify: write the result: %v\n", err) return chunkExitFailed } + if !res.Complete { + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: incomplete: %s\n", volumeID, res.Incomplete) + return chunkExitFailed + } if len(res.Findings) != 0 { - fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d findings %v\n", volumeID, len(res.Findings), res.FindingsByClass) - if res.ChunksNotRead != 0 { - // READ_ERROR is not damage: those objects were not verified. - fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d could not be read and were not verified; re-run\n", volumeID, res.ChunksNotRead) - } + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d findings\n", volumeID, len(res.Findings)) return chunkExitFindings } return ops.VolumeStatusExitOK @@ -105,20 +109,20 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { // verifyJSON is the result as one JSON object whose findings array holds // one finding per line. -func verifyJSON(res chunkstore.VerifyResult) ([]byte, error) { +func verifyJSON(res layout.VerifyResult) ([]byte, error) { findings := res.Findings res.Findings = nil head, err := json.Marshal(res) if err != nil { return nil, err } - const tail = `"findings":null}` + const tail = `"Findings":null}` if !bytes.HasSuffix(head, []byte(tail)) { return nil, errors.New("verify result: unexpected field order") } var buf bytes.Buffer buf.Write(head[:len(head)-len(tail)]) - buf.WriteString(`"findings":[`) + buf.WriteString(`"Findings":[`) for i, f := range findings { line, err := json.Marshal(f) if err != nil { @@ -139,17 +143,13 @@ func verifyJSON(res chunkstore.VerifyResult) ([]byte, error) { // verifyIncomplete prints the error body with the partial result under // "verify", and fails. -func verifyIncomplete(res chunkstore.VerifyResult, err error, stdout, stderr io.Writer) int { +func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writer) int { body := struct { chunkErrBody - Verify chunkstore.VerifyResult `json:"verify"` + Verify layout.VerifyResult `json:"verify"` }{Verify: res} body.Code, body.Message = codeInternalCLI, err.Error() - var ce *chunkstore.CatalogError - switch { - case errors.As(err, &ce): - body.Code, body.Message, body.Retryable = ce.Code, ce.Detail(), ce.Retryable - case errors.Is(err, context.DeadlineExceeded): + if errors.Is(err, context.DeadlineExceeded) { body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true } fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message) diff --git a/seaweed-block/cmd/sw-block/chunk_verify_test.go b/seaweed-block/cmd/sw-block/chunk_verify_test.go index bdf82a3447..58bd95bd46 100644 --- a/seaweed-block/cmd/sw-block/chunk_verify_test.go +++ b/seaweed-block/cmd/sw-block/chunk_verify_test.go @@ -3,22 +3,22 @@ package main import ( "bytes" "context" - "crypto/sha256" "encoding/json" "fmt" - "net/url" "path" "strings" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) -// verifyCLIFixture is volume v1 with two published chunks on an in-memory -// filer and blob store; it returns the store and the HEAD. -func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, storage.ChunkHead) { +// verifyCLIFixture is volume v1 on the content-named layout (VOLUME, HEAD, +// one root naming chunks 0 and 1) on an in-memory filer and blob store; it +// returns the store and chunk 1's pool path. +func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, string) { t.Helper() ctx := context.Background() mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) @@ -27,49 +27,55 @@ func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, storage.ChunkHead) { return mem, func() error { return nil }, nil } t.Cleanup(func() { dialChunkFiler = prev }) - cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) + root := path.Join(defaultChunkPathCLI, "v1") + put := func(rel string, b []byte) { + p := path.Join(root, rel) + if err := mem.CreateEntry(ctx, path.Dir(p), &filerpb.Entry{Name: path.Base(p), Content: b}, true); err != nil { + t.Fatal(err) + } + } + id, err := layout.NewVolumeID() if err != nil { t.Fatal(err) } - if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } - r, err := chunkstore.NewChunkRemote(mem, mem, defaultChunkPathCLI+"/v1") + vb, err := layout.Volume{ID: id, Name: "v1", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}.Encode() if err != nil { t.Fatal(err) } - cur, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} + put(layout.VolumeName, vb) + manifest := map[uint64]layout.Ref{} + var last string for idx := uint64(0); idx < 2; idx++ { - data := bytes.Repeat([]byte{byte(0x30 + idx)}, 8*4096) - key := fmt.Sprintf("chunks/e1/c%d/k", idx) - if err := r.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + data := bytes.Repeat([]byte{byte(0x30 + idx)}, 4096) + c := layout.NameChunk(idx, data) + put(c.Path(), data) + manifest[idx] = layout.Ref{Owner: "v1", OwnerID: id, Chunk: c} + last = c.Path() } - h, ids, err := r.PrepareManifest(ctx, cur, h, 8*4096) + r, segs, err := layout.Build(manifest) if err != nil { t.Fatal(err) } - if h.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { + for n, b := range segs { + put(n.Path(), b) + } + rn, rb, err := layout.NameRoot(r) + if err != nil { t.Fatal(err) } - for _, id := range ids { - if err := r.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } + put(rn.Path(), rb) + hb, err := layout.Head{VolumeID: id, Epoch: 1, Holder: "s/r", ClaimID: "c", Activity: layout.Activity{Kind: layout.ActIdle}, Current: &rn}.Encode() + if err != nil { + t.Fatal(err) } - return mem, h + put(layout.HeadName, hb) + return mem, path.Join(root, last) } -func decodeVerify(t *testing.T, out string) chunkstore.VerifyResult { +func decodeVerify(t *testing.T, out string) layout.VerifyResult { t.Helper() - var res chunkstore.VerifyResult - if err := json.Unmarshal([]byte(out), &res); err != nil || res.VolumeID == "" { + var res layout.VerifyResult + if err := json.Unmarshal([]byte(out), &res); err != nil { t.Fatalf("stdout is not a verify result: %q (%v)", out, err) } return res @@ -78,41 +84,38 @@ func decodeVerify(t *testing.T, out string) chunkstore.VerifyResult { // verify's exit codes: 0 clean, 3 completed with findings, 1 could not // complete, 2 usage; the result is one JSON object with one finding per line. func TestOpsChunk_VerifyExitCodes(t *testing.T) { - mem, h := verifyCLIFixture(t) + mem, chunk1 := verifyCLIFixture(t) filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"} code, out, errs := runChunk(append([]string{"verify"}, filer...)...) res := decodeVerify(t, out) - if code != 0 || !res.Complete || res.Depth != chunkstore.VerifyBindings || len(res.Findings) != 0 || res.ChunksChecked != 2 || - !strings.Contains(out, `"findings":[]`) || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + if code != 0 || !res.Complete || len(res.Findings) != 0 || res.Chunks != 2 || res.Roots != 1 || !strings.Contains(out, `"Findings":[]`) { t.Fatalf("clean verify: %d %q %q", code, out, errs) } - code, out, errs = runChunk(append([]string{"verify", "--depth", "data", "--timeout", "10s", "--bytes-per-sec", "0"}, filer...)...) - if res = decodeVerify(t, out); code != 0 || res.DistinctChunksRead != 2 || res.BytesRead != 2*8*4096 { + code, out, errs = runChunk(append([]string{"verify", "--depth", "data", "--timeout", "10s", "--orphans"}, filer...)...) + if res = decodeVerify(t, out); code != 0 || !res.Complete || len(res.Findings) != 0 || !res.OrphansChecked { t.Fatalf("clean data verify: %d %q %q", code, out, errs) } - // A binding gone: completed with a finding. - own := strings.TrimPrefix(h.Chunks[1].Key, "@v1/") - if err := mem.DeleteEntry(context.Background(), path.Join(defaultChunkPathCLI, "v1", "keys"), url.PathEscape(own), nil); err != nil { + // A chunk gone: completed with a finding. + if err := mem.DeleteEntry(context.Background(), path.Dir(chunk1), path.Base(chunk1), nil); err != nil { t.Fatal(err) } code, out, errs = runChunk(append([]string{"verify"}, filer...)...) res = decodeVerify(t, out) - if chunkExitFindings != 3 || code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingBindingMissing || - res.FindingsByClass[chunkstore.FindingBindingMissing] != 1 || !strings.Contains(errs, "1 findings") { - t.Fatalf("verify with a missing binding: %d %q %q", code, out, errs) + if chunkExitFindings != 3 || code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || + res.Findings[0].Class != layout.FindMissing || !strings.Contains(errs, "1 findings") { + t.Fatalf("verify with a missing chunk: %d %q %q", code, out, errs) } lines := strings.Split(strings.TrimSpace(out), "\n") - if len(lines) != 3 || !strings.HasPrefix(lines[1], `{"volume":"v1"`) || !strings.Contains(lines[1], `"class":"BINDING_MISSING"`) || lines[2] != "]}" { + if len(lines) != 3 || !strings.Contains(lines[1], `"Class":"MISSING"`) || lines[2] != "]}" { t.Fatalf("findings are not one per line:\n%s", out) } - // Could not complete: the error body, with what was covered. - code, out, _ = runChunk("verify", "--volume", "nope", "--chunk-filer", "filer:18888") - if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != chunkstore.CodeNotChunkVolume || !strings.Contains(out, `"verify":{`) || - !strings.Contains(out, `"incomplete":"error"`) { - t.Fatalf("verify of a missing volume: %d %q", code, out) + // Could not complete: a volume without VOLUME/HEAD. + code, out, errs = runChunk("verify", "--volume", "nope", "--chunk-filer", "filer:18888") + if res = decodeVerify(t, out); code != chunkExitFailed || res.Complete || !strings.Contains(errs, "incomplete") { + t.Fatalf("verify of a missing volume: %d %q %q", code, out, errs) } for _, args := range [][]string{ @@ -136,37 +139,30 @@ func TestOpsChunk_VerifyExitCodes(t *testing.T) { } } -// unreadableStore fails every read of one needle with an error that is not -// "not found" (a volume server answering 503). +// unreadableStore fails every read of one path with an error that is not +// "not found" (a filer answering 503). type unreadableStore struct { *manifestFixtureFiler - fid string + bad string } -func (s unreadableStore) Get(ctx context.Context, fid string) ([]byte, error) { - if fid == s.fid { - return nil, fmt.Errorf("chunkstore: read %s: http 503 from volume:8080", fid) +func (s unreadableStore) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if path.Join(dir, name) == s.bad { + return nil, fmt.Errorf("filer: lookup %s: unavailable (503)", s.bad) } - return s.manifestFixtureFiler.Get(ctx, fid) + return s.manifestFixtureFiler.LookupEntry(ctx, dir, name) } -// A chunk that cannot be read is READ_ERROR (not verified), and the pass -// exits 3: it did not verify everything. -func TestOpsChunk_VerifyReadErrorExits3(t *testing.T) { - mem, h := verifyCLIFixture(t) - own := strings.TrimPrefix(h.Chunks[0].Key, "@v1/") - e, err := mem.LookupEntry(context.Background(), path.Join(defaultChunkPathCLI, "v1", "keys"), url.PathEscape(own)) - if err != nil { - t.Fatal(err) - } - store := unreadableStore{mem, string(e.Extended["swb.fid"])} +// A chunk that cannot be read is not judged: the pass could not complete +// (exit 1) and says why. +func TestOpsChunk_VerifyReadErrorIsIncomplete(t *testing.T) { + mem, chunk1 := verifyCLIFixture(t) + store := unreadableStore{mem, chunk1} dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } code, out, errs := runChunk("verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--depth", "data", "--timeout", "10s") - res := decodeVerify(t, out) - if code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingReadError || - res.ChunksNotRead != 1 || res.ReadRetries != 2 || !strings.Contains(errs, "not verified") { + if code != chunkExitFailed || !strings.Contains(out, "503") || !strings.Contains(errs, "incomplete") { t.Fatalf("verify with an unreadable chunk: %d %q %q", code, out, errs) } } diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go index 75099b092b..da2f042e2d 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -2,7 +2,6 @@ package main import ( "context" - "encoding/json" "errors" "fmt" "io" @@ -12,76 +11,67 @@ import ( "google.golang.org/grpc/status" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/ops" "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/rpc/link" ) -// chunkVolumeDelete: sw-block ops chunk volume-delete --chunk-filer -// host:port --master host:port deletes a chunk volume (Catalog.DeleteVolume) -// after the blockmaster admits it (MarkVolumeDeleting: refused while the -// volume has live or pending authority; afterwards nothing assigns, places -// or binds it again). A failure prints what was done with the error. +// chunkVolumeDelete: sw-block ops chunk volume-delete --volume v +// --chunk-filer host:port --master host:port --request-id r deletes a +// volume in the layout kernel's order. The blockmaster holds the delete's +// authority: ReserveVolumeDeletion commits the reservation (refused while +// an authority line is live; no grant for the volume after it; never given +// back), and CheckVolumeNoLiveLease runs between the HEAD read and the +// update that marks HEAD deleting. A refused delete leaves the volume +// reserved; rerun with the same --request-id once its cause is cleared. A +// rerun on a deleted volume sweeps any object that landed late. func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { - fs := chunkFlagSet("volume-delete", stderr) - var ( - volumeID, filer, base, master, requestID string - timeout time.Duration - ) - fs.StringVar(&requestID, "request-id", "", "this delete's operation id; a rerun with the same id resumes (or gives back) its earlier admission") - fs.StringVar(&volumeID, "volume", "", "volume id (or the first argument)") - fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") - fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") - fs.StringVar(&master, "master", "", "authoritative blockmaster gRPC address (admits the delete)") - fs.DurationVar(&timeout, "timeout", time.Minute, "bound for this delete") - if err := fs.Parse(args); err != nil { - return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) - } - if volumeID == "" && fs.NArg() == 1 { - volumeID = fs.Arg(0) - } else if fs.NArg() != 0 { - return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "give the volume once, as an argument or --volume", false) - } - if volumeID == "" || master == "" || requestID == "" || timeout <= 0 { - return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "a volume, --master and --request-id are required; --timeout must be positive", false) - } - cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, true, timeout, stdout, stderr) - if exit >= 0 { - return exit - } - defer closeFn() - conn, err := link.DialMasterFromEnv(master) - if err != nil { - return chunkResult("volume-delete", nil, err, stdout, stderr) - } - defer conn.Close() - admit := &masterAdmission{lc: control.NewLifecycleServiceClient(conn), token: requestID} - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - res, err := cat.DeleteVolume(ctx, volumeID, admit) - if err != nil { - return volumeDeletePartial(res, err, stdout, stderr) - } - return chunkResult("volume-delete", res, nil, stdout, stderr) + c := newBCommand("volume-delete", time.Minute, stdout, stderr) + var vol volumeFlags + var requestID string + c.bindVolume(&vol, "volume", "volume") + c.fs.StringVar(&requestID, "request-id", "", "this delete's operation id; a rerun with the same id resumes it") + var ref chunkstore.VolumeRef + return c.run(args, true, func() (err error) { + if c.master == "" || requestID == "" || c.timeout <= 0 { + return errors.New("--master and --request-id are required; --timeout must be positive") + } + ref, err = vol.ref("volume") + return err + }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + conn, err := link.DialMasterFromEnv(c.master) + if err != nil { + return nil, err + } + defer conn.Close() + auth := &masterAuthority{lc: control.NewLifecycleServiceClient(conn), req: &control.MarkVolumeDeletingRequest{VolumeId: ref.Name, Token: requestID}} + if err := cat.DeleteVolume(ctx, ref, auth); err != nil { + return nil, err + } + return map[string]string{"volume": ref.Dir(), "state": "deleted"}, nil + }) } -// masterAdmission is the delete's reservation at the blockmaster, held -// under the operation's request id: a rerun with the same id adopts the -// hold an earlier run left (e.g. after a lost response), so its give-back -// releases it, while another operation's hold stays. -type masterAdmission struct { - lc control.LifecycleServiceClient - token string +// masterAuthority is the layout delete's authority, held by the +// blockmaster: both operations are its RPCs, nothing is decided here. +type masterAuthority struct { + lc control.LifecycleServiceClient + req *control.MarkVolumeDeletingRequest } -func (m *masterAdmission) req(vol string) *control.MarkVolumeDeletingRequest { - return &control.MarkVolumeDeletingRequest{VolumeId: vol, Token: m.token} +func (m *masterAuthority) Reserve(ctx context.Context) error { + _, err := m.lc.ReserveVolumeDeletion(ctx, m.req) + return authorityErr(err) } -// admissionErr: FailedPrecondition and InvalidArgument are definite +func (m *masterAuthority) NoLiveLease(ctx context.Context) error { + _, err := m.lc.CheckVolumeNoLiveLease(ctx, m.req) + return authorityErr(err) +} + +// authorityErr: FailedPrecondition and InvalidArgument are definite // refusals; anything else (unavailable, deadline, a lost response) leaves -// the outcome unknown. -func admissionErr(err error) error { +// the outcome unknown and a rerun decides. +func authorityErr(err error) error { switch status.Code(err) { case codes.OK: return nil @@ -90,39 +80,3 @@ func admissionErr(err error) error { } return err } - -func (m *masterAdmission) Admit(ctx context.Context, vol string) error { - _, err := m.lc.MarkVolumeDeleting(ctx, m.req(vol)) - return admissionErr(err) -} - -func (m *masterAdmission) Commit(ctx context.Context, vol string) error { - _, err := m.lc.CommitVolumeDeleting(ctx, m.req(vol)) - return err -} - -func (m *masterAdmission) Abort(ctx context.Context, vol string) error { - _, err := m.lc.AbortVolumeDeleting(ctx, m.req(vol)) - return err -} - -// volumeDeletePartial prints what a failed delete did, with the error, and -// fails. -func volumeDeletePartial(res chunkstore.VolumeDeleteResult, err error, stdout, stderr io.Writer) int { - body := chunkErrBody{Code: codeInternalCLI, Message: err.Error()} - var ce *chunkstore.CatalogError - if errors.As(err, &ce) { - body = chunkErrBody{Code: ce.Code, Message: ce.Detail(), Retryable: ce.Retryable} - } - fmt.Fprintf(stderr, "sw-block ops chunk volume-delete: %s: %s (headMarked=%t completed=%t uncertain=%t)\n", body.Code, body.Message, res.HeadMarked, res.Completed, res.Uncertain) - out, mErr := json.Marshal(struct { - chunkstore.VolumeDeleteResult - Error *chunkErrBody `json:"error"` - }{res, &body}) - if mErr == nil { - if wErr := writeAll(stdout, append(out, '\n')); wErr != nil { - fmt.Fprintf(stderr, "sw-block ops chunk volume-delete: write the result: %v\n", wErr) - } - } - return chunkExitFailed -} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete_schedule_test.go b/seaweed-block/cmd/sw-block/chunk_volume_delete_schedule_test.go new file mode 100644 index 0000000000..50d7f8d978 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete_schedule_test.go @@ -0,0 +1,95 @@ +package main + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +// The real command reserves through the real master while a first lease +// request is paused at RPC ingress. At the command's CAS-time lease check, +// resume that request: committed exclusion must refuse it before the check +// can certify absence. The authority package separately pauses every writer +// immediately before its grant lock; this test composes the transport path. +func TestOpsChunkVolumeDeleteClosesAPausedFirstGrant(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + paused, resume := make(chan struct{}), make(chan struct{}) + grantResult := make(chan error, 1) + var checked atomic.Bool + intercept := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) { + switch info.FullMethod { + case control.WorkspaceService_RenewWorkspaceLease_FullMethodName: + close(paused) + select { + case <-resume: + case <-ctx.Done(): + return nil, ctx.Err() + } + case control.LifecycleService_CheckVolumeNoLiveLease_FullMethodName: + close(resume) + select { + case err := <-grantResult: + if status.Code(err) != codes.FailedPrecondition { + return nil, status.Errorf(codes.Internal, "paused grant escaped reservation: %v", err) + } + case <-ctx.Done(): + return nil, ctx.Err() + } + checked.Store(true) + } + return next(ctx, req) + } + cfg := master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + ServerOptions: []grpc.ServerOption{grpc.ChainUnaryInterceptor(intercept)}, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }} + h, stop := startDeleteMaster(t, cfg) + defer stop() + seedForcedVolumeLease(t, h, false) + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + go func() { + _, err := control.NewWorkspaceServiceClient(conn).RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}) + grantResult <- err + }() + select { + case <-paused: + case <-ctx.Done(): + t.Fatal("first grant did not reach RPC ingress") + } + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "vol-f", "daily") + code, out, stderr := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "paused-first-grant"})...) + if code != 0 || !checked.Load() { + t.Fatalf("delete exit=%d checked=%v out=%s err=%s", code, checked.Load(), out, stderr) + } + cat, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + head, found, err := cat.ReadHead(ctx, v) + if err != nil || !found || head.State != layout.StateDeleted { + t.Fatalf("final HEAD: %+v found=%v err=%v", head, found, err) + } + if !h.Lifecycle().Deletions.CommittedSnapshot("vol-f") { + t.Fatal("command did not commit the real master's reservation") + } + if s := h.Publisher().WorkspaceState("vol-f"); s != nil && s.Lease != nil { + t.Fatalf("late request created a lease: %+v", s.Lease) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go b/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go deleted file mode 100644 index 535811e3a3..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "strings" - "testing" - "time" - - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials/insecure" - "google.golang.org/grpc/status" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/host/master" - "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -type volumeDeleteOutput struct { - chunkstore.VolumeDeleteResult - Error *chunkErrBody `json:"error"` -} - -func lifecycleClient(t *testing.T, addr string) control.LifecycleServiceClient { - t.Helper() - c, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { c.Close() }) - return control.NewLifecycleServiceClient(c) -} - -func startDeleteMaster(t *testing.T, cfg master.Config) (*master.Host, func()) { - t.Helper() - h, err := master.New(cfg) - if err != nil { - t.Fatal(err) - } - h.Start() - return h, func() { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - _ = h.Close(ctx) - } -} - -// volume-delete against a real master runtime: argument checks; a held -// volume and a volume with a snapshot are refused with the admission given -// back (usable again); a lost first admission is adopted and given back by -// a rerun with the same request id (usable after a master restart); a -// completed delete is committed (never created again). -func TestOpsChunk_VolumeDelete(t *testing.T) { - ctx := context.Background() - mem := chunkstore.NewMemFiler() - prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } - t.Cleanup(func() { dialChunkFiler = prev }) - cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) - if err != nil { - t.Fatal(err) - } - geo := chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} - for _, vol := range []string{"v1", "v2", "v3"} { - if _, err := cat.EnsureVolume(ctx, vol, geo); err != nil { - t.Fatal(err) - } - } - // v2 is attached: its HEAD names a holder. - r, err := chunkstore.NewChunkRemote(mem, &gcCLIStore{MemFiler: mem}, defaultChunkPathCLI+"/v2") - if err != nil { - t.Fatal(err) - } - cur, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadActive}); err != nil { - t.Fatal(err) - } - // v3 has a snapshot. - h3, _, err := cat.ReadHead(ctx, "v3") - if err != nil { - t.Fatal(err) - } - if _, err := cat.CreateSnapshot(ctx, "v3", chunkstore.SnapshotRequest{Name: "s", RequestID: "rs"}, h3); err != nil { - t.Fatal(err) - } - - for _, args := range [][]string{ - {"volume-delete", "--chunk-filer", "f:1", "--request-id", "x", "v1"}, // no --master - {"volume-delete", "--chunk-filer", "f:1", "--master", "m:1", "v1"}, // no --request-id - {"volume-delete", "--master", "m:1", "--request-id", "x", "--chunk-filer", "f:1"}, // no volume - {"volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "x", "v2", "extra"}, // two volumes - } { - if code, out, _ := runChunk(args...); code == 0 || !strings.Contains(out, codeBadRequestCLI) { - t.Fatalf("%v: %d %q; want a bad request", args, code, out) - } - } - - cfg := gcTestMasterConfig(t) - cfg.LifecycleStoreDir = t.TempDir() // the reservation store lives here - h, stop := startDeleteMaster(t, cfg) - lc := lifecycleClient(t, h.Addr()) - run := func(vol, op string) (int, volumeDeleteOutput) { - t.Helper() - code, out, _ := runChunk("volume-delete", "--chunk-filer", "f:1", "--master", h.Addr(), "--request-id", op, vol) - var got volumeDeleteOutput - if err := json.Unmarshal([]byte(out), &got); err != nil { - t.Fatalf("volume-delete %s: %q", vol, out) - } - return code, got - } - usable := func(vol string) { - t.Helper() - if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { - t.Fatalf("create %s: %v; want usable", vol, err) - } - } - - // Held: refused, admission given back. - if code, got := run("v2", "op-v2"); code == 0 || got.Error == nil || got.Error.Code != chunkstore.CodeVolumeInUse || !got.Admitted || !got.AdmissionAborted || got.Completed { - t.Fatalf("delete of attached v2: %d %+v", code, got) - } - usable("v2") - - // A first invocation's admission landed and its reply was lost (the - // master holds op-v3); the rerun with the same request id meets the - // snapshot, gives back and so releases that hold too. - if _, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v3", Token: "op-v3"}); err != nil { - t.Fatal(err) - } - if code, got := run("v3", "op-v3"); code == 0 || got.Error == nil || got.Error.Code != chunkstore.CodeVolumeHasSnapshots || !got.Reverted || !got.AdmissionAborted { - t.Fatalf("rerun of v3's delete: %d %+v; want volume_has_snapshots, reverted, given back", code, got) - } - stop() - h, stop = startDeleteMaster(t, cfg) // restart: the given-back id stays usable - defer stop() - lc = lifecycleClient(t, h.Addr()) - usable("v3") - if _, err := cat.EnsureVolume(ctx, "v3", geo); err != nil { - t.Fatalf("attach v3 after the refused delete: %v", err) - } - - // Completed: committed, never created again. - code, got := run("v1", "op-v1") - if code != 0 || got.VolumeID != "v1" || !got.Completed || !got.Committed { - t.Fatalf("delete v1: %d %+v", code, got) - } - if _, err := cat.EnsureVolume(ctx, "v1", geo); chunkstore.CodeOf(err) != chunkstore.CodeVolumeDeleted { - t.Fatalf("recreate v1: %v; want volume_deleted", err) - } - if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 1 << 20, ReplicationFactor: 1}); status.Code(err) != codes.FailedPrecondition { - t.Fatalf("create v1 after its committed delete: %v; want FailedPrecondition", err) - } -} diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 6b97f4ac45..81bfc7e5dd 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -2293,11 +2293,9 @@ func usage(w io.Writer) { fmt.Fprintln(w, " sw-block ops chunk cut|detach --volume --status-addr [--min-lsn ] [--timeout ]") fmt.Fprintln(w, " sw-block ops chunk snapshot --volume --status-addr --name [--label k=v]... [--request-id ] [--consistency crash|app]") fmt.Fprintln(w, " sw-block ops chunk snapshots|snapshot-delete --volume [--name ] --chunk-filer [--chunk-path /swblock/chunks]") - fmt.Fprintln(w, " sw-block ops chunk fork --chunk-filer [--chunk-path /swblock/chunks] --source --snapshot --target [--request-id ] [--label k=v]...") fmt.Fprintln(w, " sw-block ops chunk show --volume --chunk-filer [--chunk-path /swblock/chunks]") - fmt.Fprintln(w, " sw-block ops chunk gc --chunk-filer --master [--chunk-path /swblock/chunks] [--apply] [--grace 1h] [--intent-ttl 1h] [--timeout 1m]") - fmt.Fprintln(w, " sw-block ops chunk verify --volume --chunk-filer [--chunk-path /swblock/chunks] [--snapshot |--all-snapshots] [--depth meta|bindings|data]") - fmt.Fprintln(w, " [--concurrency 2] [--bytes-per-sec 33554432] [--timeout ] (read-only; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)") + fmt.Fprintln(w, " sw-block ops chunk verify --volume --chunk-filer [--chunk-path /swblock/chunks] [--depth meta|bindings|data] [--orphans] [--timeout ]") + fmt.Fprintln(w, " (read-only; every root HEAD names is checked; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)") fmt.Fprintln(w, " sw-block ops volume-unheld --path (exit 0: no process on this host holds it; local filesystems only)") fmt.Fprintln(w, " sw-block ops workspace force-move --master --volume --target-host --target-data --target-ctrl --request-id --confirm-forced @ [--dry-run]") fmt.Fprintln(w, " sw-block ops workspace lost-range --master --volume [--request-id ] (authority only; no bypass: see `sw-block ops workspace help`)") diff --git a/seaweed-block/cmd/sw-block/master_helpers_test.go b/seaweed-block/cmd/sw-block/master_helpers_test.go new file mode 100644 index 0000000000..a1874841e0 --- /dev/null +++ b/seaweed-block/cmd/sw-block/master_helpers_test.go @@ -0,0 +1,56 @@ +package main + +import ( + "context" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +func lifecycleClient(t *testing.T, addr string) control.LifecycleServiceClient { + t.Helper() + c, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + return control.NewLifecycleServiceClient(c) +} + +func startDeleteMaster(t *testing.T, cfg master.Config) (*master.Host, func()) { + t.Helper() + if cfg.WorkspaceRPC && cfg.LayoutCreateVolume == nil { + store := newMemChunkStore() + catalog, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + cfg.LayoutCreateVolume = func(ctx context.Context, spec lifecycle.VolumeSpec) error { + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return err + } + _, err = catalog.CreateVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}, + layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes}) + return err + } + } + h, err := master.New(cfg) + if err != nil { + t.Fatal(err) + } + h.Start() + return h, func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = h.Close(ctx) + } +} diff --git a/seaweed-block/cmd/sw-block/start_any_test.go b/seaweed-block/cmd/sw-block/start_any_test.go new file mode 100644 index 0000000000..a6d3255409 --- /dev/null +++ b/seaweed-block/cmd/sw-block/start_any_test.go @@ -0,0 +1,7 @@ +package main + +import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + +// anyStart is a local root that can start from any HEAD: these tests do +// not model the local store. +func anyStart(layout.Head) error { return nil } diff --git a/seaweed-block/cmd/sw-block/workspace_master_test.go b/seaweed-block/cmd/sw-block/workspace_master_test.go index 227153ab2b..46b9d188f0 100644 --- a/seaweed-block/cmd/sw-block/workspace_master_test.go +++ b/seaweed-block/cmd/sw-block/workspace_master_test.go @@ -21,6 +21,10 @@ import ( // seedForcedVolume makes r1 on node-a the holder of vol-f at epoch 1 (lease // renewed once) with a prepared target binding on node-b. func seedForcedVolume(t *testing.T, h *master.Host) { + seedForcedVolumeLease(t, h, true) +} + +func seedForcedVolumeLease(t *testing.T, h *master.Host, renew bool) { t.Helper() conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { @@ -64,6 +68,9 @@ func seedForcedVolume(t *testing.T, h *master.Host) { t.Fatal("no authority line for vol-f") } } + if !renew { + return + } if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 2ceb1b3f89..6b56109a4e 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -163,6 +163,9 @@ type Publisher struct { workspaceNow func() time.Time workspaceTTL time.Duration workspaceMaxClockSkew time.Duration + // Rebuilt from committed lifecycle deletion reservations before serving. + // Writes hold mu then leaseMu; readers hold either existing grant lock. + deleteReserved map[string]bool // Lease renewal state (workspace_lease_view.go). leaseMu is a memory-only // leaf: lock order p.mu -> leaseMu, never the reverse, and nothing is @@ -178,6 +181,8 @@ type Publisher struct { // testAfterIssuePublish, when set by a test, runs under mu right after // an issued move's lease view is published. testAfterIssuePublish func(volume string) + // Set before concurrent test requests; nil in production. + testBeforeGrantLock func(site string) } // PublicationAdmission surrounds an ordinary mint with local ownership/lifetime @@ -471,7 +476,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr return err } + p.beforeWorkspaceGrantLock("publication") p.mu.Lock() + if p.deleteReserved[ask.VolumeID] { + p.mu.Unlock() + return ErrWorkspaceDeleteReserved + } if p.workspaceUncertain[ask.VolumeID] { p.mu.Unlock() if grant != nil { diff --git a/seaweed-block/core/authority/layout_granted_epoch_guard_test.go b/seaweed-block/core/authority/layout_granted_epoch_guard_test.go new file mode 100644 index 0000000000..4f57222a98 --- /dev/null +++ b/seaweed-block/core/authority/layout_granted_epoch_guard_test.go @@ -0,0 +1,136 @@ +package authority + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "reflect" + "strings" + "testing" +) + +// Start relies on a granted higher epoch, not elapsed time at the volume. +// These are all epoch constructors and reassign request producers in the +// authority package. All request producers converge on applyWithWorkspaceMove: +// an enrolled LOCAL volume refuses an ordinary reassign, and a workspace +// grant is revalidated by prepareWorkspaceMoveLocked under the mint lock. +// Genesis placement has no predecessor; reload copies durable epochs. NET +// promotion and failback use ordinary reassign, never a LOCAL lease bypass. +func TestLayoutGrantedEpochIssuerSites(t *testing.T) { + want := map[string]int{ + "authority.go applyWithWorkspaceMove epoch assignment": 1, + "authority.go reloadFromStore epoch": 1, + "authority.go applyWithWorkspaceMove epoch": 2, + "controller.go decideVolume reassign": 2, + "failback_runtime.go ExecuteFailback reassign": 1, + "workspace.go MoveWorkspace reassign": 1, + "authority.go apply applyWithWorkspaceMove": 2, + "workspace.go MoveWorkspace applyWithWorkspaceMove": 1, + "authority.go applyWithWorkspaceMove prepareWorkspaceMoveLocked": 1, + } + got := map[string]int{} + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + for _, p := range files { + if strings.HasSuffix(p, "_test.go") { + continue + } + raw, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + sites, err := layoutEpochSites(p, raw) + if err != nil { + t.Fatal(err) + } + for k, n := range sites { + got[k] += n + } + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("epoch issuers changed; enumerate each proof/barrier and add its probe: got=%v want=%v", got, want) + } + // Existing behavioral probes pin the deciding guards: clean needs detached + // HEAD plus ACK; forced needs the lease barrier, including restart; an + // ordinary failover cannot bypass an enrolled workspace's guarded move. +} + +func layoutEpochSites(path string, raw []byte) (map[string]int, error) { + f, err := parser.ParseFile(token.NewFileSet(), path, raw, 0) + if err != nil { + return nil, err + } + out := map[string]int{} + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + record := func(kind string) { out[path+" "+fn.Name.Name+" "+kind]++ } + ast.Inspect(fn.Body, func(n ast.Node) bool { + if assign, ok := n.(*ast.AssignStmt); ok { + for _, lhs := range assign.Lhs { + if sel, ok := lhs.(*ast.SelectorExpr); ok && sel.Sel.Name == "Epoch" { + record("epoch assignment") + } + } + } + if inc, ok := n.(*ast.IncDecStmt); ok { + if sel, ok := inc.X.(*ast.SelectorExpr); ok && sel.Sel.Name == "Epoch" { + record("epoch assignment") + } + } + + if call, ok := n.(*ast.CallExpr); ok { + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "applyWithWorkspaceMove" || sel.Sel.Name == "prepareWorkspaceMoveLocked") { + record(sel.Sel.Name) + } + } + lit, ok := n.(*ast.CompositeLit) + if !ok { + return true + } + typ := "" + switch x := lit.Type.(type) { + case *ast.SelectorExpr: + typ = x.Sel.Name + case *ast.Ident: + typ = x.Name + } + for _, e := range lit.Elts { + kv, ok := e.(*ast.KeyValueExpr) + if !ok { + continue + } + key, ok := kv.Key.(*ast.Ident) + if !ok { + continue + } + if typ == "AssignmentInfo" && key.Name == "Epoch" { + record("epoch") + } + if typ == "AssignmentAsk" && key.Name == "Intent" { + if id, ok := kv.Value.(*ast.Ident); ok && id.Name == "IntentReassign" { + record("reassign") + } + } + } + return true + }) + } + return out, nil +} + +func TestLayoutEpochEnumerationRejectsANewIssuer(t *testing.T) { + got, err := layoutEpochSites("new.go", []byte(`package authority; func bypass(){ _ = adapter.AssignmentInfo{Epoch: 99}; _ = AssignmentAsk{Intent:IntentReassign} }`)) + if err != nil { + t.Fatal(err) + } + if got["new.go bypass epoch"] != 1 || got["new.go bypass reassign"] != 1 { + t.Fatal("new issuer escaped enumeration", got) + } +} diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 8e1230072b..5fff3e6ad4 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -55,6 +55,8 @@ type WorkspaceLease struct { type WorkspaceRevokeAck struct { ReplicaID string Epoch, HeadGen uint64 + Holder string + RemoteLSN uint64 } type WorkspaceMoveRecord struct { @@ -188,13 +190,14 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, } func validateWorkspaceMoveRequest(req WorkspaceMoveRequest) error { - // INV-WS-SAME-HOST-CLEAN-MOVE-001: clean moves may reuse the host, - // but every move preserves its logical replica slot. + // A same-host clean move still needs its seal/ACK; a forced recovery + // still needs its expired lease barrier and persisted lost range. + // Every move preserves its logical replica slot. // Refuse before locking or persisting a reservation/authority epoch. if req.ExpectedReplicaID != req.TargetReplicaID { return fmt.Errorf("workspace move: v1 requires the same logical replica id") } - if req.RequestID == "" || req.VolumeID == "" || req.ExpectedHost == "" || req.TargetHost == "" || (req.ExpectedHost == req.TargetHost && (req.Kind != "clean" || req.Force)) || req.ExpectedReplicaID == "" || req.ExpectedEpoch == 0 || req.TargetReplicaID == "" || + if req.RequestID == "" || req.VolumeID == "" || req.ExpectedHost == "" || req.TargetHost == "" || req.ExpectedReplicaID == "" || req.ExpectedEpoch == 0 || req.TargetReplicaID == "" || req.TargetDataAddr == "" || req.TargetCtrlAddr == "" || (req.Kind != "clean" && req.Kind != "forced") || req.Force != (req.Kind == "forced") { return fmt.Errorf("workspace move: invalid request") } @@ -264,6 +267,10 @@ func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, return WorkspaceMoveRecord{}, err } p.mu.Lock() + if p.deleteReserved[req.VolumeID] { + p.mu.Unlock() + return WorkspaceMoveRecord{}, ErrWorkspaceDeleteReserved + } r, replay, err := p.issuedWorkspaceReplayLocked(req) p.mu.Unlock() if err != nil { @@ -305,7 +312,7 @@ func (p *Publisher) BeginWorkspaceRevocation(ctx context.Context, volume, holder return p.persistWorkspaceLocked(volume, s) } -func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, ack WorkspaceRevokeAck) error { +func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, ack WorkspaceRevokeAck, h WorkspaceHead) error { if err := ctx.Err(); err != nil { return err } @@ -313,16 +320,23 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a defer p.mu.Unlock() _, line, ok := p.workspaceLineLocked(volume) s := cloneWorkspace(p.workspace[volume]) - if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.HeadGen == 0 || s == nil || s.Lease == nil || !s.Lease.Revoking { + if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.Holder == "" || s == nil || s.Lease == nil || !s.Lease.Revoking { return fmt.Errorf("workspace revoke ACK: stale or unsolicited") } + if !h.Detached || h.Deleting || h.Epoch != ack.Epoch || h.Holder != ack.Holder { + return fmt.Errorf("workspace revoke ACK: no detached HEAD for this holder") + } + ack.RemoteLSN = h.RemoteLSN lease := *s.Lease lease.ExpiresAtNS = min(lease.ExpiresAtNS, p.leaseDeadlineLocked(volume).UnixNano()) if p.WorkspaceLeaseValidity(lease) == 0 { return fmt.Errorf("workspace revoke ACK: lease expired; forced move required") } - if s.Ack != nil && *s.Ack != ack { - return fmt.Errorf("workspace revoke ACK changed") + if s.Ack != nil { + if s.Ack.ReplicaID != ack.ReplicaID || s.Ack.Epoch != ack.Epoch || s.Ack.Holder != ack.Holder || s.Ack.RemoteLSN != ack.RemoteLSN { + return fmt.Errorf("workspace revoke ACK changed") + } + return nil // generation is readout only; retain the original ACK } s.Ack = &ack return p.persistWorkspaceLocked(volume, s) @@ -529,7 +543,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra return nil, 0, time.Time{}, fmt.Errorf("workspace move: HEAD not owned by expected holder") } if q.Kind == "clean" { - if !h.Detached || !s.Lease.Revoking || s.Ack == nil || s.Ack.ReplicaID != q.ExpectedReplicaID || s.Ack.Epoch != q.ExpectedEpoch || s.Ack.HeadGen != h.Gen { + if !h.Detached || !s.Lease.Revoking || s.Ack == nil || s.Ack.ReplicaID != q.ExpectedReplicaID || s.Ack.Epoch != h.Epoch || s.Ack.Holder != h.Holder || s.Ack.RemoteLSN != h.RemoteLSN { return nil, 0, time.Time{}, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK") } } diff --git a/seaweed-block/core/authority/workspace_clean_metadata_test.go b/seaweed-block/core/authority/workspace_clean_metadata_test.go new file mode 100644 index 0000000000..8585243c94 --- /dev/null +++ b/seaweed-block/core/authority/workspace_clean_metadata_test.go @@ -0,0 +1,174 @@ +package authority + +import ( + "context" + "go/ast" + "go/parser" + "go/token" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// A stopped image is stable while operator metadata may still change HEAD. +// Neither a snapshot deletion nor a restore dependency invalidates its ACK. +func TestWorkspaceCleanMoveAfterStoppedSnapshotMetadataChanges(t *testing.T) { + for _, op := range []string{"DeleteSnapshot", "AddDependent"} { + t.Run(op, func(t *testing.T) { + p := newLeasePublisher(t, &failingStore{}, time.Second, newTestClock()) + bindAndGrant(t, p, "v", "r") + ctx := context.Background() + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err != nil { + t.Fatal(err) + } + root := layout.RootName{Hash: layout.Hash{1}} + h := layout.Head{Gen: 7, Epoch: 1, Holder: "host/r", Position: 42, State: layout.StateDetached, Current: &root, Activity: layout.Activity{Kind: layout.ActIdle}, Snapshots: map[string]layout.Snapshot{"s": {Root: root, Position: 42}}} + var next layout.Head + var changed bool + var err error + if op == "DeleteSnapshot" { + next, changed, err = h.DeleteSnapshot("s") + } else { + id, e := layout.NewVolumeID() + if e != nil { + t.Fatal(e) + } + next, changed, err = h.AddDependent("s", layout.Dependent{Target: "restore", TargetID: id}, root) + } + if err != nil || !changed { + t.Fatalf("operator transition: changed=%t err=%v", changed, err) + } + next.Gen++ // the filer's successful conditional metadata write + req := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "host", TargetHost: "next", ExpectedEpoch: 1, TargetDataAddr: "d", TargetCtrlAddr: "c", Kind: "clean"} + grant, err := p.MoveWorkspace(ctx, req, WorkspaceHead{Gen: next.Gen, Epoch: next.Epoch, Holder: next.Holder, RemoteLSN: next.Position, Detached: next.State == layout.StateDetached}) + if err != nil || !grant.Issued { + t.Fatalf("clean move after %s: grant=%+v err=%v; want admitted", op, grant, err) + } + if grant.HeadGen != next.Gen || grant.RemoteLSN != h.Position { + t.Fatalf("readout lost: %+v", grant) + } + }) + } +} + +// A generation is readout only on both ACK receipt and move admission. +func TestWorkspaceStopProofNeverBranchesOnGeneration(t *testing.T) { + f, err := parser.ParseFile(token.NewFileSet(), "workspace.go", nil, 0) + if err != nil { + t.Fatal(err) + } + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || (fn.Name.Name != "AckWorkspaceRevocation" && fn.Name.Name != "prepareWorkspaceMoveLocked") { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + cond, ok := n.(*ast.IfStmt) + if !ok { + return true + } + ast.Inspect(cond.Cond, func(n ast.Node) bool { + if s, ok := n.(*ast.SelectorExpr); ok && (s.Sel.Name == "HeadGen" || s.Sel.Name == "Gen") { + t.Errorf("%s branches on generation instead of stop identity", fn.Name.Name) + } + return true + }) + return true + }) + } +} + +func TestWorkspaceAckReplayKeepsOriginalGenerationReadout(t *testing.T) { + p := newLeasePublisher(t, &failingStore{}, time.Second, newTestClock()) + bindAndGrant(t, p, "v", "r") + ctx := context.Background() + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + ack := WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42} + if err := p.AckWorkspaceRevocation(ctx, "v", ack, WorkspaceHead{Detached: true, Epoch: ack.Epoch, Holder: ack.Holder, RemoteLSN: ack.RemoteLSN}); err != nil { + t.Fatal(err) + } + ack.HeadGen = 99 + if err := p.AckWorkspaceRevocation(ctx, "v", ack, WorkspaceHead{Detached: true, Epoch: ack.Epoch, Holder: ack.Holder, RemoteLSN: ack.RemoteLSN}); err != nil { + t.Fatal("metadata-only ACK replay refused", err) + } + if p.WorkspaceState("v").Ack.HeadGen != 7 { + t.Fatal("replay replaced the original generation readout") + } + ack.RemoteLSN++ + if err := p.AckWorkspaceRevocation(ctx, "v", ack, WorkspaceHead{Detached: true, Epoch: ack.Epoch, Holder: ack.Holder, RemoteLSN: ack.RemoteLSN}); err == nil { + t.Fatal("different stopped image replay accepted") + } +} + +func TestWorkspaceAckValidatesTheObservedStoppedHead(t *testing.T) { + for _, tc := range []struct { + name string + head WorkspaceHead + admit bool + }{ + {"same stop, changed generation", WorkspaceHead{Gen: 99, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true}, true}, + {"still live", WorkspaceHead{Epoch: 1, Holder: "host/r", RemoteLSN: 42}, false}, + {"foreign epoch", WorkspaceHead{Epoch: 2, Holder: "host/r", Detached: true}, false}, + {"foreign holder", WorkspaceHead{Epoch: 1, Holder: "other/r", Detached: true}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + p := newLeasePublisher(t, &failingStore{}, time.Second, newTestClock()) + bindAndGrant(t, p, "v", "r") + ctx := context.Background() + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, Holder: "host/r", HeadGen: 7, RemoteLSN: 999}, tc.head) + if (err == nil) != tc.admit { + t.Fatalf("admit=%t: %v", tc.admit, err) + } + ack := p.WorkspaceState("v").Ack + if !tc.admit && ack != nil { + t.Fatal("refusal persisted an ACK") + } + if tc.admit && (ack == nil || ack.RemoteLSN != tc.head.RemoteLSN) { + t.Fatalf("ACK did not persist the authoritative position: %+v", ack) + } + }) + } +} + +func TestWorkspaceCleanMoveRequiresTheAckedStopIdentity(t *testing.T) { + for _, tc := range []struct { + name string + head WorkspaceHead + admit bool + }{ + {"same stop, changed generation", WorkspaceHead{Gen: 99, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true}, true}, + {"not detached", WorkspaceHead{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42}, false}, + {"other epoch", WorkspaceHead{Gen: 7, Epoch: 2, Holder: "host/r", RemoteLSN: 42, Detached: true}, false}, + {"other holder", WorkspaceHead{Gen: 7, Epoch: 1, Holder: "other/r", RemoteLSN: 42, Detached: true}, false}, + {"other position", WorkspaceHead{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 43, Detached: true}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + p := newLeasePublisher(t, &failingStore{}, time.Second, newTestClock()) + bindAndGrant(t, p, "v", "r") + ctx := context.Background() + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err != nil { + t.Fatal(err) + } + req := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "host", TargetHost: "next", ExpectedEpoch: 1, TargetDataAddr: "d", TargetCtrlAddr: "c", Kind: "clean"} + got, err := p.MoveWorkspace(ctx, req, tc.head) + if (err == nil) != tc.admit || got.Issued != tc.admit { + t.Fatalf("admit=%t: %+v %v", tc.admit, got, err) + } + if !tc.admit && len(p.WorkspaceState("v").Moves) != 0 { + t.Fatal("refusal wrote a reservation") + } + }) + } +} diff --git a/seaweed-block/core/authority/workspace_delete_guard_test.go b/seaweed-block/core/authority/workspace_delete_guard_test.go new file mode 100644 index 0000000000..264c056091 --- /dev/null +++ b/seaweed-block/core/authority/workspace_delete_guard_test.go @@ -0,0 +1,95 @@ +package authority + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestDeletionReservationGuardSites(t *testing.T) { + // A new field access or grant-bound writer must join the causal controls. + flagSites := map[string]bool{ + "ReserveWorkspaceDeletion": true, "NoLiveWorkspaceLease": true, + "applyWithWorkspaceMove": true, "MoveWorkspace": true, + "RenewWorkspaceLease": true, "firstWorkspaceGrant": true, + "regrantWorkspaceLease": true, "extendWorkspaceLease": true, + } + boundSites := map[string]bool{ + "publishIssuedLeaseLocked": true, "setLeaseDeadlineLocked": true, + "RenewWorkspaceLease": true, "regrantWorkspaceLease": true, + "extendWorkspaceLease": true, + // Reply-only copies never increase published validity. + "WorkspaceLeaseReply": true, "AckWorkspaceRevocation": true, + // Copies the published horizon into the leaf view under mu -> leaseMu. + "deriveLeaseLocked": true, + // Positive lease construction and publication, or a plain clone. + "newWorkspaceLease": true, "firstWorkspaceGrant": true, + "issueWorkspaceMove": true, "cloneWorkspace": true, + } + seenFlag, seenBound := map[string]bool{}, map[string]bool{} + entries, err := os.ReadDir(".") + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if !strings.HasSuffix(e.Name(), ".go") || strings.HasSuffix(e.Name(), "_test.go") { + continue + } + f, err := parser.ParseFile(token.NewFileSet(), filepath.Clean(e.Name()), nil, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range f.Decls { + name := "package initializer" + if fn, ok := d.(*ast.FuncDecl); ok { + name = fn.Name.Name + } + ast.Inspect(d, func(n ast.Node) bool { + if s, ok := n.(*ast.SelectorExpr); ok && s.Sel.Name == "deleteReserved" { + seenFlag[name] = true + if !flagSites[name] { + t.Errorf("unclassified deletion flag reader/writer %s in %s", name, e.Name()) + } + } + if a, ok := n.(*ast.AssignStmt); ok { + for _, lhs := range a.Lhs { + if s, ok := lhs.(*ast.SelectorExpr); ok && (s.Sel.Name == "deadline" || s.Sel.Name == "horizon" || s.Sel.Name == "ExpiresAtNS" || s.Sel.Name == "Lease") { + seenBound[name] = true + if !boundSites[name] { + t.Errorf("unclassified lease bound writer %s in %s", name, e.Name()) + } + } + } + } + if kv, ok := n.(*ast.KeyValueExpr); ok { + if key, ok := kv.Key.(*ast.Ident); ok && (key.Name == "ExpiresAtNS" || key.Name == "Lease" || key.Name == "deadline" || key.Name == "horizon") { + seenBound[name] = true + if !boundSites[name] { + t.Errorf("unclassified lease constructor %s in %s", name, e.Name()) + } + } + } + if call, ok := n.(*ast.CallExpr); ok { + if fn, ok := call.Fun.(*ast.SelectorExpr); ok && fn.Sel.Name == "newWorkspaceLease" && !boundSites[name] { + t.Errorf("unclassified lease grant constructor caller %s in %s", name, e.Name()) + } + } + return true + }) + } + } + for name := range flagSites { + if !seenFlag[name] { + t.Errorf("missing reservation guard at %s", name) + } + } + for name := range boundSites { + if !seenBound[name] { + t.Errorf("missing bound classification %s", name) + } + } +} diff --git a/seaweed-block/core/authority/workspace_delete_reservation.go b/seaweed-block/core/authority/workspace_delete_reservation.go new file mode 100644 index 0000000000..5f8220e872 --- /dev/null +++ b/seaweed-block/core/authority/workspace_delete_reservation.go @@ -0,0 +1,92 @@ +package authority + +import ( + "context" + "errors" + "fmt" + "time" +) + +var ErrWorkspaceDeleteReserved = errors.New("workspace: deletion is committed") + +// ErrWorkspaceDeleteRefused means the early reservation check refused before +// calling persist. Context and persistence errors never carry this sentinel. +var ErrWorkspaceDeleteRefused = errors.New("workspace: deletion refused before persistence") + +func (p *Publisher) beforeWorkspaceGrantLock(site string) { + if p.testBeforeGrantLock != nil { + p.testBeforeGrantLock(site) + } +} + +// ReserveWorkspaceDeletion persists the existing lifecycle reservation as +// committed, then closes all grant writers under mu -> leaseMu. persist must +// not reenter Publisher. A replay does no I/O. On startup, call this for every +// reloaded committed reservation before serving requests (persist is then nil). +func (p *Publisher) ReserveWorkspaceDeletion(ctx context.Context, volume string, persist func() error) error { + p.mu.Lock() + defer p.mu.Unlock() + if err := ctx.Err(); err != nil { + return err + } + if volume == "" { + return errors.New("workspace delete: volume is required") + } + if p.deleteReserved[volume] { + return nil + } + // An operator's delete of a volume still served is refused before the + // irreversible step: nothing is persisted while a lease is live now. + // This decides nothing for safety (the closed grant writers and the + // check at the delete's HEAD update do); it stops an outage by mistake. + if persist != nil { + if err := p.liveLeaseLocked(volume); err != nil { + return fmt.Errorf("%w: %w", ErrWorkspaceDeleteRefused, err) + } + } + if persist != nil { + if err := persist(); err != nil { + return err + } + } + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + if p.deleteReserved == nil { + p.deleteReserved = map[string]bool{} + } + p.deleteReserved[volume] = true + return nil +} + +// NoLiveWorkspaceLease checks the deletion's stable lease premise. +func (p *Publisher) NoLiveWorkspaceLease(ctx context.Context, volume string) error { + p.mu.Lock() + defer p.mu.Unlock() + if err := ctx.Err(); err != nil { + return err + } + if !p.deleteReserved[volume] { + return errors.New("workspace delete: committed reservation required") + } + return p.liveLeaseLocked(volume) +} + +// liveLeaseLocked reports a lease of volume that may still be live (or +// that cannot be proven absent). Caller holds mu. +func (p *Publisher) liveLeaseLocked(volume string) error { + // A skipped authority record is not evidence that its lease never existed. + // Until recovery identifies it, do not certify absence from a partial load. + if len(p.loadErrs) != 0 { + return errors.New("workspace delete: authority records were skipped during recovery; lease absence is unknown") + } + if p.workspaceUncertain[volume] { + return errors.New("workspace delete: lease persistence uncertain; restart required") + } + if s := p.workspace[volume]; s != nil && s.Lease != nil { + until, _, err := p.forcedMoveBarrierLocked(volume, s.Lease) + if err != nil { + return fmt.Errorf("workspace delete: live until %s: %w", time.Unix(0, until).UTC().Format(time.RFC3339Nano), err) + } + } + return nil +} diff --git a/seaweed-block/core/authority/workspace_delete_reservation_test.go b/seaweed-block/core/authority/workspace_delete_reservation_test.go new file mode 100644 index 0000000000..0ca5fad970 --- /dev/null +++ b/seaweed-block/core/authority/workspace_delete_reservation_test.go @@ -0,0 +1,272 @@ +package authority + +import ( + "context" + "errors" + "strings" + "testing" + "time" +) + +type deleteGrantStore struct{ failingStore } + +func (*deleteGrantStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) { + return map[string][]WorkspaceLostRange{}, nil, nil +} + +type skippedDeleteStore struct{ deleteGrantStore } + +func (*skippedDeleteStore) LoadWithSkips() ([]DurableRecord, []error, error) { + return nil, []error{errors.New("corrupt authority record")}, nil +} + +func TestDeleteCannotProveNoLeaseFromASkippedAuthorityRecord(t *testing.T) { + p := NewPublisher(nil, WithStore(&skippedDeleteStore{})) + if err := p.ReserveWorkspaceDeletion(context.Background(), "v", nil); err != nil { + t.Fatal(err) + } + if err := p.NoLiveWorkspaceLease(context.Background(), "v"); err == nil { + t.Fatal("a partial authority load proved lease absence") + } +} + +// A delete of a volume still served is refused before anything is +// persisted, and the holder keeps renewing: a mistaken delete is not an +// outage. Once the lease has lapsed the reservation commits. +func TestDeleteOfALiveVolumeIsRefusedBeforePersisting(t *testing.T) { + ctx := context.Background() + c := newTestClock() + p := newLeasePublisher(t, &deleteGrantStore{}, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + persisted := false + if err := p.ReserveWorkspaceDeletion(ctx, "v", func() error { persisted = true; return nil }); !errors.Is(err, ErrWorkspaceDeleteRefused) || !strings.Contains(err.Error(), "live until") || persisted { + t.Fatalf("reserve of a live volume: %v (persisted %t); want refused, nothing persisted", err, persisted) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatalf("the holder's renewal after a refused delete: %v", err) + } + c.at(1000) + if err := p.ReserveWorkspaceDeletion(ctx, "v", func() error { persisted = true; return nil }); err != nil || !persisted { + t.Fatalf("reserve after the lease lapsed: %v (persisted %t)", err, persisted) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { + t.Fatal("a committed delete extended a holder lease") + } +} + +// A committed reservation reloaded at startup (persist nil) while a lease +// record exists stops every grant and waits for the whole lease. +func TestCommittedDeleteStopsGrantsAndWaitsForTheWholeLease(t *testing.T) { + ctx := context.Background() + c := newTestClock() + p := newLeasePublisher(t, &deleteGrantStore{}, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + if err := p.ReserveWorkspaceDeletion(ctx, "v", nil); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { + t.Fatal("committed delete extended a holder lease") + } + // First horizon is 45 s, plus the default skew of 20 s. Host validity + // expiring earlier is insufficient evidence for deleting remote data. + c.at(64) + if err := p.NoLiveWorkspaceLease(ctx, "v"); err == nil || !strings.Contains(err.Error(), "live until") { + t.Fatalf("before durable horizon + skew: %v", err) + } + c.at(65) + if err := p.NoLiveWorkspaceLease(ctx, "v"); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { + t.Fatal("expired regrant reopened a committed delete") + } +} + +func TestDeleteReservationMustBeDurableBeforeItCanProveNoLease(t *testing.T) { + p := NewPublisher(nil) + errDisk := errors.New("reservation sync failed") + if err := p.ReserveWorkspaceDeletion(context.Background(), "v", func() error { return errDisk }); !errors.Is(err, errDisk) { + t.Fatalf("persist error: %v", err) + } + if err := p.NoLiveWorkspaceLease(context.Background(), "v"); err == nil { + t.Fatal("a failed reservation proved no lease") + } +} + +func TestDeleteReservationPersistenceDoesNotBlockLiveRenewal(t *testing.T) { + c := newTestClock() + p := newLeasePublisher(t, &deleteGrantStore{}, 30*time.Second, c) + // Another volume's holder renews while v's reservation is on disk. + bindAndGrant(t, p, "w", "r") + entered, release, reserved := make(chan struct{}), make(chan struct{}), make(chan error, 1) + go func() { + reserved <- p.ReserveWorkspaceDeletion(context.Background(), "v", func() error { + close(entered) + <-release + return nil + }) + }() + <-entered + renewed := make(chan error, 1) + go func() { _, err := p.RenewWorkspaceLease(context.Background(), "w", "r", 1); renewed <- err }() + select { + case err := <-renewed: + close(release) + if err != nil { + t.Fatal(err) + } + case <-time.After(time.Second): + close(release) + t.Fatal("live renewal waited on reservation disk I/O") + } + if err := <-reserved; err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); !errors.Is(err, ErrWorkspaceDeleteReserved) { + t.Fatal(err) + } +} + +func TestDeleteReservationClosesPausedGrantWriters(t *testing.T) { + ctx := context.Background() + for _, site := range []string{"publication", "first grant", "regrant", "renewal", "extension", "move"} { + t.Run(site, func(t *testing.T) { + c := newTestClock() + store := &deleteGrantStore{} + p := newLeasePublisher(t, store, 30*time.Second, c) + if site != "publication" { + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if site != "first grant" { + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + } + } + if site == "regrant" || site == "move" { + c.at(100) + } + paused, resume := make(chan struct{}), make(chan struct{}) + p.testBeforeGrantLock = func(at string) { + if at == site || (site == "move" && at == "publication") { + close(paused) + <-resume + } + } + done := make(chan error, 1) + go func() { + switch site { + case "publication": + done <- p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}) + case "extension": + p.extWG.Add(1) + p.extendWorkspaceLease("v", "r", 1, c.sec(100)) + done <- nil + case "move": + _, err := p.MoveWorkspace(ctx, WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "a", TargetHost: "b", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}, WorkspaceHead{Gen: 1, Epoch: 1, Holder: "a/r"}) + done <- err + default: + _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1) + done <- err + } + }() + select { + case <-paused: + case err := <-done: + t.Fatalf("request did not reach %s boundary: %v", site, err) + } + // The delete is admitted once the old lease has lapsed (a live one + // refuses it early); the paused writer must still be closed. + c.at(100) + if err := p.ReserveWorkspaceDeletion(ctx, "v", func() error { return nil }); err != nil { + close(resume) + t.Fatal(err) + } + if err := p.NoLiveWorkspaceLease(ctx, "v"); err != nil { + t.Fatal(err) + } + writes := len(store.records) + close(resume) + err := <-done + if site != "extension" && !errors.Is(err, ErrWorkspaceDeleteReserved) { + t.Fatalf("paused %s: %v", site, err) + } + if len(store.records) != writes { + t.Fatalf("paused %s wrote after the no-live-lease proof", site) + } + if err := p.NoLiveWorkspaceLease(ctx, "v"); err != nil { + t.Fatalf("paused %s invalidated the proof: %v", site, err) + } + }) + } +} + +func TestDeleteReservationReplayAndRestart(t *testing.T) { + ctx := context.Background() + c := newTestClock() + store := &deleteGrantStore{} + p := newLeasePublisher(t, store, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + writes := 0 + persist := func() error { writes++; return nil } + c.at(70) // the lease has lapsed: a live one refuses the delete early + if err := p.ReserveWorkspaceDeletion(ctx, "v", persist); err != nil { + t.Fatal(err) + } + if err := p.ReserveWorkspaceDeletion(ctx, "v", persist); err != nil { + t.Fatal(err) + } + if writes != 1 { + t.Fatalf("reservation persisted %d times", writes) + } + // The fake preserves the latest complete authority record; the lifecycle + // reservation is independently reloaded by master.New before serving. + last := store.records[len(store.records)-1] + c.at(100) + loaded := newLeasePublisher(t, &deleteGrantStore{failingStore: failingStore{records: []DurableRecord{last}}}, 30*time.Second, c) + if err := loaded.ReserveWorkspaceDeletion(ctx, "v", nil); err != nil { + t.Fatal(err) + } + if _, err := loaded.RenewWorkspaceLease(ctx, "v", "r", 1); !errors.Is(err, ErrWorkspaceDeleteReserved) { + t.Fatal(err) + } + // A restart conservatively starts a fresh TTL deadline, even though the + // old persisted horizon has passed. It too must expire with the skew. + c.at(149) + if err := loaded.NoLiveWorkspaceLease(ctx, "v"); err == nil { + t.Fatal("restart deadline was ignored") + } + c.at(150) + if err := loaded.NoLiveWorkspaceLease(ctx, "v"); err != nil { + t.Fatal(err) + } +} + +func TestDeleteReservationContextAndPersistenceFailuresStayUnknown(t *testing.T) { + canceled, cancel := context.WithCancel(context.Background()) + cancel() + expired, stop := context.WithDeadline(context.Background(), time.Unix(0, 0)) + defer stop() + disk := errors.New("disk response lost") + for _, tc := range []struct { + name string + ctx context.Context + failure error + }{ + {"cancel", canceled, context.Canceled}, + {"deadline", expired, context.DeadlineExceeded}, + {"persist", context.Background(), disk}, + } { + t.Run(tc.name, func(t *testing.T) { + p := newLeasePublisher(t, &deleteGrantStore{}, 30*time.Second, newTestClock()) + err := p.ReserveWorkspaceDeletion(tc.ctx, "v", func() error { return disk }) + if !errors.Is(err, tc.failure) || errors.Is(err, ErrWorkspaceDeleteRefused) { + t.Fatalf("failure classification=%v", err) + } + if err := p.NoLiveWorkspaceLease(context.Background(), "v"); err == nil { + t.Fatal("failed reservation proved lease absence") + } + }) + } +} diff --git a/seaweed-block/core/authority/workspace_expiry_test.go b/seaweed-block/core/authority/workspace_expiry_test.go index e5049ed947..bbeb111858 100644 --- a/seaweed-block/core/authority/workspace_expiry_test.go +++ b/seaweed-block/core/authority/workspace_expiry_test.go @@ -21,7 +21,7 @@ func TestWorkspaceExpiredLeaseCannotAcknowledgeCLEAN(t *testing.T) { t.Fatal(err) } now = now.Add(2 * time.Second) - if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err == nil { + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err == nil { t.Fatal("expired lease recorded a CLEAN revocation ACK") } if p.WorkspaceState("v").Ack != nil { diff --git a/seaweed-block/core/authority/workspace_issue_publish_test.go b/seaweed-block/core/authority/workspace_issue_publish_test.go index 3c650a87dc..a28b5538f3 100644 --- a/seaweed-block/core/authority/workspace_issue_publish_test.go +++ b/seaweed-block/core/authority/workspace_issue_publish_test.go @@ -24,7 +24,7 @@ func TestWorkspaceIssuePublishNeverLowersARenewedDeadline(t *testing.T) { if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { t.Fatal(err) } - if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen}); err != nil { + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}, WorkspaceHead{Detached: true, Epoch: 1, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}); err != nil { t.Fatal(err) } now = now.Add(100 * time.Millisecond) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 9cbf2570bf..4854429616 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -178,7 +178,7 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { t.Fatal(err) } check("revocation") - if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "old/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "old/r", RemoteLSN: 42}); err != nil { t.Fatal(err) } check("ack") @@ -878,7 +878,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { writersDone <- fmt.Errorf("revocation: %w", err) return } - err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}) + err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "old/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "old/r", RemoteLSN: 42}) clock.Resume() if err != nil { writersDone <- fmt.Errorf("ack: %w", err) diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index 92577cc553..c8e3979c9f 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -222,6 +222,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri if err := ctx.Err(); err != nil { return WorkspaceLease{}, err } + p.beforeWorkspaceGrantLock("renewal") p.leaseMu.Lock() now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it // unlock releases leaseMu on a path that grants nothing and logs a due @@ -232,6 +233,10 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri p.leaseMu.Unlock() p.logLease(summary) } + if p.deleteReserved[volume] { + unlock() + return WorkspaceLease{}, ErrWorkspaceDeleteReserved + } lv := p.leaseViews[volume] if lv == nil || !lv.d.bound || lv.d.replica != holder || lv.d.epoch != epoch { unlock() @@ -316,7 +321,12 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri // its holder's lease. A host whose first renewal fails does not fence: it has // no deadline yet and retries. The durable horizon starts at now+1.5*TTL. func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { + p.beforeWorkspaceGrantLock("first grant") p.mu.Lock() + if p.deleteReserved[volume] { + p.mu.Unlock() + return WorkspaceLease{}, ErrWorkspaceDeleteReserved + } _, line, ok := p.workspaceLineLocked(volume) if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch { p.mu.Unlock() @@ -353,12 +363,16 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri // reusing the forced-move barrier so the old process's validity is past. // The live renewal path releases leaseMu before entering this writer. func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { + p.beforeWorkspaceGrantLock("regrant") // INV-WS-RENEW-NONBLOCKING-001: a held writer refuses this attempt; // a returning process can retry after that writer has settled. if !p.mu.TryLock() { return WorkspaceLease{}, fmt.Errorf("workspace lease: authority writer busy; retry") } defer p.mu.Unlock() + if p.deleteReserved[volume] { + return WorkspaceLease{}, ErrWorkspaceDeleteReserved + } if err := ctx.Err(); err != nil { return WorkspaceLease{}, err } @@ -409,6 +423,7 @@ func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time // (INV-AUTH-UNCERTAIN-001); a failed recheck is a known no-write. func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, trigger time.Time) { defer p.extWG.Done() + p.beforeWorkspaceGrantLock("extension") var note string defer func() { if note != "" { @@ -427,7 +442,7 @@ func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, tr p.leaseMu.Lock() closing := p.leaseClosing p.leaseMu.Unlock() - if closing { + if closing || p.deleteReserved[volume] { return } _, line, ok := p.workspaceLineLocked(volume) diff --git a/seaweed-block/core/authority/workspace_lost_range_test.go b/seaweed-block/core/authority/workspace_lost_range_test.go index 4be162bd56..8f1a197677 100644 --- a/seaweed-block/core/authority/workspace_lost_range_test.go +++ b/seaweed-block/core/authority/workspace_lost_range_test.go @@ -101,7 +101,7 @@ func TestWorkspaceCleanMoveRecordsNoLostRange(t *testing.T) { if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil { t.Fatal(err) } - if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}); err != nil { + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7, Holder: "old-node/old", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42}); err != nil { t.Fatal(err) } req := WorkspaceMoveRequest{RequestID: "c", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, diff --git a/seaweed-block/core/authority/workspace_regrant_storage_test.go b/seaweed-block/core/authority/workspace_regrant_storage_test.go index 2f5cf00411..1893c691f3 100644 --- a/seaweed-block/core/authority/workspace_regrant_storage_test.go +++ b/seaweed-block/core/authority/workspace_regrant_storage_test.go @@ -3,14 +3,13 @@ package authority import ( "bytes" "context" - "errors" - "reflect" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) type regrantStorageView struct{} @@ -22,33 +21,29 @@ func (regrantStorageView) Projection() frontend.Projection { // These component controls obtain the real authority re-grant before opening // the returning file-backed provider. They do not model a second live process. func TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut(t *testing.T) { - testWorkspaceRegrantStorage(t, false, false) + testWorkspaceRegrantStorage(t) } -func TestWorkspaceLeaseRegrantCannotUnsealSameEpoch(t *testing.T) { - testWorkspaceRegrantStorage(t, true, false) -} - -func TestWorkspaceLeaseRegrantEmptyRootClaimsOnlyHEAD(t *testing.T) { - testWorkspaceRegrantStorage(t, false, true) -} - -func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) { +// The B-layout equivalents of the removed legacy-only cases are +// TestLayoutPlainDetachLostReplyRestartReplaysProof and +// TestLayoutProviderRefusesEmptyOwnEpochAndRemountedOldRoot. +func testWorkspaceRegrantStorage(t *testing.T) { t.Helper() ctx := context.Background() disk, _ := newTempStore(t) clock := newTestClock() p := newLeasePublisher(t, disk, time.Second, clock) bindAndGrant(t, p, "v", "r") - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v", 64, 4) root := t.TempDir() open := func() *durable.DurableProvider { t.Helper() - provider, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, regrantStorageView{}) + } + fixture.Configure(&cfg) + provider, err := durable.NewDurableProvider(cfg, regrantStorageView{}) if err != nil { t.Fatal(err) } @@ -81,14 +76,9 @@ func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) { t.Fatal(err) } write(4096, b) // completed Sync, deliberately absent from the last HEAD - if sealed { - if _, _, err := first.DetachVolumePlain(ctx, "v"); err != nil { - t.Fatal(err) - } - } - before, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) + before, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found { + t.Fatalf("HEAD before regrant: found=%v err=%v", found, err) } if err := first.Close(); err != nil { t.Fatal(err) @@ -97,26 +87,8 @@ func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) { if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { t.Fatal("returning process could not obtain the authority re-grant", err) } - if fresh { - root = t.TempDir() - b = make([]byte, 4096) // the absent local log cannot be claimed as present - } second := open() _, err = second.RecoverVolume(ctx, "v") - if sealed { - after, readErr := remote.GetHead(ctx) - if !errors.Is(err, storage.ErrChunkLayerDetached) || readErr != nil || !reflect.DeepEqual(after, before) { - t.Fatal("same-epoch re-grant reactivated the seal", after, err, readErr) - } - blocked, openErr := second.Open(ctx, "v") - if openErr != nil { - t.Fatal(openErr) - } - if _, readErr := blocked.Read(ctx, 0, make([]byte, 4096)); !errors.Is(readErr, frontend.ErrNotReady) { - t.Fatal("sealed re-granted process exposed guest I/O", readErr) - } - return - } if err != nil { t.Fatal(err) } @@ -130,25 +102,31 @@ func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) { t.Fatal("return lost locally acknowledged bytes", i, err) } } - claimed, err := remote.GetHead(ctx) - if err != nil || claimed.Gen <= before.Gen || claimed.Epoch != 1 || claimed.Holder != before.Holder || claimed.RemoteLSN != before.RemoteLSN { - t.Fatal("return served without the new generation fence", claimed, err) + claimed, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found || claimed.Gen != before.Gen || claimed.Epoch != 1 || claimed.Holder != before.Holder || claimed.ClaimID != before.ClaimID || claimed.Position != before.Position { + t.Fatal("same-root return changed the B HEAD before the first cut", claimed, err) } if _, err := second.CaptureVolume(ctx, "v"); err != nil { t.Fatal(err) } - final, err := remote.GetHead(ctx) - if fresh { - if err != nil || !reflect.DeepEqual(final, claimed) { - t.Fatal("empty-root return published bytes/frontier absent from HEAD", final, err) - } - return - } - if err != nil || final.RemoteLSN <= before.RemoteLSN { + final, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found || final.Position <= before.Position { t.Fatal("first returning cut did not cover the local log", final, err) } - payload, err := remote.Get(ctx, final.Chunks[0].Key) - if err != nil || len(payload) < 8192 || !bytes.Equal(payload[:4096], a) || !bytes.Equal(payload[4096:8192], b) { + st, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + t.Fatal(err) + } + reader, err := layout.NewReader("/provider-test", fixture.Ref.Dir(), st.Fetch) + if err != nil || final.Current == nil { + t.Fatal("first cut has no B image", err) + } + image, err := reader.Open(ctx, *final.Current) + if err != nil { + t.Fatal(err) + } + chunk, err := image.Chunk(ctx, 0) + if err != nil || chunk.Zero || len(chunk.Data) < 8192 || !bytes.Equal(chunk.Data[:4096], a) || !bytes.Equal(chunk.Data[4096:8192], b) { t.Fatal("first cut did not publish the full acknowledged image", err) } } diff --git a/seaweed-block/core/authority/workspace_regrant_test.go b/seaweed-block/core/authority/workspace_regrant_test.go index c191bab314..3a562bb09e 100644 --- a/seaweed-block/core/authority/workspace_regrant_test.go +++ b/seaweed-block/core/authority/workspace_regrant_test.go @@ -191,7 +191,7 @@ func TestWorkspaceLeaseSealedAckNeverRegrants(t *testing.T) { if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { t.Fatal(err) } - if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err != nil { t.Fatal(err) } // ACK is the master's durable evidence for this holder's sealed generation. diff --git a/seaweed-block/core/authority/workspace_same_host_clean_test.go b/seaweed-block/core/authority/workspace_same_host_clean_test.go index 4473ebd22f..7bdfbf7319 100644 --- a/seaweed-block/core/authority/workspace_same_host_clean_test.go +++ b/seaweed-block/core/authority/workspace_same_host_clean_test.go @@ -6,7 +6,7 @@ import ( "time" ) -// INV-WS-SAME-HOST-CLEAN-MOVE-001: an unchanged sealed generation and its +// INV-WS-SAME-HOST-CLEAN-MOVE-001: an unchanged sealed image and its // durable ACK remain a clean-move proof after the lease expires overnight. func TestWorkspaceSameHostCleanMoveUsesOvernightSeal(t *testing.T) { disk, _ := newTempStore(t) @@ -22,25 +22,20 @@ func TestWorkspaceSameHostCleanMoveUsesOvernightSeal(t *testing.T) { if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { t.Fatal(err) } - if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err != nil { t.Fatal(err) } clock.at(86400) for _, bad := range []WorkspaceHead{ {Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42}, - {Gen: 8, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true}, + {Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 43, Detached: true}, {Gen: 7, Epoch: 1, Holder: "other/r", RemoteLSN: 42, Detached: true}, {Gen: 7, Epoch: 2, Holder: "host/r", RemoteLSN: 42, Detached: true}, } { if _, err := p.MoveWorkspace(ctx, req, bad); err == nil { - t.Fatal("same-host move bypassed sealed-generation proof", bad) + t.Fatal("same-host move bypassed sealed-image proof", bad) } } - forced := req - forced.Kind, forced.Force = "forced", true - if _, err := p.MoveWorkspace(ctx, forced, head); err == nil { - t.Fatal("same-host forced move accepted") - } if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 1 || len(p.WorkspaceState("v").Moves) != 0 { t.Fatal("refusal reserved or published authority", line) } diff --git a/seaweed-block/core/authority/workspace_same_host_forced_test.go b/seaweed-block/core/authority/workspace_same_host_forced_test.go new file mode 100644 index 0000000000..66cdad55d3 --- /dev/null +++ b/seaweed-block/core/authority/workspace_same_host_forced_test.go @@ -0,0 +1,50 @@ +package authority + +import ( + "context" + "testing" + "time" +) + +// A lost local image can rejoin on the same host only through a new epoch +// with the same lease barrier and durable loss record as a cross-host move. +func TestWorkspaceSameHostForcedMoveRecordsLostRange(t *testing.T) { + for _, restart := range []bool{false, true} { + t.Run(map[bool]string{false: "running", true: "reloaded"}[restart], func(t *testing.T) { + disk, _ := newTempStore(t) + p, now, barrier := forcedLostRangeFixture(t, disk, restart) + req := forcedLostRangeReq + req.TargetHost = req.ExpectedHost + *now = barrier.Add(-time.Nanosecond) + if p.PreviewWorkspaceForcedMove(req).Admitted { + t.Fatal("same-host preview bypassed the live lease barrier") + } + if _, err := p.MoveWorkspace(context.Background(), req, forcedLostRangeHead); err == nil { + t.Fatal("same-host forced move bypassed the live lease barrier") + } + if len(p.WorkspaceLostRanges("v")) != 0 || len(p.WorkspaceState("v").Moves) != 0 { + t.Fatal("refused move wrote a loss record or reservation") + } + *now = barrier.Add(time.Nanosecond) + if preview := p.PreviewWorkspaceForcedMove(req); !preview.Admitted { + t.Fatalf("same-host recovery preview refused after barrier: %s", preview.Reason) + } + grant, err := p.MoveWorkspace(context.Background(), req, forcedLostRangeHead) + if err != nil { + t.Fatal(err) + } + if !grant.Issued || grant.NewEpoch != 2 || grant.OldHost != grant.NewHost { + t.Fatalf("wrong same-host successor: %+v", grant) + } + want := WorkspaceLostRange{RequestID: req.RequestID, NewEpoch: 2, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano()} + for _, checked := range []*Publisher{p, NewPublisher(nil, WithStore(disk))} { + if got := checked.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want { + t.Fatalf("same-host recovery lost the durable loss report: %+v", got) + } + } + if replay, err := p.MoveWorkspace(context.Background(), req, WorkspaceHead{}); err != nil || replay != grant { + t.Fatalf("same-host replay changed grant: %+v %v", replay, err) + } + }) + } +} diff --git a/seaweed-block/core/authority/workspace_test.go b/seaweed-block/core/authority/workspace_test.go index cda50e45d1..bd494aa6cd 100644 --- a/seaweed-block/core/authority/workspace_test.go +++ b/seaweed-block/core/authority/workspace_test.go @@ -118,7 +118,7 @@ func TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck(t *testing.T) { if _, err := p.MoveWorkspace(ctx, req, head); err == nil { t.Fatal("clean without ack") } - if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}); err == nil { + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "", RemoteLSN: 0}); err == nil { t.Fatal("unsolicited ack accepted") } if err := p.BeginWorkspaceRevocation(ctx, "v", "old", 1); err != nil { @@ -128,7 +128,7 @@ func TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck(t *testing.T) { if err != nil || !lease.Revoking { t.Fatal("revocation not delivered", lease, err) } - if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}); err != nil { + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7, Holder: "old-node/old", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42}); err != nil { t.Fatal(err) } bad := head @@ -137,9 +137,9 @@ func TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck(t *testing.T) { t.Fatal("attached head accepted") } bad = head - bad.Gen++ + bad.RemoteLSN++ if _, err := p.MoveWorkspace(ctx, req, bad); err == nil { - t.Fatal("different generation accepted") + t.Fatal("different sealed position accepted") } r, err := p.MoveWorkspace(ctx, req, head) if err != nil || r.NewEpoch != 2 || !r.Issued { diff --git a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go index d57b36760e..3635d94ea2 100644 --- a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go +++ b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go @@ -40,7 +40,7 @@ func cleanMoveToGrantee(t *testing.T, store AuthorityStore, now *time.Time) (*Pu if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { t.Fatal(err) } - if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen}); err != nil { + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}, WorkspaceHead{Detached: true, Epoch: 1, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}); err != nil { t.Fatal(err) } *now = now.Add(100 * time.Millisecond) @@ -145,7 +145,7 @@ func TestWorkspaceUnclaimedGrantHEADRule(t *testing.T) { if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 2); err != nil { t.Fatal("revoke the grantee's issued lease:", err) } - if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 2, HeadGen: predecessorHead.Gen}); err != nil { + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 2, HeadGen: predecessorHead.Gen, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}, WorkspaceHead{Detached: true, Epoch: 2, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}); err != nil { t.Fatal(err) } clean := forcedFromGrantee("clean-2") diff --git a/seaweed-block/core/authority/workspace_validity_test.go b/seaweed-block/core/authority/workspace_validity_test.go index 96e8e74a47..c07443f731 100644 --- a/seaweed-block/core/authority/workspace_validity_test.go +++ b/seaweed-block/core/authority/workspace_validity_test.go @@ -49,7 +49,7 @@ func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) { } } now = start.Add(tc.elapsed) - err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}) + err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}) if (err == nil) != tc.allowed { t.Fatalf("ACK allowed=%t, want %t: %v", err == nil, tc.allowed, err) } diff --git a/seaweed-block/core/frontend/chunkstore/api.go b/seaweed-block/core/frontend/chunkstore/api.go index eae7dd0fd8..605b8437ce 100644 --- a/seaweed-block/core/frontend/chunkstore/api.go +++ b/seaweed-block/core/frontend/chunkstore/api.go @@ -1,23 +1,26 @@ package chunkstore -// The JSON bodies of a snapshot listing and a snapshot delete (B9 W2 §3.3, -// §3.4), shared by blockvolume's /chunk/* routes and the sw-block CLI, which -// reads the filer directly; and the body of `sw-block ops chunk show`. +// Snapshot listing and deletion bodies shared by blockvolume's /chunk/* +// routes and the sw-block CLI. -import "github.com/seaweedfs/seaweed-block/core/storage" +import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" -// SnapshotListItem is one listed snapshot, exactly §3.3's fields. +// SnapshotListItem is one listed snapshot. type SnapshotListItem struct { - Name string `json:"name"` - HeadGen uint64 `json:"headGen"` - HeadEpoch uint64 `json:"headEpoch"` - CutLSN uint64 `json:"cutLSN"` - CreatedNs int64 `json:"createdNs"` - State string `json:"state"` - ChunkCount int `json:"chunkCount"` - Labels map[string]string `json:"labels"` - Consistency string `json:"consistency"` - Parent *Parent `json:"parent"` + Class string `json:"class,omitempty"` + ExpiresAtNs int64 `json:"expiresAtNs,omitempty"` + Root string `json:"root,omitempty"` + Dependents []layout.Dependent `json:"dependents,omitempty"` + Name string `json:"name"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + CutLSN uint64 `json:"cutLSN"` + CreatedNs int64 `json:"createdNs"` + State string `json:"state"` + ChunkCount int `json:"chunkCount"` + Labels map[string]string `json:"labels"` + Consistency string `json:"consistency"` + Parent *Parent `json:"parent"` } // SnapshotListBody is a listing page: the snapshots after the request's @@ -32,7 +35,7 @@ type SnapshotListBody struct { func NewSnapshotListBody(vol string, list []SnapshotInfo, next string) SnapshotListBody { body := SnapshotListBody{VolumeID: vol, Snapshots: make([]SnapshotListItem, 0, len(list)), Next: next} for _, s := range list { - body.Snapshots = append(body.Snapshots, SnapshotListItem{Name: s.Name, HeadGen: s.HeadGen, HeadEpoch: s.HeadEpoch, + body.Snapshots = append(body.Snapshots, SnapshotListItem{Name: s.Name, Root: s.Root, Dependents: s.Dependents, Class: s.Class, ExpiresAtNs: s.ExpiresAtNs, HeadGen: s.HeadGen, HeadEpoch: s.HeadEpoch, CutLSN: s.CutLSN, CreatedNs: s.CreatedNs, State: s.State, ChunkCount: s.ChunkCount, Labels: s.Labels, Consistency: s.Consistency, Parent: s.Parent}) } @@ -45,59 +48,3 @@ type SnapshotDeleteBody struct { Name string `json:"name"` State string `json:"state"` } - -// VolumeShowBody is one volume's VOLUME entry and HEAD (sw-block ops chunk -// show); each is null when it does not exist. -type VolumeShowBody struct { - VolumeID string `json:"volumeID"` - Volume *VolumeShow `json:"volume"` - Head *HeadShow `json:"head"` -} - -// VolumeShow is the VOLUME entry (§4.2). -type VolumeShow struct { - Origin string `json:"origin"` - NumBlocks uint64 `json:"numBlocks"` - BlockSize uint32 `json:"blockSize"` - ChunkBlocks uint32 `json:"chunkBlocks"` - CreatedNs int64 `json:"createdNs"` - Parent *Parent `json:"parent"` -} - -// HeadShow is the HEAD; a HEAD without a state is active. -type HeadShow struct { - Gen uint64 `json:"gen"` - Epoch uint64 `json:"epoch"` - Holder string `json:"holder"` - RemoteLSN uint64 `json:"remoteLSN"` - State string `json:"state"` - DetachedBy *DetachedByShow `json:"detachedBy"` - ChunkCount int `json:"chunkCount"` -} - -// DetachedByShow is the detach proof in a detached HEAD. -type DetachedByShow struct { - Holder string `json:"holder"` - Epoch uint64 `json:"epoch"` - Gen uint64 `json:"gen"` -} - -// NewVolumeShowBody is vol's show body from what exists. -func NewVolumeShowBody(vol string, v *VolumeInfo, h *storage.ChunkHead) VolumeShowBody { - body := VolumeShowBody{VolumeID: vol} - if v != nil { - body.Volume = &VolumeShow{Origin: v.Origin, NumBlocks: v.NumBlocks, BlockSize: v.BlockSize, ChunkBlocks: v.ChunkBlocks, - CreatedNs: v.CreatedNs, Parent: v.Parent} - } - if h != nil { - state := h.State - if state == "" { - state = storage.ChunkHeadActive - } - body.Head = &HeadShow{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: state, ChunkCount: manifestCount(*h)} - if d := h.DetachedBy; d != nil { - body.Head.DetachedBy = &DetachedByShow{Holder: d.Holder, Epoch: d.Epoch, Gen: d.Gen} - } - } - return body -} diff --git a/seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go b/seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go deleted file mode 100644 index 95a762361b..0000000000 --- a/seaweed-block/core/frontend/chunkstore/attach_lookup_error_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -type attachLookupProjection struct{} - -func (attachLookupProjection) Projection() frontend.Projection { - return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true} -} - -// Attach lookup errors fail closed; INV-WS-CLAIM-BEFORE-SERVE-001. -// Real gRPC lookup errors pass through SWFS and a fresh durable provider. -// An existing HEAD must never become a bootstrap claim or an I/O-ready volume. -func TestAttachLookupUnavailableIsNotAnAbsentHead(t *testing.T) { - for _, code := range []codes.Code{codes.Unavailable, codes.DeadlineExceeded, codes.PermissionDenied, codes.Internal} { - t.Run(code.String(), func(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - head := storage.ChunkHead{Gen: 7, Epoch: 3, Holder: "node/r1", State: storage.ChunkHeadActive} - entry, err := headEntry(head) - if err != nil { - t.Fatal(err) - } - f := &fakeFilerGRPC{lookupResp: &filerpb.LookupDirectoryEntryResponse{Entry: entry}} - swfs := startFakeFiler(t, f) - remote, err := NewChunkRemote(swfs, newFakeBlobs(), "/chunks/v1") - if err != nil { - t.Fatal(err) - } - before, err := remote.GetHead(ctx) - if err != nil || before.Gen != 7 { - t.Fatalf("pre-existing HEAD=%+v error=%v", before, err) - } - f.mu.Lock() - // The absence sentinel inside an Unavailable message is still an error. - f.lookupErr = status.Error(code, "lookup failed: "+filerNotFoundText) - f.mu.Unlock() - if h, err := remote.GetHead(ctx); err == nil || errors.Is(err, ErrNotFound) || status.Code(err) != code || !strings.Contains(err.Error(), "lookup failed: "+filerNotFoundText) { - t.Fatalf("failed lookup became an absent HEAD: head=%+v error=%v", h, err) - } - p, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16, - ChunkHolder: "node/r1", - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, attachLookupProjection{}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = p.Close() }) - if _, err := p.EnsureStorage("v1"); err != nil { - t.Fatal(err) - } - if _, err := p.RecoverVolume(ctx, "v1"); status.Code(err) != code || !strings.Contains(err.Error(), "lookup failed: "+filerNotFoundText) { - t.Fatalf("attach error=%v; want preserved %s", err, code) - } - if err := p.AdmitsIO("v1"); err == nil { - t.Fatal("failed HEAD lookup admitted guest I/O") - } - f.mu.Lock() - created, updated := f.lastCreate, f.lastUpdate - f.lookupErr = nil - f.mu.Unlock() - if created != nil || updated != nil { - t.Fatalf("failed lookup attempted a HEAD CAS: create=%+v update=%+v", created, updated) - } - after, err := remote.GetHead(ctx) - if err != nil || after.Gen != head.Gen || after.Holder != head.Holder || after.Epoch != head.Epoch { - t.Fatalf("failed attach changed HEAD: %+v error=%v", after, err) - } - }) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go deleted file mode 100644 index 8c60e8bff6..0000000000 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ /dev/null @@ -1,1498 +0,0 @@ -package chunkstore - -// Catalog: the chunk control plane's filer metadata and Fork (B9 W2 spec -// §3-§5). Under the chunk base directory, per volume: -// -// //HEAD the published HEAD (ChunkRemote) -// //keys/ chunk key bindings (ChunkRemote) -// //intents/ live intents (ChunkRemote; GC roots) -// //VOLUME identity, geometry and lineage; write-once -// //snaps/ snapshots: a full copy of one HEAD document -// -// No entry carries filer chunks (UpdateEntry would delete chunks a new -// entry drops); every entry carries swb.kind and is checked on read, and an -// entry that does not check out is an error, never "absent". -// -// Snapshot and fork are read-then-write. Each writes an intent naming the -// keys it references before its final manifest write, and refuses that -// write once OpDeadline has passed since it read its source (spec §2.3). -// The operation's intents are removed only once its outcome is settled: the -// manifest is confirmed published (re-read shows it), or the attempt -// cleanly aborted (it never sent the write, or another entry already holds -// the name, so its exclusive create can never land). An uncertain outcome -// keeps them and reports outcome_unknown; a retry with the same request id -// settles it and removes every intent of the operation. - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "path" - "strconv" - "strings" - "time" - - "github.com/seaweedfs/seaweed-block/core/geometry" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -const ( - kindChunkVolume = "chunkvolume" - kindChunkSnap = "chunksnap" - - volumeName = "VOLUME" - snapsDir = "snaps" - // snapNamesDir holds one name record per snapshot name: the request and - // the attempt that own the name (W5). - snapNamesDir = "snapnames" - kindSnapName = "chunksnapname" - - extReq = "swb.req" - extAttempt = "swb.attempt" // the id of the intent of the attempt that wrote the entry - extSnapGen = "swb.snap.gen" - extSnapEpoch = "swb.snap.epoch" - extSnapLSN = "swb.snap.lsn" - extSnapState = "swb.snap.state" - extSnapDeletedNs = "swb.snap.deleted_ns" - - volumeFormat = 1 - snapFormat = 1 - - // SnapActive and SnapDeleting are a snapshot's states. - SnapActive = "active" - SnapDeleting = "deleting" - // SnapAbsent is DeleteSnapshot's answer for a snapshot that is not there. - SnapAbsent = "absent" - - // OriginCreate, OriginFork and OriginRestore are a volume's origins. A - // restore is a fork whose volume later becomes independent of its source - // (own chunks, restoreIndependentName written); until then it is a fork. - OriginCreate = "create" - OriginFork = "fork" - OriginRestore = "restore" - - // DefaultOpDeadline bounds a snapshot or fork from reading its source to - // its final write (spec §2.3). - DefaultOpDeadline = 5 * time.Minute - - defaultListLimit = 100 - maxListLimit = 1000 - maxLabels = 32 - maxLabelKey = 64 - maxLabelValue = 256 - maxSnapName = 128 -) - -// Error codes of the control plane (spec §2.2), as the HTTP API and the CLI -// report them. -const ( - CodeNotChunkVolume = "not_chunk_volume" - CodeInvalidName = "invalid_name" - CodeSnapshotExists = "snapshot_exists" - CodeSnapshotNotFound = "snapshot_not_found" - CodeSnapshotDeleting = "snapshot_deleting" - CodeTargetExists = "target_exists" - CodeGeometryMismatch = "geometry_mismatch" - CodeForkIncomplete = "fork_incomplete" - CodeDeadlineExceeded = "deadline_exceeded" - CodeRemoteUnavailable = "remote_unavailable" - CodeOutcomeUnknown = "outcome_unknown" - CodeInvalidLabel = "invalid_label" -) - -// CatalogError is a typed control-plane failure. -type CatalogError struct { - Code string - Message string - Retryable bool - Err error -} - -func (e *CatalogError) Error() string { - if e.Err != nil { - return fmt.Sprintf("chunkstore: %s: %s: %v", e.Code, e.Message, e.Err) - } - return fmt.Sprintf("chunkstore: %s: %s", e.Code, e.Message) -} - -func (e *CatalogError) Unwrap() error { return e.Err } - -// Detail is the error without its code: the message, and the cause if any -// (an error body carries the code in its own field). -func (e *CatalogError) Detail() string { - if e.Err != nil { - return fmt.Sprintf("%s: %v", e.Message, e.Err) - } - return e.Message -} - -// CodeOf returns the control-plane code of err, or "" when it has none. -func CodeOf(err error) string { - var ce *CatalogError - if errors.As(err, &ce) { - return ce.Code - } - return "" -} - -func catErr(code string, retryable bool, err error, format string, a ...any) error { - return &CatalogError{Code: code, Message: fmt.Sprintf(format, a...), Retryable: retryable, Err: err} -} - -// remoteErr wraps a filer failure as remote_unavailable, keeping the cause. -func remoteErr(err error, format string, a ...any) error { - return catErr(CodeRemoteUnavailable, true, err, format, a...) -} - -// Geometry is a volume's shape; a chunk index means nothing without it. -type Geometry struct { - NumBlocks uint64 `json:"num_blocks"` - BlockSize uint32 `json:"block_size"` - ChunkBlocks uint32 `json:"chunk_blocks"` -} - -// Parent is a forked volume's source. -type Parent struct { - VolumeID string `json:"volume_id"` - Snapshot string `json:"snapshot"` - Gen uint64 `json:"gen"` -} - -// VolumeInfo is the VOLUME entry (spec §4.2). -type VolumeInfo struct { - Format int `json:"format"` - VolumeID string `json:"volume_id"` - Geometry - Origin string `json:"origin"` - CreatedNs int64 `json:"created_ns"` - Parent *Parent `json:"parent"` - // Fork records the fork operation that made this volume (origin fork): - // a retry is bound to it, and a completed fork replays it. - Fork *ForkRecord `json:"fork,omitempty"` - // State is VolumeDeleted for a deleted volume, read from the entry's - // extended attributes (never from the stored document). - State string `json:"state,omitempty"` -} - -// ForkRecord is the operation identity and original result of a fork. -type ForkRecord struct { - RequestID string `json:"request_id"` - Source string `json:"source"` - Snapshot string `json:"snapshot"` - SourceGen uint64 `json:"source_gen"` - HeadSHA256 string `json:"head_sha256"` // SHA-256 of the snapshot's HEAD document - RemoteLSN uint64 `json:"remote_lsn"` - ChunkCount int `json:"chunk_count"` - QualifiedRefs int `json:"qualified_refs"` -} - -type snapDoc struct { - Format int `json:"format"` - VolumeID string `json:"volume_id"` - Name string `json:"name"` - RequestID string `json:"request_id"` - CreatedNs int64 `json:"created_ns"` - CreatedBy string `json:"created_by"` - Consistency string `json:"consistency"` - Head json.RawMessage `json:"head"` - Geometry Geometry `json:"geometry"` - Parent *Parent `json:"parent"` - Labels map[string]string `json:"labels"` - ExpiresAtNs int64 `json:"expires_at_ns"` - // Class is the retention class: "semantic", "pinned", or "" for a - // snapshot made before classes existed (see retention.go). - Class string `json:"class,omitempty"` -} - -// SnapshotInfo describes one snapshot, with the field names of the HTTP API -// (spec §3.2-§3.3). -type SnapshotInfo struct { - VolumeID string `json:"volumeID"` - Name string `json:"name"` - HeadGen uint64 `json:"headGen"` - HeadEpoch uint64 `json:"headEpoch"` - CutLSN uint64 `json:"cutLSN"` - CreatedNs int64 `json:"createdNs"` - State string `json:"state"` - ChunkCount int `json:"chunkCount"` - ManifestBytes int `json:"manifestBytes"` - Consistency string `json:"consistency"` - Labels map[string]string `json:"labels"` - Parent *Parent `json:"parent"` - ExpiresAtNs int64 `json:"expiresAtNs"` - Replayed bool `json:"replayed"` - Class string `json:"class"` - - attempt string // the attempt the name resolved to, when read by name - - head storage.ChunkHead - geo Geometry - digest string // identity uses the embedded writer version, not today's serializer -} - -// Head returns the HEAD the snapshot copied. -func (s SnapshotInfo) Head() storage.ChunkHead { return s.head } - -// SnapshotRequest names a snapshot of the HEAD a cut installed. -type SnapshotRequest struct { - Name string - RequestID string // required; a retry with the same id replays - Labels map[string]string - Consistency string // "crash" (default) or "app" - ExpiresAtNs int64 - CreatedBy string - // Class is the retention class: "semantic" or "pinned" ("" leaves it - // unset, which retention treats as unpinned). - Class string - // SourceReadAt is when the caller obtained the HEAD it snapshots (the - // cut's return); OpDeadline counts from it. Zero means now. - SourceReadAt time.Time - // ShareToken is the ShareGuard token of a caller that began the share - // before it obtained the HEAD (the owner's seal: Begin, then the cut). - // Empty: CreateSnapshot begins the share itself and refuses a HEAD that - // is no longer current. Unused without a guard; never stored. - ShareToken string -} - -// ListOptions pages a snapshot listing. -type ListOptions struct { - Prefix string - StartAfter string - Limit int - IncludeDeleting bool -} - -// ForkRequest makes a new volume from a snapshot. -type ForkRequest struct { - Source string - Snapshot string - Target string - RequestID string // required; a retry with the same id replays - Labels map[string]string -} - -// ForkResult reports a fork, with the field names of the CLI output -// (spec §3.5). -type ForkResult struct { - Target string `json:"target"` - Source string `json:"source"` - Snapshot string `json:"snapshot"` - SourceGen uint64 `json:"sourceGen"` - HeadGen uint64 `json:"headGen"` - HeadEpoch uint64 `json:"headEpoch"` - RemoteLSN uint64 `json:"remoteLSN"` - ChunkCount int `json:"chunkCount"` - QualifiedRefs int `json:"qualifiedRefs"` - Replayed bool `json:"replayed"` -} - -// Catalog reads and writes the control-plane entries under one chunk base. -type Catalog struct { - blobs Blobs // optional immutable-object reader; SWFS supplies it directly - f Filer - base string - // OpDeadline bounds a snapshot or fork (DefaultOpDeadline when zero). - OpDeadline time.Duration - now func() time.Time - // retainHook, when set, runs at the named stages of a Retain pass (a - // test seam for interleavings; see hookPlanned). - retainHook func(stage, name string) - // guard, when set, is told about every share of a volume's chunks. - guard ShareGuard -} - -// NewCatalog returns the catalog for the chunk base directory base (the -// blockvolume --chunk-path), a clean absolute directory other than /. -func NewCatalog(f Filer, base string) (*Catalog, error) { - if f == nil { - return nil, errors.New("chunkstore: catalog needs a filer") - } - if !path.IsAbs(base) || path.Clean(base) != base || base == "/" { - return nil, fmt.Errorf("chunkstore: chunk base %q must be a clean absolute directory other than /", base) - } - blobs, _ := f.(Blobs) - return &Catalog{f: f, blobs: blobs, base: base, now: time.Now}, nil -} - -// SetClock replaces the catalog's clock (tests). -func (c *Catalog) SetClock(now func() time.Time) { c.now = now } - -func (c *Catalog) deadline() time.Duration { - if c.OpDeadline > 0 { - return c.OpDeadline - } - return DefaultOpDeadline -} - -func (c *Catalog) volRoot(vol string) (string, error) { - if err := CheckVolumeID(vol); err != nil { - return "", catErr(CodeInvalidName, false, err, "volume %q", vol) - } - return path.Join(c.base, vol), nil -} - -// CheckSnapshotName enforces the snapshot name rule (spec §4.4). -func CheckSnapshotName(name string) error { - if name == "" || len(name) > maxSnapName || strings.HasPrefix(name, ".") { - return catErr(CodeInvalidName, false, nil, "snapshot name %q: 1-%d characters, not starting with '.'", name, maxSnapName) - } - switch name { - case headName, volumeName, keysDir, snapsDir, snapNamesDir, intentsDir: - return catErr(CodeInvalidName, false, nil, "snapshot name %q is reserved", name) - } - for _, r := range name { - if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '.' || r == '_' || r == '-') { - return catErr(CodeInvalidName, false, nil, "snapshot name %q: only [A-Za-z0-9._-]", name) - } - } - return nil -} - -func checkLabels(labels map[string]string) error { - if len(labels) > maxLabels { - return catErr(CodeInvalidLabel, false, nil, "%d labels, at most %d", len(labels), maxLabels) - } - for k, v := range labels { - if k == "" || len(k) > maxLabelKey || len(v) > maxLabelValue { - return catErr(CodeInvalidLabel, false, nil, "label %q: key 1-%d characters, value at most %d bytes", k, maxLabelKey, maxLabelValue) - } - for _, r := range k { - if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '.' || r == '_' || r == '-') { - return catErr(CodeInvalidLabel, false, nil, "label key %q: only [a-z0-9._-]", k) - } - } - } - return nil -} - -// ---- VOLUME ---- - -func volumeEntry(v VolumeInfo, req string) (*filerpb.Entry, error) { - body, err := json.Marshal(v) - if err != nil { - return nil, err - } - now := time.Now().Unix() - ext := map[string][]byte{extKind: []byte(kindChunkVolume)} - if req != "" { - ext[extReq] = []byte(req) - } - return &filerpb.Entry{ - Name: volumeName, - Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"}, - Extended: ext, - Content: body, - }, nil -} - -func decodeVolume(p string, e *filerpb.Entry) (VolumeInfo, error) { - if len(e.GetChunks()) != 0 { - return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s carries %d filer chunks", p, len(e.Chunks)) - } - if k := string(e.Extended[extKind]); k != kindChunkVolume { - return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: kind %q, want %q", p, k, kindChunkVolume) - } - var v VolumeInfo - if err := json.Unmarshal(e.GetContent(), &v); err != nil { - return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: decode: %v", p, err) - } - if v.Format != volumeFormat { - return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: format %d not supported", p, v.Format) - } - if v.Origin != OriginCreate && v.Origin != OriginFork && v.Origin != OriginRestore { - return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: origin %q", p, v.Origin) - } - if isForked(v.Origin) && (v.Fork == nil || v.Fork.RequestID == "") { - return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: a fork without its fork record", p) - } - v.State = string(e.Extended[extVolState]) - return v, nil -} - -// ReadVolume returns the VOLUME entry; ok is false when it does not exist. -func (c *Catalog) ReadVolume(ctx context.Context, vol string) (VolumeInfo, bool, error) { - root, err := c.volRoot(vol) - if err != nil { - return VolumeInfo{}, false, err - } - e, err := c.f.LookupEntry(ctx, root, volumeName) - if errors.Is(err, ErrNotFound) { - return VolumeInfo{}, false, nil - } - if err != nil { - return VolumeInfo{}, false, remoteErr(err, "read VOLUME of %s", vol) - } - v, err := decodeVolume(path.Join(root, volumeName), e) - if err != nil { - return VolumeInfo{}, false, err - } - return v, true, nil -} - -func (c *Catalog) headExists(ctx context.Context, root string) (bool, error) { - _, err := c.f.LookupEntry(ctx, root, headName) - if errors.Is(err, ErrNotFound) { - return false, nil - } - if err != nil { - return false, err - } - return true, nil -} - -// ensureInitialHead creates vol's initial empty HEAD unless a HEAD exists. -func (c *Catalog) ensureInitialHead(ctx context.Context, vol, root string) error { - has, err := c.headExists(ctx, root) - if err != nil { - return remoteErr(err, "read HEAD of %s", vol) - } - if has { - return nil - } - he, err := headEntry(storage.ChunkHead{Gen: 1, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadActive}) - if err != nil { - return err - } - if err := c.f.CreateEntry(ctx, root, he, true); err != nil && !errors.Is(err, ErrExists) { - return remoteErr(err, "create the initial HEAD of %s", vol) - } - return nil -} - -// ReadHead returns vol's HEAD, and false when no HEAD was ever published. -func (c *Catalog) ReadHead(ctx context.Context, vol string) (storage.ChunkHead, bool, error) { - root, err := c.volRoot(vol) - if err != nil { - return storage.ChunkHead{}, false, err - } - e, err := c.f.LookupEntry(ctx, root, headName) - if errors.Is(err, ErrNotFound) { - return storage.ChunkHead{}, false, nil - } - if err != nil { - return storage.ChunkHead{}, false, remoteErr(err, "read HEAD of %s", vol) - } - h, err := decodeHead(path.Join(root, headName), e) - if err != nil { - return storage.ChunkHead{}, false, err - } - return h, true, nil -} - -// EnsureVolume applies the attach rules of spec §4.2 for a volume served -// with geometry g: it creates a missing VOLUME entry (origin create), and -// refuses with geometry_mismatch when VOLUME disagrees with g, or with -// fork_incomplete when VOLUME is a fork whose HEAD is not written yet. -func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (VolumeInfo, error) { - root, err := c.volRoot(vol) - if err != nil { - return VolumeInfo{}, err - } - v, ok, err := c.ReadVolume(ctx, vol) - if err != nil { - return VolumeInfo{}, err - } - if !ok { - if g.BlockSize != 0 && g.NumBlocks > geometry.MaxVolumeBytes/uint64(g.BlockSize) { - return VolumeInfo{}, catErr(CodeGeometryMismatch, false, nil, "volume size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) - } - v = VolumeInfo{Format: volumeFormat, VolumeID: vol, Geometry: g, Origin: OriginCreate, CreatedNs: c.now().UnixNano()} - e, err := volumeEntry(v, "") - if err != nil { - return VolumeInfo{}, err - } - if err := c.f.CreateEntry(ctx, root, e, true); err != nil { - if !errors.Is(err, ErrExists) { - return VolumeInfo{}, remoteErr(err, "create VOLUME of %s", vol) - } - // Another writer created it first: check theirs. - if v, ok, err = c.ReadVolume(ctx, vol); err != nil || !ok { - return VolumeInfo{}, remoteErr(err, "re-read VOLUME of %s", vol) - } - } - } - if v.State == VolumeDeleted { - return VolumeInfo{}, refuseDeleted(vol, "it cannot be attached or created again") - } - if h, has, err := c.ReadHead(ctx, vol); err != nil { - return VolumeInfo{}, err - } else if has && headDeletingOrDeleted(h) { - return VolumeInfo{}, refuseDeleted(vol, "it cannot be attached") - } - if v.Geometry != g { - return VolumeInfo{}, catErr(CodeGeometryMismatch, false, nil, "volume %s: VOLUME geometry %+v, this host serves %+v", vol, v.Geometry, g) - } - if v.Origin == OriginCreate { - // A created volume gets its initial HEAD with VOLUME (integration - // ruling F1): gen 1, epoch 0, no holder, remote_lsn 0, no chunks - // (all zero). An exclusive create: an existing HEAD (a volume made - // before VOLUME entries, or an earlier attach) is kept. - if err := c.ensureInitialHead(ctx, vol, root); err != nil { - return VolumeInfo{}, err - } - } - if isForked(v.Origin) { - // One read of HEAD decides both: absent and aborted never attach. - // A restore reads only its own HEAD here, never its source: a source - // deleted meanwhile is a normal state, not a mismatch. - h, has, err := c.ReadHead(ctx, vol) - switch { - case err != nil: - return VolumeInfo{}, err - case !has: - return VolumeInfo{}, catErr(CodeForkIncomplete, false, nil, "volume %s is a fork whose HEAD is not written yet", vol) - case h.State == storage.ChunkHeadAborted: - return VolumeInfo{}, catErr(CodeForkIncomplete, false, nil, "volume %s: its fork was aborted (HEAD is a tombstone); it never attaches", vol) - } - } - return v, nil -} - -// ---- snapshots ---- -// -// A snapshot name is owned by a name record snapnames/ {request, -// attempt}, created exclusively; the snapshot itself is published by an -// exclusive create at the attempt's own path snaps//, which -// is never removed (W5). A GC sweep settles a -// dead attempt by claiming its path with an aborted tombstone; a retry of -// the same request publishes to the same attempt path. DeleteSnapshot -// marks the attempt deleting and removes the name record, freeing the name. - -// SnapAborted marks an attempt path a GC sweep claimed for a dead attempt. -const SnapAborted = "aborted" - -type nameRecord struct { - Format int `json:"format"` - VolumeID string `json:"volume_id"` - Name string `json:"name"` - RequestID string `json:"request_id"` - Attempt string `json:"attempt"` - CreatedNs int64 `json:"created_ns"` -} - -func nameRecordEntry(rec nameRecord) (*filerpb.Entry, error) { - body, err := json.Marshal(rec) - if err != nil { - return nil, err - } - now := time.Now().Unix() - return &filerpb.Entry{ - Name: rec.Name, - Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"}, - Extended: map[string][]byte{extKind: []byte(kindSnapName), extReq: []byte(rec.RequestID), extAttempt: []byte(rec.Attempt)}, - Content: body, - }, nil -} - -func decodeNameRecord(p string, e *filerpb.Entry) (nameRecord, error) { - var rec nameRecord - if k := string(e.Extended[extKind]); k != kindSnapName { - return rec, fmt.Errorf("chunkstore: snapshot name %s: kind %q, want %q", p, k, kindSnapName) - } - if err := json.Unmarshal(e.GetContent(), &rec); err != nil { - return rec, fmt.Errorf("chunkstore: snapshot name %s: decode: %v", p, err) - } - if rec.Format != snapFormat || rec.Attempt == "" || rec.RequestID == "" || - string(e.Extended[extAttempt]) != rec.Attempt || string(e.Extended[extReq]) != rec.RequestID { - return rec, fmt.Errorf("chunkstore: snapshot name %s: malformed record", p) - } - return rec, nil -} - -// snapRef is a name resolved through its record: the record, and the -// attempt's entry when it exists (nil: the attempt has not published). -type snapRef struct { - rec nameRecord - entry *filerpb.Entry - info SnapshotInfo -} - -// resolveSnap reads snapnames/ and the attempt it names. ok is false -// when no record holds the name. -func (c *Catalog) resolveSnap(ctx context.Context, vol, name string) (snapRef, bool, error) { - root, err := c.volRoot(vol) - if err != nil { - return snapRef{}, false, err - } - re, err := c.f.LookupEntry(ctx, path.Join(root, snapNamesDir), name) - if errors.Is(err, ErrNotFound) { - return snapRef{}, false, nil - } - if err != nil { - return snapRef{}, false, remoteErr(err, "read snapshot name %s/%s", vol, name) - } - rec, err := decodeNameRecord(path.Join(root, snapNamesDir, name), re) - if err != nil { - return snapRef{}, false, err - } - ref := snapRef{rec: rec} - dir := path.Join(root, snapsDir, name) - e, err := c.f.LookupEntry(ctx, dir, rec.Attempt) - switch { - case errors.Is(err, ErrNotFound): - return ref, true, nil // the attempt has not published (in flight, or dead) - case err != nil: - return snapRef{}, false, remoteErr(err, "read snapshot %s/%s", vol, name) - } - info, _, err := decodeSnap(path.Join(dir, rec.Attempt), e) - if err != nil { - return snapRef{}, false, err - } - info.attempt = rec.Attempt - ref.entry, ref.info = e, info - return ref, true, nil -} - -// readSnap returns the published, not aborted snapshot named name, or -// snapshot_not_found. -func (c *Catalog) readSnap(ctx context.Context, vol, name string) (SnapshotInfo, error) { - ref, ok, err := c.resolveSnap(ctx, vol, name) - if err != nil { - return SnapshotInfo{}, err - } - if !ok || ref.entry == nil || ref.info.State == SnapAborted { - return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", vol, name) - } - return ref.info, nil -} - -func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { - fail := func(format string, a ...any) (SnapshotInfo, string, error) { - return SnapshotInfo{}, "", fmt.Errorf("chunkstore: snapshot %s: "+format, append([]any{p}, a...)...) - } - if len(e.GetChunks()) != 0 { - return fail("carries %d filer chunks; refusing", len(e.Chunks)) - } - if k := string(e.Extended[extKind]); k != kindChunkSnap { - return fail("kind %q, want %q", k, kindChunkSnap) - } - var doc snapDoc - if err := json.Unmarshal(e.GetContent(), &doc); err != nil { - return fail("decode: %v", err) - } - if doc.Format != snapFormat { - return fail("format %d not supported", doc.Format) - } - if string(e.Extended[extSnapState]) == SnapAborted { - return SnapshotInfo{VolumeID: doc.VolumeID, Name: doc.Name, CreatedNs: doc.CreatedNs, State: SnapAborted}, "", nil - } - head, err := decodeHeadDoc(p+"#head", doc.Head) - if err != nil { - return fail("%v", err) - } - digest, err := snapshotHeadDigest(head, doc.Head) - if err != nil { - return fail("HEAD identity: %v", err) - } - state := string(e.Extended[extSnapState]) - if state != SnapActive && state != SnapDeleting { - return fail("state %q", state) - } - if string(e.Extended[extSnapGen]) != strconv.FormatUint(head.Gen, 10) { - return fail("extended gen %q disagrees with the document's HEAD gen %d", e.Extended[extSnapGen], head.Gen) - } - return SnapshotInfo{ - VolumeID: doc.VolumeID, Name: doc.Name, HeadGen: head.Gen, HeadEpoch: head.Epoch, CutLSN: head.RemoteLSN, - CreatedNs: doc.CreatedNs, State: state, ChunkCount: manifestCount(head), ManifestBytes: len(e.GetContent()), - Consistency: doc.Consistency, Labels: doc.Labels, Parent: doc.Parent, ExpiresAtNs: doc.ExpiresAtNs, - Class: doc.Class, head: head, geo: doc.Geometry, digest: digest, - }, doc.RequestID, nil -} - -// abortedSnapEntry is the tombstone a sweep writes at an attempt path. -func (c *Catalog) abortedSnapEntry(vol, name, attempt string) (*filerpb.Entry, error) { - body, err := json.Marshal(snapDoc{Format: snapFormat, VolumeID: vol, Name: name, CreatedNs: c.now().UnixNano()}) - if err != nil { - return nil, err - } - now := time.Now().Unix() - return &filerpb.Entry{ - Name: attempt, - Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"}, - Extended: map[string][]byte{extKind: []byte(kindChunkSnap), extSnapState: []byte(SnapAborted)}, - Content: body, - }, nil -} - -// AbortSnapshot settles a dead snapshot attempt for a GC sweep (W5): it -// claims the attempt path snaps// -// with an exclusive create of an aborted tombstone. claimed is true when -// the path holds a tombstone (this one or an earlier one): the attempt can -// never publish. false: the attempt published, and its keys are reachable -// through that snapshot. Either way its copy intent can then be deleted. -// The attempt is the one in the intent's holder "snapshot://". -func (c *Catalog) AbortSnapshot(ctx context.Context, vol, name, attempt string) (claimed bool, err error) { - root, err := c.volRoot(vol) - if err != nil { - return false, err - } - if err := CheckSnapshotName(name); err != nil { - return false, err - } - if !storage.ValidChunkIntentID(attempt) { - return false, catErr(CodeInvalidName, false, nil, "attempt %q", attempt) - } - e, err := c.abortedSnapEntry(vol, name, attempt) - if err != nil { - return false, err - } - dir := path.Join(root, snapsDir, name) - switch err := c.f.CreateEntry(ctx, dir, e, true); { - case err == nil: - return true, nil - case !errors.Is(err, ErrExists): - return false, remoteErr(err, "aborted tombstone %s/%s/%s", vol, name, attempt) - } - got, err := c.f.LookupEntry(ctx, dir, attempt) - if err != nil { - return false, remoteErr(err, "read %s/%s/%s", vol, name, attempt) - } - return string(got.Extended[extSnapState]) == SnapAborted, nil -} - -// dropIntent deletes one attempt's own intent, once that attempt's create -// is confirmed or can never apply. It never touches another attempt's -// intent, even under the same operation: an earlier attempt's create may -// still be held by the server and land later (W5 rule). A failed delete -// leaves the intent, which only over-protects. The delete outlives the -// caller's cancellation (cleanup after a refused or cancelled request) but is -// bounded by dropIntentTimeout, so it can never hang on an unresponsive filer. -func (c *Catalog) dropIntent(ctx context.Context, root, id string) { - dctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dropIntentTimeout) - defer cancel() - _ = c.f.DeleteEntry(dctx, path.Join(root, intentsDir), id, nil) -} - -// dropIntentTimeout bounds one intent delete (a var so tests can shorten it). -var dropIntentTimeout = 30 * time.Second - -type createOutcome int - -const ( - createdNow createOutcome = iota // this attempt's create applied (confirmed) - createRefused // the filer refused it (the name exists): it will never apply - createUnsettled // no answer: it may still apply, even later -) - -// publishCtx bounds a publishing create by the operation's deadline -// (catalog clock), so the RPC cannot outlive the deadline its intent -// records (W5). -func (c *Catalog) publishCtx(ctx context.Context, deadline time.Time) (context.Context, context.CancelFunc) { - return context.WithTimeout(ctx, deadline.Sub(c.now())) -} - -// createResolved makes this attempt's exclusive create of e under dir and -// returns its outcome and the entry now under the name (nil if unread). -// The create runs under publish (bounded by the operation's deadline); the -// re-read that settles an ambiguous failure under ctx. -// attempt, when not empty, is stored in e as extAttempt; a re-read that -// finds it confirms this attempt's create. Only the filer's own "already -// exists" answer settles a failure as refused; any other failure leaves -// the create unsettled, whatever entry the re-read finds (that entry may -// be another attempt's, and this one may still land after it is gone). -func (c *Catalog) createResolved(ctx, publish context.Context, dir string, e *filerpb.Entry, attempt string) (createOutcome, *filerpb.Entry, error) { - if attempt != "" { - e.Extended[extAttempt] = []byte(attempt) - } - err := c.f.CreateEntry(publish, dir, e, true) - if err == nil { - return createdNow, e, nil - } - got, lerr := c.f.LookupEntry(ctx, dir, e.GetName()) - if lerr != nil { - got = nil - } - if got != nil && attempt != "" && string(got.Extended[extAttempt]) == attempt { - return createdNow, got, nil - } - if errors.Is(err, ErrExists) { - return createRefused, got, err - } - return createUnsettled, got, err -} - -func headDigest(h storage.ChunkHead) (string, error) { - e, err := headEntry(h) - if err != nil { - return "", err - } - sum := sha256.Sum256(e.Content) - return hex.EncodeToString(sum[:]), nil -} - -func headKeys(h storage.ChunkHead) []string { - if h.Segments != nil { - keys := make([]string, 0, len(h.Segments)) - for _, ref := range h.Segments { - keys = append(keys, ref.Key) - } - return keys - } - keys := make([]string, 0, len(h.Chunks)) - for _, ref := range h.Chunks { - keys = append(keys, ref.Key) - } - return keys -} - -// CreateSnapshot stores head, which must be the HEAD a cut of vol installed -// (ChunkCutResult.Head), as the snapshot req.Name. A retry with the same -// RequestID returns the existing snapshot (Replayed); another RequestID -// gets snapshot_exists. The name is taken with an exclusive name record -// {request, attempt}; an intent names the snapshot's keys and the attempt -// (holder "snapshot://") before the exclusive create at -// the attempt path snaps//, which only that request's -// attempts ever write. -func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRequest, head storage.ChunkHead) (SnapshotInfo, error) { - readAt := req.SourceReadAt - if readAt.IsZero() { - readAt = c.now() - } - root, err := c.volRoot(vol) - if err != nil { - return SnapshotInfo{}, err - } - if existing, replayed, err := c.SnapshotReplay(ctx, vol, req); err != nil || replayed { - return existing, err - } - consistency := req.Consistency - if consistency == "" { - consistency = "crash" - } - if err := ValidateSnapshotClass(req.Class); err != nil { - return SnapshotInfo{}, err - } - if head.Gen == 0 { - return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no published HEAD to snapshot", vol) - } - v, ok, err := c.ReadVolume(ctx, vol) - if err != nil { - return SnapshotInfo{}, err - } - if !ok { - return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol) - } - if v.Origin == OriginRestore { - // A restore is independent only once its marker exists: a snapshot - // taken before would keep naming the source's chunks for its whole - // retention, so it is refused until then. - if _, independent, err := c.ReadIndependence(ctx, vol); err != nil { - return SnapshotInfo{}, err - } else if !independent { - return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s is still being restored: snapshots are refused until it is independent", vol) - } - // The supplied image need not be the current HEAD: a cut taken before - // the marker may still name the source's chunks. Check the image itself. - if q, err := c.foreignRefsOf(ctx, vol, head); err != nil { - return SnapshotInfo{}, err - } else if q > 0 { - return SnapshotInfo{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: snapshot image gen %d holds %d refs to another volume", vol, head.Gen, q) - } - } - shareToken := req.ShareToken - if shareToken == "" { - if shareToken, err = c.beginShare(ctx, vol, head); err != nil { - return SnapshotInfo{}, err - } - } - - // Take the name: this request's record, or an earlier attempt's of it. - attempt, err := c.claimName(ctx, vol, root, req, head.Gen) - if err != nil { - return SnapshotInfo{}, err - } - // A volume delete marks HEAD deleting before it checks for snapshot - // names: either it sees this name (and refuses), or this read sees the - // mark and nothing is published. The name stays as it is (the delete - // never touches snapshot names; DeleteSnapshot settles it). - if gone, err := c.volumeGone(ctx, vol); err != nil { - return SnapshotInfo{}, err - } else if gone { - return SnapshotInfo{}, refuseDeleted(vol, "it cannot be snapshotted") - } - - head, upgradeIDs, err := c.prepareLegacyHead(ctx, root, head, head, v.Geometry) - defer c.dropManifestIntents(ctx, root, upgradeIDs) - if err != nil { - return SnapshotInfo{}, err - } - headEnt, err := headEntry(head) - if err != nil { - return SnapshotInfo{}, err - } - doc := snapDoc{Format: snapFormat, VolumeID: vol, Name: req.Name, RequestID: req.RequestID, CreatedNs: c.now().UnixNano(), - CreatedBy: req.CreatedBy, Consistency: consistency, Head: headEnt.Content, Geometry: v.Geometry, Parent: v.Parent, - Labels: req.Labels, ExpiresAtNs: req.ExpiresAtNs, Class: req.Class} - body, err := json.Marshal(doc) - if err != nil { - return SnapshotInfo{}, err - } - now := time.Now().Unix() - e := &filerpb.Entry{ - Name: attempt, - Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"}, - Extended: map[string][]byte{ - extKind: []byte(kindChunkSnap), - extSnapGen: []byte(strconv.FormatUint(head.Gen, 10)), - extSnapEpoch: []byte(strconv.FormatUint(head.Epoch, 10)), - extSnapLSN: []byte(strconv.FormatUint(head.RemoteLSN, 10)), - extSnapState: []byte(SnapActive), - extReq: []byte(req.RequestID), - }, - Content: body, - } - - tag := "snapshot:" + vol + "/" + req.Name + "/" + attempt - deadline := readAt.Add(c.deadline()) - id, err := putIntent(ctx, c.f, root, storage.ChunkIntent{Gen: head.Gen, Epoch: head.Epoch, Holder: tag, Keys: headKeys(head), Segments: head.Segments, ChunkBytes: head.ChunkBytes, - DeadlineNs: deadline.UnixNano()}) - if err != nil { - return SnapshotInfo{}, remoteErr(err, "intent for snapshot %s/%s", vol, req.Name) - } - if !c.now().Before(deadline) { // re-checked immediately before publishing - // Clean abort: the snapshot entry was never sent. - c.dropIntent(ctx, root, id) - return SnapshotInfo{}, catErr(CodeDeadlineExceeded, true, nil, "snapshot %s/%s: %v since the cut, over the %v deadline; nothing written", vol, req.Name, c.now().Sub(readAt), c.deadline()) - } - dir := path.Join(root, snapsDir, req.Name) - if err := c.finishShare(ctx, vol, shareToken, head); err != nil { - // Clean abort: the snapshot entry was never sent. - c.dropIntent(ctx, root, id) - return SnapshotInfo{}, err - } - pctx, cancel := c.publishCtx(ctx, deadline) - outcome, got, cerr := c.createResolved(ctx, pctx, dir, e, attempt) - cancel() - switch { - case outcome == createdNow: - // This request's snapshot is at the attempt path (this create, or - // an earlier attempt's of the same request). Judge it from that - // entry, never by resolving the name again (the name can be freed - // and reused meanwhile). - c.dropIntent(ctx, root, id) - info, _, err := decodeSnap(path.Join(dir, attempt), got) - if err != nil { - return SnapshotInfo{}, err - } - if info.State == SnapAborted { - return SnapshotInfo{}, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s: this request's attempt was aborted; delete the name to reuse it", vol, req.Name) - } - if info.State == SnapDeleting { - return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s is being deleted; wait for the delete to finish, then reuse the name", req.Name) - } - return info, nil - case got != nil: - // The attempt path holds a sweep's tombstone, which is permanent: - // this create can never land. - c.dropIntent(ctx, root, id) - return SnapshotInfo{}, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s: this request's attempt was aborted; delete the name to reuse it", vol, req.Name) - case outcome == createRefused: - c.dropIntent(ctx, root, id) - return SnapshotInfo{}, remoteErr(cerr, "snapshot %s/%s: the attempt path exists but could not be read; retry with the same request id", vol, req.Name) - default: - // Unsettled: the create may still land; its intent stays. - return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, cerr, "snapshot %s/%s: create outcome unknown; its intent is kept, retry with the same request id", vol, req.Name) - } -} - -// claimName returns the attempt that publishes req: a new attempt whose -// name record this call created, or the attempt of this request's earlier -// record (a retry publishes to the same attempt path). -func (c *Catalog) claimName(ctx context.Context, vol, root string, req SnapshotRequest, gen uint64) (string, error) { - attempt, err := storage.NewChunkIntentID(gen) - if err != nil { - return "", err - } - re, err := nameRecordEntry(nameRecord{Format: snapFormat, VolumeID: vol, Name: req.Name, RequestID: req.RequestID, Attempt: attempt, CreatedNs: c.now().UnixNano()}) - if err != nil { - return "", err - } - cerr := c.f.CreateEntry(ctx, path.Join(root, snapNamesDir), re, true) - if cerr == nil { - return attempt, nil - } - // Taken, or an ambiguous create: the record now under the name decides. - ref, ok, err := c.resolveSnap(ctx, vol, req.Name) - if err != nil || !ok { - return "", catErr(CodeOutcomeUnknown, true, cerr, "snapshot %s/%s: name record outcome unknown; retry with the same request id", vol, req.Name) - } - if ref.rec.RequestID != req.RequestID { - return "", catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s exists (another request)", vol, req.Name) - } - return ref.rec.Attempt, nil -} - -// SnapshotReplay resolves a snapshot request against the catalog before -// the caller cuts (B9 W2 §3.2 step 1): when the name is held by req's -// request and its attempt published, it returns that snapshot (Replayed, -// true); held by another request, snapshot_exists; free, or held by req's -// unpublished attempt, (zero, false, nil). It validates the whole request -// first (name, request id, labels, consistency), so a caller can refuse a -// bad request before it cuts. -func (c *Catalog) SnapshotReplay(ctx context.Context, vol string, req SnapshotRequest) (SnapshotInfo, bool, error) { - if _, err := c.volRoot(vol); err != nil { - return SnapshotInfo{}, false, err - } - if err := CheckSnapshotName(req.Name); err != nil { - return SnapshotInfo{}, false, err - } - if req.RequestID == "" { - return SnapshotInfo{}, false, catErr(CodeInvalidName, false, nil, "snapshot %s/%s: a request id is required", vol, req.Name) - } - if err := checkLabels(req.Labels); err != nil { - return SnapshotInfo{}, false, err - } - if cs := req.Consistency; cs != "" && cs != "crash" && cs != "app" { - return SnapshotInfo{}, false, catErr(CodeInvalidName, false, nil, "consistency %q: crash or app", cs) - } - ref, ok, err := c.resolveSnap(ctx, vol, req.Name) - switch { - case err != nil: - return SnapshotInfo{}, false, err - case !ok: - return SnapshotInfo{}, false, nil - case ref.rec.RequestID != req.RequestID: - return SnapshotInfo{}, false, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s exists (another request)", vol, req.Name) - case ref.entry == nil: - return SnapshotInfo{}, false, nil // this request's attempt has not published: publish it - case ref.info.State == SnapAborted: - return SnapshotInfo{}, false, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s: this request's attempt was aborted; delete the name to reuse it", vol, req.Name) - case ref.info.State == SnapDeleting: - return SnapshotInfo{}, false, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s is being deleted; wait for the delete to finish, then reuse the name", req.Name) - } - ref.info.Replayed = true - return ref.info, true, nil -} - -// ListSnapshots lists vol's named snapshots in name order, after -// opts.StartAfter: names whose attempt published and was not aborted. A -// deleted snapshot no longer holds its name (opts.IncludeDeleting adds the -// ones marked deleting that still do). next is the last name returned when -// more may follow, else "". -func (c *Catalog) ListSnapshots(ctx context.Context, vol string, opts ListOptions) ([]SnapshotInfo, string, error) { - root, err := c.volRoot(vol) - if err != nil { - return nil, "", err - } - limit := opts.Limit - if limit <= 0 { - limit = defaultListLimit - } - if limit > maxListLimit { - limit = maxListLimit - } - dir := path.Join(root, snapNamesDir) - var out []SnapshotInfo - after := opts.StartAfter - for { - page, err := c.f.ListEntries(ctx, dir, opts.Prefix, after, uint32(limit)) - if err != nil { - return nil, "", remoteErr(err, "list snapshots of %s", vol) - } - for _, e := range page { - after = e.GetName() - ref, ok, err := c.resolveSnap(ctx, vol, e.GetName()) - if err != nil { - return nil, "", err - } - if !ok || ref.entry == nil || ref.info.State == SnapAborted || (ref.info.State == SnapDeleting && !opts.IncludeDeleting) { - continue - } - out = append(out, ref.info) - if len(out) == limit { - return out, after, nil - } - } - if len(page) < limit { - return out, "", nil - } - } -} - -// DeleteSnapshot frees the name (spec §3.4, W5): -// it marks the attempt deleting (or, when the attempt never published, -// claims its path with an aborted tombstone so a late insert cannot land), -// then removes the name record. The attempt path is never removed. It -// returns SnapDeleting, or SnapAbsent when no snapshot holds the name; both -// are success, so a retry is always safe. -func (c *Catalog) DeleteSnapshot(ctx context.Context, vol, name string) (string, error) { - root, err := c.volRoot(vol) - if err != nil { - return "", err - } - if err := CheckSnapshotName(name); err != nil { - return "", err - } - dir := path.Join(root, snapsDir, name) - for try := 0; try < 3; try++ { - ref, ok, err := c.resolveSnap(ctx, vol, name) - if err != nil { - return "", err - } - if !ok { - return SnapAbsent, nil - } - switch { - case ref.entry == nil: - tomb, err := c.abortedSnapEntry(vol, name, ref.rec.Attempt) - if err != nil { - return "", err - } - if err := c.f.CreateEntry(ctx, dir, tomb, true); err != nil && !errors.Is(err, ErrExists) { - return "", remoteErr(err, "claim the unpublished attempt of %s/%s", vol, name) - } - continue // re-read: the path now holds a tombstone or the late snapshot - case ref.info.State == SnapActive: - // The one mark path shared with retention; forks do not hold it. - m, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) - if err != nil { - return "", err - } - if m == markGone { - continue - } - } - // The attempt is deleting or aborted: free the name. - err = c.f.DeleteEntry(ctx, path.Join(root, snapNamesDir), name, map[string][]byte{extAttempt: []byte(ref.rec.Attempt)}) - if err != nil && !errors.Is(err, ErrNotFound) && !errors.Is(err, ErrPrecondition) { - return "", remoteErr(err, "remove the name record %s/%s", vol, name) - } - return SnapDeleting, nil - } - return "", remoteErr(nil, "delete snapshot %s/%s: it kept changing", vol, name) -} - -// ListVolumes returns the ids of every volume directory under the base (GC). -func (c *Catalog) ListVolumes(ctx context.Context) ([]string, error) { - var out []string - after := "" - for { - page, err := c.f.ListEntries(ctx, c.base, "", after, listPage) - if err != nil { - return nil, remoteErr(err, "list volumes under %s", c.base) - } - for _, e := range page { - after = e.GetName() - if e.GetIsDirectory() && CheckVolumeID(e.GetName()) == nil { - out = append(out, e.GetName()) - } - } - if len(page) < listPage { - return out, nil - } - } -} - -// ---- fork ---- - -// Fork makes req.Target a new volume whose content is snapshot -// req.Source/req.Snapshot, in O(1) filer writes and no data copy. -// -// The target is resolved first, independently of the source: -// - a target VOLUME from another request is target_exists, and so is one -// from this request id with other parameters; -// - a completed fork of this request (VOLUME and HEAD exist) replays the -// result recorded in VOLUME, even if the source has changed since. -// -// Otherwise: -// 1. read the snapshot (snapshot_not_found, snapshot_deleting); -// 2. exclusively create the target's VOLUME (origin fork, the snapshot's -// geometry, parent, and a fork record binding the request to the -// snapshot's image digest and the result). An incomplete fork of this -// request resumes only if the snapshot still has that exact image; -// 3. qualify every chunk ref as "@/" (a ref already qualified -// keeps its owner), under an intent in the target; -// 4. exclusively create the target's HEAD: gen 1, epoch 0, no holder, and -// the snapshot's remote_lsn (LSNs carry forward). -// -// The HEAD write is refused once OpDeadline has passed since step 1. An -// uncertain outcome of step 2 or 4 is outcome_unknown; a retry with the same -// request id completes the fork. An attempt whose HEAD create stays -// unsettled keeps its own intent (that create may still land); no attempt -// or replay deletes another attempt's intent. -func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) { - return c.fork(ctx, req, OriginFork) -} - -// Restore starts an independent restore of req.Source's snapshot into -// req.Target: the same steps as Fork (claim, qualified refs, HEAD), recorded -// with Origin restore. The target serves at once (lazy fill); the restore -// driver then hydrates every chunk, re-uploads the qualified ones under the -// target's own keys in bounded batch cuts, and MarkIndependent records the -// end of the lineage once HEAD holds no ref to another volume. -func (c *Catalog) Restore(ctx context.Context, req ForkRequest) (ForkResult, error) { - return c.fork(ctx, req, OriginRestore) -} - -// isForked reports whether origin made the volume from another volume's -// snapshot (a fork record exists and HEAD may hold qualified refs). -func isForked(origin string) bool { return origin == OriginFork || origin == OriginRestore } - -func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (ForkResult, error) { - if _, err := c.volRoot(req.Source); err != nil { - return ForkResult{}, err - } - dstRoot, err := c.volRoot(req.Target) - if err != nil { - return ForkResult{}, err - } - if req.Source == req.Target { - return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork target %s is the source", req.Target) - } - if err := CheckSnapshotName(req.Snapshot); err != nil { - return ForkResult{}, err - } - if req.RequestID == "" { - return ForkResult{}, catErr(CodeInvalidName, false, nil, "fork %s: a request id is required", req.Target) - } - if err := checkLabels(req.Labels); err != nil { - return ForkResult{}, err - } - tag := "fork:" + req.Target + "/" + req.RequestID - - // The target first: replay or refuse without reading the source. - existing, ok, err := c.ReadVolume(ctx, req.Target) - if err != nil { - return ForkResult{}, err - } - if ok && existing.State == VolumeDeleted { - return ForkResult{}, refuseDeleted(req.Target, "fork to a new volume id") - } - if ok { - if err := c.checkForkRecord(existing, req, origin); err != nil { - return ForkResult{}, err - } - h, has, err := c.ReadHead(ctx, req.Target) - if err != nil { - return ForkResult{}, err - } - if has && h.State == storage.ChunkHeadAborted { - return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork %s was aborted (its HEAD is a tombstone); fork to a new volume id", req.Target) - } - if has && headDeletingOrDeleted(h) { - // The target is being (or was) deleted: never a successful - // replay, also before its VOLUME is marked. - return ForkResult{}, refuseDeleted(req.Target, "fork to a new volume id") - } - if has { - return forkResult(existing, true), nil - } - } - - // The deadline starts before the parent is read, and every attempt - // (a retry included) reads it again: a snapshot deleted before the read - // is refused, and one deleted after it stays rooted by GC's grace past - // readAt + deadline, the last moment this fork can publish - // (INV-SNAP-DELETE-ANY-ORDER-001). The parent is not claimed. - readAt := c.now() - deadline := readAt.Add(c.deadline()) - var shareToken string - if c.guard != nil { // the shared HEAD is the snapshot's, read below - if shareToken, err = c.guard.Begin(ctx, req.Source); err != nil { - return ForkResult{}, remoteErr(err, "share guard for %s", req.Source) - } - } - snap, err := c.readForkParent(ctx, req) - if err != nil { - return ForkResult{}, err - } - if gone, err := c.volumeGone(ctx, req.Source); err != nil { - return ForkResult{}, err - } else if gone { - return ForkResult{}, refuseDeleted(req.Source, "its snapshots cannot be forked") - } - if snap.geo == (Geometry{}) { - return ForkResult{}, fmt.Errorf("chunkstore: snapshot %s/%s has no geometry", req.Source, req.Snapshot) - } - src := snap.Head() - digest := snap.digest - head := storage.ChunkHead{Gen: 1, Epoch: 0, Holder: "", RemoteLSN: src.RemoteLSN, Chunks: make(map[uint64]storage.ChunkRef, len(src.Chunks)), State: storage.ChunkHeadActive} - qualified := 0 - if src.Segments != nil { - head.Segments = make(map[uint64]storage.ChunkSegment, len(src.Segments)) - head.ChunkBytes, head.ManifestChunkCount = src.ChunkBytes, src.ManifestChunkCount - for idx, ref := range src.Segments { - ref.Key = qualifyManifestKey(req.Source, ref.Key) - head.Segments[idx] = ref - qualified++ - } - } - for idx, ref := range src.Chunks { - if !strings.HasPrefix(ref.Key, "@") { - ref.Key = "@" + req.Source + "/" + ref.Key - qualified++ - } - head.Chunks[idx] = ref - } - record := &ForkRecord{RequestID: req.RequestID, Source: req.Source, Snapshot: req.Snapshot, SourceGen: snap.HeadGen, - HeadSHA256: digest, RemoteLSN: head.RemoteLSN, ChunkCount: manifestCount(head), QualifiedRefs: qualified} - - if ok { - // An incomplete fork of this request resumes only on the same image. - if existing.Fork.HeadSHA256 != digest || existing.Fork.SourceGen != snap.HeadGen || existing.Geometry != snap.geo { - return ForkResult{}, catErr(CodeTargetExists, false, nil, - "fork %s: snapshot %s/%s changed since this request's first attempt (gen %d -> %d); not resuming onto another image", - req.Target, req.Source, req.Snapshot, existing.Fork.SourceGen, snap.HeadGen) - } - } else { - if !c.now().Before(deadline) { - return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; VOLUME not written", req.Target) - } - vol := VolumeInfo{Format: volumeFormat, VolumeID: req.Target, Geometry: snap.geo, Origin: origin, CreatedNs: c.now().UnixNano(), - Parent: &Parent{VolumeID: req.Source, Snapshot: req.Snapshot, Gen: snap.HeadGen}, Fork: record} - ve, err := volumeEntry(vol, req.RequestID) - if err != nil { - return ForkResult{}, err - } - // VOLUME names no chunk keys, so it needs no intent; a found VOLUME - // is this request's when it binds the same request and image. - outcome, got, cerr := c.createResolved(ctx, ctx, dstRoot, ve, "") - if outcome != createdNow { - if got == nil { - return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: VOLUME create outcome unknown; retry with the same request id", req.Target) - } - v, err := decodeVolume(path.Join(dstRoot, volumeName), got) - if err != nil || c.checkForkRecord(v, req, origin) != nil || v.Fork.HeadSHA256 != digest { - return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s exists (another request, or another image)", req.Target) - } - } - existing = vol - } - - if !c.now().Before(deadline) { - return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; manifest preparation not started", req.Target) - } - head, upgradeIDs, err := c.prepareLegacyHead(ctx, dstRoot, storage.ChunkHead{}, head, snap.geo) - defer c.dropManifestIntents(ctx, dstRoot, upgradeIDs) - if err != nil { - return ForkResult{}, err - } - he, err := headEntry(head) - if err != nil { - return ForkResult{}, err - } - he.Extended[extReq] = []byte(req.RequestID) - if !c.now().Before(deadline) { - return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; copy intent not written", req.Target) - } - id, err := putIntent(ctx, c.f, dstRoot, storage.ChunkIntent{Gen: 0, Epoch: 0, Holder: tag, Keys: headKeys(head), Segments: head.Segments, ChunkBytes: head.ChunkBytes, - DeadlineNs: deadline.UnixNano()}) - if err != nil { - return ForkResult{}, remoteErr(err, "intent for fork %s", req.Target) - } - if !c.now().Before(deadline) { // re-checked immediately before publishing - // Clean abort: HEAD was never sent. - c.dropIntent(ctx, dstRoot, id) - return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: %v since reading the snapshot, over the %v deadline; HEAD not written", req.Target, c.now().Sub(readAt), c.deadline()) - } - if err := c.finishShare(ctx, req.Source, shareToken, src); err != nil { - // Clean abort: HEAD was never sent. - c.dropIntent(ctx, dstRoot, id) - return ForkResult{}, err - } - // Under this request's VOLUME only this request's attempts write HEAD - // (attach refuses a fork without HEAD), so a HEAD found there completes - // the fork; if it is another attempt's and this create is unsettled, - // this attempt's intent stays (the create may land after HEAD is gone). - pctx, cancel := c.publishCtx(ctx, deadline) - outcome, got, cerr := c.createResolved(ctx, pctx, dstRoot, he, id) - cancel() - // The HEAD now at the target decides, from that one read: a real HEAD - // completes the fork; an aborted tombstone means a sweep claimed the - // target first, so this fork lost and its create can never land. - if got == nil { - if outcome == createUnsettled { - return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: HEAD create outcome unknown; its intent is kept, retry with the same request id", req.Target) - } - c.dropIntent(ctx, dstRoot, id) // refused for good, but HEAD could not be read - return ForkResult{}, remoteErr(cerr, "fork %s: HEAD exists but could not be read; retry with the same request id", req.Target) - } - h, err := decodeHead(path.Join(dstRoot, headName), got) - if err != nil { - return ForkResult{}, err - } - if h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { - c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands - return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork %s lost to a sweep: its HEAD is an aborted tombstone; fork to a new volume id", req.Target) - } - if outcome != createUnsettled { - c.dropIntent(ctx, dstRoot, id) // confirmed, or refused for good - } - return forkResult(existing, outcome != createdNow), nil -} - -// readForkParent returns the published snapshot fork req names. A parent -// deleting is refused (snapshot_deleting), an absent or aborted one -// (snapshot_not_found). -func (c *Catalog) readForkParent(ctx context.Context, req ForkRequest) (SnapshotInfo, error) { - ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) - if err != nil { - return SnapshotInfo{}, err - } - if !ok || ref.entry == nil || ref.info.State == SnapAborted { - return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", req.Source, req.Snapshot) - } - if ref.info.State == SnapDeleting { - return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) - } - if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) { - return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) - } - return ref.info, nil -} - -// AbortFork settles a dead fork for a GC sweep (W5): it claims the -// target's HEAD, the fork's publishing entry, with -// an exclusive create of an aborted HEAD tombstone. claimed is true when -// HEAD is a tombstone (this one or an earlier one): the fork can never -// publish, and the target never attaches. false: the fork published, and -// its keys are reachable through that HEAD. Either way the fork's copy -// intent can then be deleted. Volume ids are never reused, so the -// tombstone stays. -func (c *Catalog) AbortFork(ctx context.Context, target string) (claimed bool, err error) { - root, err := c.volRoot(target) - if err != nil { - return false, err - } - he, err := headEntry(storage.ChunkHead{Gen: 1, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadAborted}) - if err != nil { - return false, err - } - switch err := c.f.CreateEntry(ctx, root, he, true); { - case err == nil: - return true, nil - case !errors.Is(err, ErrExists): - return false, remoteErr(err, "aborted HEAD of %s", target) - } - h, _, err := c.ReadHead(ctx, target) - if err != nil { - return false, err - } - return h.State == storage.ChunkHeadAborted, nil -} - -// checkForkRecord refuses a target VOLUME that is not this fork request's. -func (c *Catalog) checkForkRecord(v VolumeInfo, req ForkRequest, origin string) error { - if v.Origin != origin { - return catErr(CodeTargetExists, false, nil, "volume %s exists (origin %s, not %s)", req.Target, v.Origin, origin) - } - if v.Fork == nil || v.Fork.RequestID != req.RequestID { - return catErr(CodeTargetExists, false, nil, "volume %s exists (another request)", req.Target) - } - if v.Fork.Source != req.Source || v.Fork.Snapshot != req.Snapshot { - return catErr(CodeTargetExists, false, nil, "volume %s: request id %s was used for a fork of %s/%s", req.Target, req.RequestID, v.Fork.Source, v.Fork.Snapshot) - } - return nil -} - -// forkResult is the result recorded when the fork created VOLUME. -func forkResult(v VolumeInfo, replayed bool) ForkResult { - r := v.Fork - return ForkResult{Target: v.VolumeID, Source: r.Source, Snapshot: r.Snapshot, SourceGen: r.SourceGen, HeadGen: 1, HeadEpoch: 0, - RemoteLSN: r.RemoteLSN, ChunkCount: r.ChunkCount, QualifiedRefs: r.QualifiedRefs, Replayed: replayed} -} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_b.go b/seaweed-block/core/frontend/chunkstore/catalog_b.go new file mode 100644 index 0000000000..610738d7dd --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_b.go @@ -0,0 +1,333 @@ +package chunkstore + +import ( + "context" + "errors" + "fmt" + "path" + "sort" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// VolumeRef names a volume as the master's volume record does: its name +// and its layout volume id. Its directory is layout.VolumeDir(name, id), +// never reused. +type VolumeRef struct { + Name string + ID layout.VolumeID +} + +// Dir is the volume's directory name under the store's base. +func (v VolumeRef) Dir() string { return layout.VolumeDir(v.Name, v.ID) } + +// BCatalog is the volume catalog on the content-named layout: every +// operation is a layout kernel step over the volume's filer store. +type BCatalog struct { + f Filer + b Blobs + base string +} + +// NewBCatalog returns the catalog of the volumes under base. +func NewBCatalog(f Filer, b Blobs, base string) (*BCatalog, error) { + if f == nil || b == nil || !path.IsAbs(base) || path.Clean(base) != base { + return nil, errors.New("chunkstore: catalog needs a filer, blobs and a clean base") + } + return &BCatalog{f: f, b: b, base: base}, nil +} + +// Store returns the volume's filer store. +func (c *BCatalog) Store(v VolumeRef) (*LayoutStore, error) { + return NewLayoutStore(c.f, c.b, path.Join(c.base, v.Dir()), v.ID) +} + +func (c *BCatalog) open(v VolumeRef) (*LayoutStore, *layout.Reader, error) { + s, err := c.Store(v) + if err != nil { + return nil, nil, err + } + r, err := layout.NewReader(c.base, v.Dir(), s.Fetch) + return s, r, err +} + +// CreateVolume creates the volume with its unclaimed HEAD. +func (c *BCatalog) CreateVolume(ctx context.Context, v VolumeRef, geometry layout.Geometry) (layout.Head, error) { + s, err := c.Store(v) + if err != nil { + return layout.Head{}, err + } + return layout.CreateVolume(ctx, s, layout.Volume{ID: v.ID, Name: v.Name, Format: layout.VolumeFormat, Geometry: geometry}) +} + +// ReadVolume returns the source's immutable VOLUME record; a restore takes +// its geometry from this record rather than operator flags. +func (c *BCatalog) ReadVolume(ctx context.Context, v VolumeRef) (layout.Volume, error) { + s, err := c.Store(v) + if err != nil { + return layout.Volume{}, err + } + got, found, err := s.ReadVolumeRecord(ctx) + if err != nil { + return layout.Volume{}, err + } + if !found { + return layout.Volume{}, layout.ErrMissing + } + if got.ID != v.ID || got.Name != v.Name { + return layout.Volume{}, layout.ErrIdentity + } + return got, nil +} + +// ReadHead reads the volume's HEAD. +func (c *BCatalog) ReadHead(ctx context.Context, v VolumeRef) (layout.Head, bool, error) { + s, err := c.Store(v) + if err != nil { + return layout.Head{}, false, err + } + return s.ReadHead(ctx) +} + +// DeleteSnapshot removes the named snapshot; refused while it has +// dependents. +func (c *BCatalog) DeleteSnapshot(ctx context.Context, v VolumeRef, name string) (layout.Head, error) { + s, err := c.Store(v) + if err != nil { + return layout.Head{}, err + } + return layout.RunDeleteSnapshot(ctx, s, name) +} + +// Restore creates target from the source's named snapshot: the target is +// recorded as the snapshot's dependent, the snapshot's root and segments +// are copied into the target's directory, then the target is created with +// that root as its current image. +func (c *BCatalog) Restore(ctx context.Context, src VolumeRef, snapshot string, target VolumeRef) (layout.Head, error) { + ss, sr, err := c.open(src) + if err != nil { + return layout.Head{}, err + } + ts, err := c.Store(target) + if err != nil { + return layout.Head{}, err + } + copyRoot := func(ctx context.Context, rn layout.RootName) error { + raw, err := c.fetchVerified(ctx, ss, src, rn.Path(), rn.Hash) + if err != nil { + return err + } + root, err := layout.DecodeRoot(raw) + if err != nil { + return err + } + segs := map[layout.SegName][]byte{} + for _, n := range root.Segments { + if segs[n], err = c.fetchVerified(ctx, ss, src, n.Path(), n.Hash); err != nil { + return err + } + } + got, err := layout.PrepareRoot(ctx, ts, root, segs, "restore-"+target.ID.String()) + if err == nil && got != rn { + err = fmt.Errorf("%w: root %s re-encodes as %s", layout.ErrCorrupt, rn, got) + } + return err + } + source, found, err := ss.ReadVolumeRecord(ctx) + if err != nil { + return layout.Head{}, err + } + if !found { + return layout.Head{}, layout.ErrMissing + } + return layout.CreateTarget(ctx, ss, sr, snapshot, ts, layout.Volume{ID: target.ID, Name: target.Name, Format: layout.VolumeFormat, Geometry: source.Geometry}, copyRoot) +} + +func (c *BCatalog) fetchVerified(ctx context.Context, s *LayoutStore, v VolumeRef, rel string, want layout.Hash) ([]byte, error) { + p := path.Join(c.base, v.Dir(), rel) + raw, found, err := s.Fetch(ctx, p) + if err != nil { + return nil, err + } + if !found { + return nil, fmt.Errorf("%w: %s", layout.ErrMissing, p) + } + if layout.Sum(raw) != want { + return nil, fmt.Errorf("%w: %s does not hash to its name", layout.ErrCorrupt, p) + } + return raw, nil +} + +// ReleaseTarget removes target from the source's dependents once the +// target is deleted or no longer names the source's chunks (the operator's +// remove-dependent; a target without HEAD is tombstoned first). +func (c *BCatalog) ReleaseTarget(ctx context.Context, src, target VolumeRef) (layout.Head, error) { + ss, err := c.Store(src) + if err != nil { + return layout.Head{}, err + } + ts, tr, err := c.open(target) + if err != nil { + return layout.Head{}, err + } + return layout.OperatorReleaseDependent(ctx, ss, ts, tr, target.ID) +} + +// DeleteVolume deletes the volume in the kernel's order. The sources it is +// released from are the volumes its roots name chunks of (read from its +// references, never from a name given); its objects are every pool, +// segment and root entry in its directory, listed after HEAD is deleting. +// A re-run on a deleted volume sweeps any object that landed late. +func (c *BCatalog) DeleteVolume(ctx context.Context, v VolumeRef, auth layout.DeleteAuthority) error { + s, r, err := c.open(v) + if err != nil { + return err + } + h, found, err := s.ReadHead(ctx) + if err != nil { + return err + } + if !found { + return layout.ErrHeadAbsent + } + owners, err := foreignOwners(ctx, r, h) + if err != nil { + return err + } + var sources []layout.HeadStore + for _, o := range owners { + ss, err := c.Store(o) + if err != nil { + return err + } + sources = append(sources, ss) + } + list := func(ctx context.Context) ([]string, error) { return c.listObjects(ctx, v) } + return layout.DeleteVolume(ctx, s, auth, v.ID, sources, s, list) +} + +// foreignOwners returns the volumes, other than h's own, whose chunks a +// root in h names, from the references themselves. +func foreignOwners(ctx context.Context, r *layout.Reader, h layout.Head) ([]VolumeRef, error) { + roots := map[layout.RootName]bool{} + if h.Current != nil { + roots[*h.Current] = true + } + for _, s := range h.Snapshots { + roots[s.Root] = true + } + seen := map[VolumeRef]bool{} + for rn := range roots { + refs, err := rootRefs(ctx, r, rn) + if err != nil { + return nil, err + } + for _, ref := range refs { + if ref.OwnerID != h.VolumeID { + seen[VolumeRef{Name: ref.Owner, ID: ref.OwnerID}] = true + } + } + } + out := make([]VolumeRef, 0, len(seen)) + for o := range seen { + out = append(out, o) + } + sort.Slice(out, func(a, b int) bool { return out[a].Dir() < out[b].Dir() }) + return out, nil +} + +// rootRefs returns every chunk reference the root names. +func rootRefs(ctx context.Context, r *layout.Reader, rn layout.RootName) ([]layout.Ref, error) { + var out []layout.Ref + err := r.EachRef(ctx, rn, layout.AllShards, func(_ uint64, ref layout.Ref) bool { out = append(out, ref); return true }) + return out, err +} + +// listObjects lists the volume's pool, segment and root entries. +func (c *BCatalog) listObjects(ctx context.Context, v VolumeRef) ([]string, error) { + dir := path.Join(c.base, v.Dir()) + var out []string + buckets, err := c.listAll(ctx, path.Join(dir, layout.PoolDir)) + if err != nil { + return nil, err + } + for _, b := range buckets { + names, err := c.listAll(ctx, path.Join(dir, layout.PoolDir, b)) + if err != nil { + return nil, err + } + for _, n := range names { + out = append(out, path.Join(layout.PoolDir, b, n)) + } + } + for _, sub := range []string{layout.SegDir, layout.RootDir} { + names, err := c.listAll(ctx, path.Join(dir, sub)) + if err != nil { + return nil, err + } + for _, n := range names { + out = append(out, path.Join(sub, n)) + } + } + return out, nil +} + +func (c *BCatalog) listAll(ctx context.Context, dir string) ([]string, error) { + var out []string + after := "" + for { + es, err := c.f.ListEntries(ctx, dir, "", after, 1000) + if err != nil { + return nil, err + } + for _, e := range es { + out = append(out, e.Name) + } + if len(es) < 1000 { + return out, nil + } + after = es[len(es)-1].Name + } +} + +// Usage is what a volume's HEAD holds: its snapshots, their dependents, and +// the chunks its current image names, its own and other volumes'. +type Usage struct { + Snapshots int `json:"snapshots"` + Dependents int `json:"dependents"` + OwnChunks int `json:"own_chunks"` + ForeignChunks int `json:"foreign_chunks"` +} + +// Usage reads the volume's usage from its HEAD and current root. +func (c *BCatalog) Usage(ctx context.Context, v VolumeRef) (Usage, error) { + s, r, err := c.open(v) + if err != nil { + return Usage{}, err + } + h, found, err := s.ReadHead(ctx) + if err != nil { + return Usage{}, err + } + if !found { + return Usage{}, layout.ErrHeadAbsent + } + u := Usage{Snapshots: len(h.Snapshots)} + for _, sn := range h.Snapshots { + u.Dependents += len(sn.Dependents) + } + if h.Current != nil { + refs, err := rootRefs(ctx, r, *h.Current) + if err != nil { + return Usage{}, err + } + for _, ref := range refs { + if ref.OwnerID == h.VolumeID { + u.OwnChunks++ + } else { + u.ForeignChunks++ + } + } + } + return u, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_b_test.go b/seaweed-block/core/frontend/chunkstore/catalog_b_test.go new file mode 100644 index 0000000000..9e5c030e29 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_b_test.go @@ -0,0 +1,202 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +type okDeleteAuthority struct{} + +func (okDeleteAuthority) Reserve(context.Context) error { return nil } +func (okDeleteAuthority) NoLiveLease(context.Context) error { return nil } + +// commitSnapshot makes v hold one chunk at index 1 and a snapshot named +// name of it, through the kernel's own steps: Start, Begin, objects, Commit. +func commitSnapshot(t *testing.T, c *BCatalog, v VolumeRef, data []byte, name string) { + t.Helper() + ctx := context.Background() + s, err := c.Store(v) + if err != nil { + t.Fatal(err) + } + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + if _, err := layout.Start(ctx, s, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + if _, err := layout.RunBegin(ctx, s, me, "s1"); err != nil { + t.Fatal(err) + } + ch := layout.NameChunk(1, data) + if err := layout.EnsureObject(ctx, s, ch.Path(), data, "s1"); err != nil { + t.Fatal(err) + } + next := map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: ch}} + root, segs, err := layout.Build(next) + if err != nil { + t.Fatal(err) + } + for n, b := range segs { + if err := layout.EnsureObject(ctx, s, n.Path(), b, "s1"); err != nil { + t.Fatal(err) + } + } + rn, rb, err := layout.NameRoot(root) + if err != nil { + t.Fatal(err) + } + if err := layout.EnsureObject(ctx, s, rn.Path(), rb, "s1"); err != nil { + t.Fatal(err) + } + if _, err := layout.RunCommit(ctx, s, s, v.Name, me, layout.CommitRequest{Session: "s1", Next: next, Position: 1, Snapshot: name}); err != nil { + t.Fatal(err) + } +} + +func newRef(t *testing.T, name string) VolumeRef { + t.Helper() + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + return VolumeRef{Name: name, ID: id} +} + +// A restore target reads the source's chunk through its copied root; the +// source's snapshot cannot be deleted while the target depends on it; the +// target's delete releases it, and then the snapshot deletes. +func TestBCatalog_RestoreThenDeleteTheTarget(t *testing.T) { + ctx := context.Background() + c, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + src, tgt := newRef(t, "src"), newRef(t, "t") + if _, err := c.CreateVolume(ctx, src, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + data := []byte("source chunk") + commitSnapshot(t, c, src, data, "daily") + + th, err := c.Restore(ctx, src, "daily", tgt) + if err != nil { + t.Fatalf("restore: %v", err) + } + if th.Holder != "" || th.Current == nil { + t.Fatalf("target HEAD %+v; want unclaimed with the copied root", th) + } + ts, tr, err := c.open(tgt) + if err != nil { + t.Fatal(err) + } + img, err := tr.Open(ctx, *th.Current) + if err != nil { + t.Fatal(err) + } + got, err := img.Chunk(ctx, 1) + if err != nil || string(got.Data) != string(data) || got.Ref.OwnerID != src.ID { + t.Fatalf("target reads chunk 1: %+v %v; want the source's bytes", got, err) + } + if u, err := c.Usage(ctx, tgt); err != nil || u.ForeignChunks != 1 || u.OwnChunks != 0 { + t.Fatalf("target usage %+v %v", u, err) + } + if u, err := c.Usage(ctx, src); err != nil || u.Dependents != 1 || u.OwnChunks != 1 { + t.Fatalf("source usage %+v %v", u, err) + } + if _, err := c.Restore(ctx, src, "daily", tgt); err != nil { + t.Fatalf("restore again: %v; want a replay", err) + } + if _, err := c.DeleteSnapshot(ctx, src, "daily"); !errors.Is(err, layout.ErrHasDependents) { + t.Fatalf("delete a depended-on snapshot: %v; want ErrHasDependents", err) + } + + if err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err != nil { + t.Fatalf("delete the target: %v", err) + } + if h, _, err := ts.ReadHead(ctx); err != nil || h.State != layout.StateDeleted { + t.Fatalf("target HEAD after delete: %+v %v", h, err) + } + if objs, err := c.listObjects(ctx, tgt); err != nil || len(objs) != 0 { + t.Fatalf("target objects after delete: %v %v", objs, err) + } + if _, err := c.DeleteSnapshot(ctx, src, "daily"); err != nil { + t.Fatalf("delete the released snapshot: %v", err) + } + if v, ok, err := ts.ReadVolumeRecord(ctx); err != nil || !ok || v.ID != tgt.ID { + t.Fatalf("target VOLUME after delete: %+v %t %v; want kept", v, ok, err) + } +} + +// A snapshot of a restore target names the source's chunks, so it cannot +// itself be a restore source (dependency depth stays one). +func TestBCatalog_RestoreOfARestoreTargetIsRefused(t *testing.T) { + ctx := context.Background() + c, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + src, tgt, again := newRef(t, "src"), newRef(t, "t"), newRef(t, "t2") + if _, err := c.CreateVolume(ctx, src, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + commitSnapshot(t, c, src, []byte("x"), "daily") + if _, err := c.Restore(ctx, src, "daily", tgt); err != nil { + t.Fatal(err) + } + ts, _ := c.Store(tgt) + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + if _, err := layout.Start(ctx, ts, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + h, _, _ := ts.ReadHead(ctx) + if _, err := layout.RunBegin(ctx, ts, me, "s2"); err != nil { + t.Fatal(err) + } + img, _ := layout.NewReader("/blocks", tgt.Dir(), ts.Fetch) + im, _ := img.Open(ctx, *h.Current) + ref, _, _ := im.Resolve(ctx, 1) + prev := map[uint64]layout.Ref{1: ref} + root, segs, _ := layout.Build(prev) + for n, b := range segs { + if err := layout.EnsureObject(ctx, ts, n.Path(), b, "s2"); err != nil { + t.Fatal(err) + } + } + rn, rb, _ := layout.NameRoot(root) + if err := layout.EnsureObject(ctx, ts, rn.Path(), rb, "s2"); err != nil { + t.Fatal(err) + } + if _, err := layout.RunCommit(ctx, ts, ts, tgt.Name, me, layout.CommitRequest{Session: "s2", Prev: prev, Next: prev, Position: 2, Snapshot: "copy"}); err != nil { + t.Fatalf("snapshot of the target: %v", err) + } + if _, err := c.Restore(ctx, tgt, "copy", again); !errors.Is(err, layout.ErrForeignSource) { + t.Fatalf("restore from a snapshot naming another volume's chunks: %v; want ErrForeignSource", err) + } +} + +// A restore target that was never started still names the source's +// chunks: the operator's release of it is refused, and the source keeps its +// dependent. +func TestBCatalog_ReleaseOfAnUnstartedRestoreTargetIsRefused(t *testing.T) { + ctx := context.Background() + c, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + src, tgt := newRef(t, "src"), newRef(t, "t") + if _, err := c.CreateVolume(ctx, src, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + commitSnapshot(t, c, src, []byte("data"), "daily") + if _, err := c.Restore(ctx, src, "daily", tgt); err != nil { + t.Fatal(err) + } + if _, err := c.ReleaseTarget(ctx, src, tgt); !errors.Is(err, layout.ErrTargetLive) { + t.Fatalf("release of an unstarted restore target: %v; want ErrTargetLive", err) + } + if h, _, _ := c.ReadHead(ctx, src); len(h.Snapshots["daily"].Dependents) != 1 { + t.Fatalf("source dependents after the refused release: %+v", h.Snapshots["daily"].Dependents) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_crash_snapshot_test.go b/seaweed-block/core/frontend/chunkstore/catalog_crash_snapshot_test.go deleted file mode 100644 index 90b7c5efa0..0000000000 --- a/seaweed-block/core/frontend/chunkstore/catalog_crash_snapshot_test.go +++ /dev/null @@ -1,233 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "path" - "strings" - "sync" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" -) - -// errCrashed is what a filer call returns once the process that issued it -// is dead. -var errCrashed = errors.New("crashed") - -// crashFiler models a blockvolume killed in the middle of a catalog -// operation: at the chosen filer call it dies, before or after that call -// reaches the filer, and from then on no call of it reaches the filer, so -// none of its cleanup runs. Blob calls are not intercepted (snapshot create -// writes entries only). -type crashFiler struct { - manifestFilerBlobs - mu sync.Mutex - dead bool - match func(op, p string) bool // the call at which the process dies - after bool // the call reaches the filer, its reply is lost -} - -func (c *crashFiler) gate(op, p string) (pass, die bool) { - c.mu.Lock() - defer c.mu.Unlock() - if c.dead { - return false, false - } - if c.match(op, p) { - c.dead = true - return c.after, true - } - return true, false -} - -func (c *crashFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { - if pass, _ := c.gate("lookup", path.Join(dir, name)); !pass { - return nil, errCrashed - } - return c.manifestFilerBlobs.LookupEntry(ctx, dir, name) -} - -func (c *crashFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error { - pass, die := c.gate("create", path.Join(dir, e.GetName())) - if !pass { - return errCrashed - } - err := c.manifestFilerBlobs.CreateEntry(ctx, dir, e, oExcl) - if die { - return errCrashed - } - return err -} - -func (c *crashFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { - pass, die := c.gate("update", path.Join(dir, e.GetName())) - if !pass { - return errCrashed - } - err := c.manifestFilerBlobs.UpdateEntry(ctx, dir, e, expected) - if die { - return errCrashed - } - return err -} - -func (c *crashFiler) ListEntries(ctx context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) { - if pass, _ := c.gate("list", dir); !pass { - return nil, errCrashed - } - return c.manifestFilerBlobs.ListEntries(ctx, dir, prefix, startAfter, limit) -} - -func (c *crashFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { - pass, die := c.gate("delete", path.Join(dir, name)) - if !pass { - return errCrashed - } - err := c.manifestFilerBlobs.DeleteEntry(ctx, dir, name, expected) - if die { - return errCrashed - } - return err -} - -// TestCatalogRestartAfterAbandonedSnapshot: a snapshot create of s1 whose -// process dies at each of its filer steps (after the name record, after the -// intent, with the attempt create lost before or after it applied, after the -// create before the intent is dropped), then a catalog restarted over the -// same filer. Whatever the step: -// - the create never answers success unless its attempt entry was -// written; -// - the list shows s1 only if its attempt entry was written, and then as -// the snapshot of the cut HEAD, never a partial one; -// - a retry with the same request id completes s1, listed once; -// - a new snapshot of another name is taken and listed; -// - when s1 is abandoned unpublished, its name record still holds the name -// (another request gets snapshot_exists) and blocks volume delete -// (volume_has_snapshots), and deleting s1 settles it: the name is free -// and the volume delete completes. -func TestCatalogRestartAfterAbandonedSnapshot(t *testing.T) { - isName := func(p string) bool { return p == path.Join(catBase, "v1", snapNamesDir, "s1") } - isIntent := func(p string) bool { return strings.HasPrefix(p, path.Join(catBase, "v1", intentsDir)+"/") } - isAttempt := func(p string) bool { return isSnapPath(p, "v1", "s1") } - for _, tc := range []struct { - name string - op string - at func(string) bool - after bool - published bool // the attempt entry was written before the crash - }{ - {"after the name record", "create", isName, true, false}, - {"after the intent", "create", isIntent, true, false}, - {"attempt create lost before it applied", "create", isAttempt, false, false}, - {"attempt create applied, reply lost", "create", isAttempt, true, true}, - {"before the intent is dropped", "delete", isIntent, false, true}, - } { - t.Run(tc.name, func(t *testing.T) { - f, b, _, h := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: tc.after, - match: func(op, p string) bool { return op == tc.op && tc.at(p) }} - dying, err := NewCatalog(crashed, catBase) - if err != nil { - t.Fatal(err) - } - // A crash before the attempt entry is written cannot return success; - // once it is written the create has succeeded (the intent drop - // after it is best effort), whatever the caller then hears. - if _, err := dying.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err == nil && !tc.published { - t.Fatal("the create returned success although its process died before publishing") - } - crashed.mu.Lock() - died := crashed.dead - crashed.mu.Unlock() - if !died { - t.Fatalf("the create never reached the step %q", tc.name) - } - - c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) // the restarted process - if err != nil { - t.Fatal(err) - } - list := func() []SnapshotInfo { - t.Helper() - l, _, err := c.ListSnapshots(ctx, "v1", ListOptions{}) - if err != nil { - t.Fatal(err) - } - return l - } - switch l := list(); { - case !tc.published && len(l) != 0: - t.Fatalf("an unpublished snapshot is listed after the restart: %+v", l) - case tc.published && (len(l) != 1 || l[0].Name != "s1" || l[0].HeadGen != h.Gen || l[0].State != SnapActive): - t.Fatalf("after the restart the list is %+v; want s1 of HEAD gen %d, active", l, h.Gen) - } - - if !tc.published { - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "other"}, h); CodeOf(err) != CodeSnapshotExists { - t.Fatalf("another request for the abandoned name: %v; want snapshot_exists (the name record holds it)", err) - } - if _, err := c.DeleteVolume(ctx, "v1", nil); CodeOf(err) != CodeVolumeHasSnapshots { - t.Fatalf("volume delete with the abandoned name record: %v; want volume_has_snapshots", err) - } - } - - info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h) - if err != nil || info.Name != "s1" || info.HeadGen != h.Gen { - t.Fatalf("retry with the same request id after the restart: %+v %v", info, err) - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s2", RequestID: "r2"}, h); err != nil { - t.Fatalf("the next snapshot after the restart: %v", err) - } - if l := list(); len(l) != 2 || l[0].Name != "s1" || l[1].Name != "s2" { - t.Fatalf("after the retry and the next snapshot the list is %+v; want s1, s2 once each", l) - } - - for _, name := range []string{"s1", "s2"} { - if _, err := c.DeleteSnapshot(ctx, "v1", name); err != nil { - t.Fatalf("delete %s: %v", name, err) - } - } - if l := list(); len(l) != 0 { - t.Fatalf("after deleting both the list is %+v", l) - } - if res, err := c.DeleteVolume(ctx, "v1", nil); err != nil || !res.Completed { - t.Fatalf("volume delete after the snapshots are deleted: %+v %v", res, err) - } - }) - } -} - -// TestCatalogAbandonedUnpublishedSnapshotIsSettledByDelete: an abandoned, -// never-published s1 (the process died after its name record) is settled by -// deleting it without a retry: the name is then free for another request and -// the volume delete is no longer blocked by it. -func TestCatalogAbandonedUnpublishedSnapshotIsSettledByDelete(t *testing.T) { - f, b, _, h := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: true, - match: func(op, p string) bool { return op == "create" && p == path.Join(catBase, "v1", snapNamesDir, "s1") }} - dying, err := NewCatalog(crashed, catBase) - if err != nil { - t.Fatal(err) - } - if _, err := dying.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err == nil { - t.Fatal("the create returned success although its process died") - } - c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) - if err != nil { - t.Fatal(err) - } - if st, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting { - t.Fatalf("delete of the abandoned s1: %q %v", st, err) - } - if l, _, err := c.ListSnapshots(ctx, "v1", ListOptions{}); err != nil || len(l) != 0 { - t.Fatalf("list after settling: %+v %v", l, err) - } - if res, err := c.DeleteVolume(ctx, "v1", nil); err != nil || !res.Completed { - t.Fatalf("volume delete after settling the abandoned name: %+v %v", res, err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go b/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go deleted file mode 100644 index e8efff29a3..0000000000 --- a/seaweed-block/core/frontend/chunkstore/catalog_deadline_test.go +++ /dev/null @@ -1,193 +0,0 @@ -package chunkstore - -import ( - "context" - "fmt" - "strings" - "testing" - "time" -) - -// A snapshot or fork copy intent records its publication deadline, and the -// publishing create runs under a context bounded by that deadline (W5). -// The deadline is now metadata only: -// a sweep settles a dead attempt by a tombstone claim (catalog_tombstone). - -func TestCatalog_CopyIntentRecordsItsDeadline(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - t0 := time.Unix(1_800_000_000, 0) - c.SetClock(func() time.Time { return t0 }) - holdFirst(f, catBase+"/v1/snaps/s1/") - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r", SourceReadAt: t0}, h); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("held snapshot create: %v", err) - } - in := intentsOf(t, f, "v1") - if len(in) != 1 || in[0].DeadlineNs != t0.Add(DefaultOpDeadline).UnixNano() { - t.Fatalf("snapshot intent %+v; want deadline %d", in, t0.Add(DefaultOpDeadline).UnixNano()) - } - - f.deferCreate = nil - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s2", RequestID: "r2"}, h); err != nil { - t.Fatal(err) - } - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("held fork HEAD create: %v", err) - } - if fin := intentsOf(t, f, "v2"); len(fin) != 1 || fin[0].DeadlineNs != t0.Add(DefaultOpDeadline).UnixNano() { - t.Fatalf("fork intent %+v; want deadline %d", fin, t0.Add(DefaultOpDeadline).UnixNano()) - } -} - -func TestCatalog_PublishIsBoundedByTheDeadline(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - c.OpDeadline = 300 * time.Millisecond - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s0", RequestID: "r0"}, h); err != nil { - t.Fatal(err) - } - for _, tc := range []struct { - name, path string - run func() error - }{ - {"snapshot", catBase + "/v1/snaps/s1", func() error { - _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h) - return err - }}, - {"fork", catBase + "/v2/HEAD", func() error { - _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s0", Target: "v2", RequestID: "f"}) - return err - }}, - } { - stalled := tc.path - f.stallCreate = func(p string) bool { return p == stalled || strings.HasPrefix(p, stalled+"/") } - done := make(chan error, 1) - start := time.Now() - go func() { done <- tc.run() }() - select { - case err := <-done: - if CodeOf(err) != CodeOutcomeUnknown || time.Since(start) > 2*time.Second { - t.Fatalf("%s against a filer that never answers: %v after %v; want outcome_unknown by the deadline", tc.name, err, time.Since(start)) - } - case <-time.After(5 * time.Second): - t.Fatalf("%s: the publishing create outlived its deadline (still waiting after 5s)", tc.name) - } - f.stallCreate = nil - } -} - -// A delayed source read must not create a target, and an expired attempt -// after VOLUME must not create a copy intent, even one it later deletes. -func TestFork_ExpiredAttemptWritesNoNewMetadata(t *testing.T) { - for _, origin := range []string{OriginFork, OriginRestore} { - for _, stage := range []string{"source_read", "volume_written", "live"} { - t.Run(origin+"/"+stage, func(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - now := time.Unix(1800000000, 0) - c.SetClock(func() time.Time { return now }) - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h); err != nil { - t.Fatal(err) - } - start := now - volumeWrites, intentWrites := 0, 0 - f.afterLookup = func(p string) { - if stage == "source_read" && isSnapPath(p, "v1", "s1") { - now = start.Add(DefaultOpDeadline) - } - } - f.beforeCreate = func(p string) { - if p == catBase+"/v2/VOLUME" { - volumeWrites++ - if stage == "volume_written" { - now = start.Add(DefaultOpDeadline) - } - } - if strings.HasPrefix(p, catBase+"/v2/intents/") { - intentWrites++ - } - } - req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} - var err error - if origin == OriginFork { - _, err = c.Fork(ctx, req) - } else { - _, err = c.Restore(ctx, req) - } - f.afterLookup, f.beforeCreate = nil, nil - if stage == "live" { - if err != nil || volumeWrites != 1 || intentWrites != 1 { - t.Fatalf("live attempt: err=%v VOLUME=%d intents=%d", err, volumeWrites, intentWrites) - } - return - } - if CodeOf(err) != CodeDeadlineExceeded { - t.Fatalf("expired attempt: %v", err) - } - wantVolume := 0 - if stage == "volume_written" { - wantVolume = 1 - } - if volumeWrites != wantVolume || intentWrites != 0 { - t.Fatalf("expired attempt wrote VOLUME=%d intents=%d; want %d and 0", volumeWrites, intentWrites, wantVolume) - } - if _, err := f.LookupEntry(ctx, catBase+"/v2", headName); err == nil { - t.Fatal("expired attempt published HEAD") - } - if intents := intentsOf(t, f, "v2"); len(intents) != 0 { - t.Fatalf("expired attempt left intents: %+v", intents) - } - }) - } - } -} - -// The frozen flat snapshot forces the manifest-upgrade path to create an -// intent before uploading its segment; count creates, even if later removed. -func TestFork_ExpiredLegacyPreparationWritesNoIntent(t *testing.T) { - for _, origin := range []string{OriginFork, OriginRestore} { - for _, expired := range []bool{true, false} { - t.Run(fmt.Sprintf("%s/expired=%t", origin, expired), func(t *testing.T) { - f, c, r := preF4ForkFixture(t, false) - now := time.Unix(1800000000, 0) - start := now - c.SetClock(func() time.Time { return now }) - intents := 0 - f.beforeCreate = func(p string) { - if p == catBase+"/v3/VOLUME" && expired { - now = start.Add(DefaultOpDeadline) - } - if strings.HasPrefix(p, catBase+"/v3/intents/") { - intents++ - } - } - req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "legacy-deadline"} - var err error - if origin == OriginFork { - _, err = c.Fork(context.Background(), req) - } else { - _, err = c.Restore(context.Background(), req) - } - f.beforeCreate = nil - if expired { - if CodeOf(err) != CodeDeadlineExceeded || intents != 0 { - t.Fatalf("expired legacy attempt: err=%v intent creates=%d; want deadline and zero", err, intents) - } - if _, err := f.LookupEntry(context.Background(), catBase+"/v3", headName); err == nil { - t.Fatal("expired legacy attempt published HEAD") - } - } else { - if err != nil || intents != 2 { - t.Fatalf("live legacy attempt: err=%v intent creates=%d; want success and upgrade+copy intents", err, intents) - } - dst, err := NewChunkRemote(f, r.b, catBase+"/v3") - if err != nil { - t.Fatal(err) - } - assertLegacyImage(t, dst) - } - }) - } - } -} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go b/seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go deleted file mode 100644 index b1ee96ecd6..0000000000 --- a/seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go +++ /dev/null @@ -1,289 +0,0 @@ -package chunkstore - -import ( - "context" - "path" - "strings" - "testing" - - "google.golang.org/protobuf/proto" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" -) - -// Schedules where the filer holds an attempt's create and runs it after the -// attempt has returned (second review of #111, P1). The rule (W5): an -// attempt deletes only its own intent, and only once its own create is -// confirmed or can never apply; never another attempt's, even under the same -// request, since that attempt's create may still land. - -// holdFirst makes the filer hold the first create of p (p ending in "/": -// the first create under it). -func holdFirst(f *fakeFiler, p string) { - held := false - f.deferCreate = func(q string, _ *filerpb.Entry) bool { - if held || !(q == p || strings.HasSuffix(p, "/") && strings.HasPrefix(q, p)) { - return false - } - held = true - return true - } -} - -// holdFirstBehindAnother holds the first create of p and, in the same -// moment, lets another attempt of the same request write p (a copy of the -// held entry stamped with another attempt id). -func holdFirstBehindAnother(f *fakeFiler, p string) { - held := false - f.deferCreate = func(q string, e *filerpb.Entry) bool { - if q != p || held { - return false - } - held = true - other := proto.Clone(e).(*filerpb.Entry) - other.Extended["swb.attempt"] = []byte("0-00000000000000ff") - f.entries[q] = other - return true - } -} - -// gcRemove removes an entry, as GC does after a delete. -func gcRemove(f *fakeFiler, p string) { - f.mu.Lock() - delete(f.entries, p) - f.mu.Unlock() -} - -// assertKeysProtected fails unless every key is named by an intent of vol. -func assertKeysProtected(t *testing.T, f *fakeFiler, vol string, keys []string) { - t.Helper() - named := map[string]bool{} - for _, in := range intentsOf(t, f, vol) { - for _, k := range in.Keys { - named[k] = true - } - } - for _, k := range keys { - if !named[k] { - t.Fatalf("key %s of the late entry is named by no intent of %s: GC may delete it", k, vol) - } - } -} - -func lateSnapshotKeys(t *testing.T, f *fakeFiler, vol, name string) []string { - t.Helper() - dir := path.Join(catBase, vol, snapsDir) - e, err := f.LookupEntry(context.Background(), dir, name) - if err != nil { - t.Fatalf("the held create did not land: %v", err) - } - info, _, err := decodeSnap(path.Join(dir, name), e) - if err != nil { - t.Fatal(err) - } - return sortedKeysOf(info.Head(), "") -} - -func lateHeadKeys(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) []string { - t.Helper() - r, _ := NewChunkRemote(f, b, path.Join(catBase, vol)) - h, err := r.GetHead(context.Background()) - if err != nil { - t.Fatalf("the held HEAD create did not land: %v", err) - } - return sortedKeysOf(h, "") -} - -// Attempt A's snapshot create is held. Retry B of the same request takes -// over A's attempt path (the name record names it) and publishes there, -// deleting only B's intent. A's held insert can never land: the path is -// taken, and attempt paths are never removed, not even by DeleteSnapshot. -// A sweep then finds A's attempt published. -func TestCatalog_HeldSnapshotCreateKeepsItsIntent(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v1/snaps/s1/") - req := SnapshotRequest{Name: "s1", RequestID: "r"} - if _, err := c.CreateSnapshot(ctx, "v1", req, h); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("attempt A, create held: %v, want outcome_unknown", err) - } - a := intentsOf(t, f, "v1") - if len(a) != 1 { - t.Fatalf("attempt A left %d intents, want its own", len(a)) - } - attempt := path.Base(snapPath(t, f, "v1", "s1")) - if a[0].Holder != "snapshot:v1/s1/"+attempt { - t.Fatalf("intent holder %q, want it to name the attempt %s", a[0].Holder, attempt) - } - if info, err := c.CreateSnapshot(ctx, "v1", req, h); err != nil || info.State != SnapActive { - t.Fatalf("retry B: %+v %v", info, err) - } - if in := intentsOf(t, f, "v1"); len(in) != 1 || in[0].ID != a[0].ID { - t.Fatalf("after B: intents %+v, want only A's %s", in, a[0].ID) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - if n := f.releaseDeferredCreates(); n != 0 { - t.Fatalf("A's held insert landed (%d applied); its attempt path is held for good", n) - } - if claimed, err := c.AbortSnapshot(ctx, "v1", "s1", attempt); err != nil || claimed { - t.Fatalf("sweep over A's published attempt: claimed=%v %v; want published", claimed, err) - } -} - -// A sweep settles a dead attempt by claiming its path with an aborted -// tombstone: the late insert fails, the name reads as aborted until it is -// deleted, and then the name can be reused. -func TestCatalog_SweepTombstonesADeadSnapshotAttempt(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v1/snaps/s1/") - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("attempt with a held create: %v", err) - } - attempt := path.Base(snapPath(t, f, "v1", "s1")) - if claimed, err := c.AbortSnapshot(ctx, "v1", "s1", attempt); err != nil || !claimed { - t.Fatalf("sweep over the dead attempt: claimed=%v %v", claimed, err) - } - if n := f.releaseDeferredCreates(); n != 0 { - t.Fatalf("the dead attempt's late insert landed over the tombstone (%d applied)", n) - } - if again, err := c.AbortSnapshot(ctx, "v1", "s1", attempt); err != nil || !again { - t.Fatalf("a repeated sweep: claimed=%v %v; want the tombstone found", again, err) - } - for _, include := range []bool{false, true} { - if list, _, err := c.ListSnapshots(ctx, "v1", ListOptions{IncludeDeleting: include}); err != nil || len(list) != 0 { - t.Fatalf("list (includeDeleting=%v) shows the aborted attempt: %+v %v", include, list, err) - } - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotNotFound { - t.Fatalf("fork from the aborted attempt: %v; want snapshot_not_found", err) - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); CodeOf(err) != CodeSnapshotExists { - t.Fatalf("retry of the aborted request: %v; want snapshot_exists until the name is deleted", err) - } - if st, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting { - t.Fatalf("delete of the aborted name: %q %v", st, err) - } - info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r2"}, h) - if err != nil || info.State != SnapActive { - t.Fatalf("snapshot after the name was freed: %+v %v", info, err) - } - if p := snapPath(t, f, "v1", "s1"); path.Base(p) == attempt { - t.Fatal("the new snapshot reused the aborted attempt's path") - } -} - -// Another request holding the name refuses before any intent is written. -func TestCatalog_NameHeldByAnotherRequestWritesNoIntent(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - // Another request takes the name between this request's check and its - // name record create. - f.failCreate = func(p string) error { - if p != catBase+"/v1/"+snapNamesDir+"/s1" { - return nil - } - other, _ := nameRecordEntry(nameRecord{Format: snapFormat, VolumeID: "v1", Name: "s1", RequestID: "other", Attempt: "1-00000000000000aa"}) - f.entries[p] = other - return ErrExists - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); CodeOf(err) != CodeSnapshotExists { - t.Fatalf("name held by another request: %v, want snapshot_exists", err) - } - if in := intentsOf(t, f, "v1"); len(in) != 0 { - t.Fatalf("a refused name left %d intents", len(in)) - } -} - -// Fork: attempt A's HEAD create is held; retry B completes the fork and -// deletes only B's intent; a replay C deletes none. The target's HEAD is -// later removed; A's held create lands with its qualified keys protected. -func TestFork_HeldHeadCreateKeepsItsIntent(t *testing.T) { - f, b, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - p := catBase + "/v2/HEAD" - holdFirst(f, p) - req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} - if _, err := c.Fork(ctx, req); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("attempt A, HEAD create held: %v, want outcome_unknown", err) - } - a := intentsOf(t, f, "v2") - if len(a) != 1 { - t.Fatalf("attempt A left %d intents, want its own", len(a)) - } - if res, err := c.Fork(ctx, req); err != nil || res.Replayed { - t.Fatalf("retry B: %+v %v", res, err) - } - if res, err := c.Fork(ctx, req); err != nil || !res.Replayed { - t.Fatalf("replay C: %+v %v", res, err) - } - if in := intentsOf(t, f, "v2"); len(in) != 1 || in[0].ID != a[0].ID { - t.Fatalf("after B and C: intents %+v, want only A's %s (A's HEAD create is still held)", in, a[0].ID) - } - gcRemove(f, p) - if n := f.releaseDeferredCreates(); n != 1 { - t.Fatalf("A's held HEAD create applied %d times, want 1", n) - } - assertKeysProtected(t, f, "v2", lateHeadKeys(t, f, b, "v2")) -} - -// Fork: attempt A's HEAD create is held while another attempt writes HEAD. -// A reports the completed fork and keeps its own intent. -func TestFork_HeldHeadCreateBehindAnotherAttempt(t *testing.T) { - f, b, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - p := catBase + "/v2/HEAD" - holdFirstBehindAnother(f, p) - res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}) - if in := intentsOf(t, f, "v2"); len(in) != 1 { - t.Fatalf("attempt A (err %v) left %d intents; its held create needs its own", err, len(in)) - } - if err != nil || !res.Replayed || res.HeadGen != 1 { - t.Fatalf("attempt A behind another attempt: %+v %v, want the completed fork", res, err) - } - gcRemove(f, p) - if n := f.releaseDeferredCreates(); n != 1 { - t.Fatalf("A's held HEAD create applied %d times, want 1", n) - } - assertKeysProtected(t, f, "v2", lateHeadKeys(t, f, b, "v2")) -} - -// The filer's "already exists" answer to a fork's HEAD create: HEAD is there -// (only this request writes it), so the fork is complete and the attempt -// deletes its own intent. -func TestFork_RefusedHeadCreateDropsItsIntent(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} - if _, err := c.Fork(ctx, req); err != nil { - t.Fatal(err) - } - // HEAD is written by another attempt after this attempt finds it absent - // and before this attempt's create. - p := catBase + "/v2/HEAD" - head := f.entries[p] - gcRemove(f, p) - f.beforeCreate = func(q string) { - if path.Dir(q) == catBase+"/v2/intents" { - f.entries[p] = head - } - } - res, err := c.Fork(ctx, req) - if err != nil || !res.Replayed || res.HeadGen != 1 { - t.Fatalf("refused HEAD create: %+v %v, want the completed fork", res, err) - } - if in := intentsOf(t, f, "v2"); len(in) != 0 { - t.Fatalf("a refused HEAD create left %d intents", len(in)) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_interleave_test.go b/seaweed-block/core/frontend/chunkstore/catalog_interleave_test.go deleted file mode 100644 index 21a18e5169..0000000000 --- a/seaweed-block/core/frontend/chunkstore/catalog_interleave_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package chunkstore - -import ( - "context" - "encoding/json" - "path" - "strings" - "testing" - - "google.golang.org/protobuf/proto" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Interleaved sweeps and name reuse (review of #119 r4): every decision is -// taken from ONE read of the entry acted on, and a fork's or snapshot's -// success from re-reading the entry it tried to create. - -func abortedHeadEntry(t *testing.T) *filerpb.Entry { - t.Helper() - he, err := headEntry(storage.ChunkHead{Gen: 1, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadAborted}) - if err != nil { - t.Fatal(err) - } - return he -} - -// A sweep claims the fork's HEAD right after the attach gate's first read: -// the gate must not pass the aborted HEAD. -func TestEnsureVolume_OneHeadReadDecides(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - tomb := abortedHeadEntry(t) - done := false - f.afterLookup = func(p string) { - if p == catBase+"/v2/HEAD" && !done { - done = true - f.entries[p] = tomb // the sweep wins right after the first read - } - } - if _, err := c.EnsureVolume(ctx, "v2", catGeo); CodeOf(err) != CodeForkIncomplete { - t.Fatalf("attach with a sweep between reads: %v; want fork_incomplete", err) - } - f.afterLookup = nil -} - -// A sweep claims the fork's HEAD after the fork wrote its intent and before -// its HEAD create: the fork lost, so it must not report success. -func TestFork_LosesToASweepBeforeItsHeadCreate(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - tomb := abortedHeadEntry(t) - f.beforeCreate = func(p string) { - if path.Dir(p) == catBase+"/v2/intents" { - f.entries[catBase+"/v2/HEAD"] = tomb - } - } - if res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("fork that lost to a sweep: %+v %v; want target_exists", res, err) - } - if in := intentsOf(t, f, "v2"); len(in) != 0 { - t.Fatalf("a fork that lost to a tombstone left %d intents", len(in)) - } - f.beforeCreate = nil -} - -// The name is deleted and reused by another request between a snapshot's -// create and its completion: the caller gets its own attempt, not the name's -// new owner. -func TestCatalog_SnapshotCompletionReadsItsOwnAttempt(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - f.failCreateAfterApply = func(p string) error { - if isSnapPath(p, "v1", "s1") { - return errTransport // applied; the response is lost - } - return nil - } - reused := false - f.afterLookup = func(p string) { - if reused || !isSnapPath(p, "v1", "s1") { - return - } - reused = true - // Meanwhile: the name is deleted and taken by request rB, whose - // snapshot carries other labels. - attB := "1-00000000000000bb" - rec, _ := nameRecordEntry(nameRecord{Format: snapFormat, VolumeID: "v1", Name: "s1", RequestID: "rB", Attempt: attB}) - f.entries[catBase+"/v1/"+snapNamesDir+"/s1"] = rec - other := proto.Clone(f.entries[p]).(*filerpb.Entry) - var doc snapDoc - _ = json.Unmarshal(other.Content, &doc) - doc.RequestID, doc.Labels = "rB", map[string]string{"who": "b"} - other.Content, _ = json.Marshal(doc) - other.Name = attB - other.Extended[extReq] = []byte("rB") - f.entries[path.Join(path.Dir(p), attB)] = other - } - info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "rA", Labels: map[string]string{"who": "a"}}, h) - if err != nil || info.Labels["who"] != "a" { - t.Fatalf("completion after the name was reused: %+v %v; want the caller's own snapshot (labels who=a)", info, err) - } - f.afterLookup, f.failCreateAfterApply = nil, nil -} - -// A sweep's tombstone lands on the attempt path before the create: the -// create is refused for good and reported aborted, never as this attempt's. -func TestCatalog_SnapshotTombstoneIsNeverThisAttempt(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - f.beforeCreate = func(p string) { - if path.Dir(p) != catBase+"/v1/intents" { - return - } - re := f.entries[catBase+"/v1/"+snapNamesDir+"/s1"] - attempt := string(re.Extended[extAttempt]) - tomb, _ := c.abortedSnapEntry("v1", "s1", attempt) - f.entries[catBase+"/v1/snaps/s1/"+attempt] = tomb - } - _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h) - if CodeOf(err) != CodeSnapshotExists || !strings.Contains(err.Error(), "aborted") { - t.Fatalf("create over its own attempt's tombstone: %v; want the aborted refusal", err) - } - if in := intentsOf(t, f, "v1"); len(in) != 0 { - t.Fatalf("an attempt that lost to a tombstone left %d intents", len(in)) - } - f.beforeCreate = nil -} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_replay_deleting_test.go b/seaweed-block/core/frontend/chunkstore/catalog_replay_deleting_test.go deleted file mode 100644 index ca695c8c45..0000000000 --- a/seaweed-block/core/frontend/chunkstore/catalog_replay_deleting_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package chunkstore - -import ( - "context" - "path" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" -) - -// TestCatalogReplayOfASnapshotBeingDeletedIsNotSuccess: s1 is created by -// request r1, then deleted by a process that dies after marking it deleting -// and before freeing its name (the name record still names r1's attempt). -// A retry of r1, through a restarted catalog, must not answer success for -// the snapshot being deleted, neither from the replay check nor from the -// create: both refuse it as snapshot_deleting, and the snapshot stays -// deleting and unlisted. -func TestCatalogReplayOfASnapshotBeingDeletedIsNotSuccess(t *testing.T) { - f, b, c, h := catalogFixture(t) - ctx := context.Background() - req := SnapshotRequest{Name: "s1", RequestID: "r1"} - if _, err := c.CreateSnapshot(ctx, "v1", req, h); err != nil { - t.Fatal(err) - } - - nameRecord := path.Join(catBase, "v1", snapNamesDir, "s1") - crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, - match: func(op, p string) bool { return op == "delete" && p == nameRecord }} - dying, err := NewCatalog(crashed, catBase) - if err != nil { - t.Fatal(err) - } - if _, err := dying.DeleteSnapshot(ctx, "v1", "s1"); err == nil { - t.Fatal("the delete returned success although its process died before freeing the name") - } - if _, err := f.LookupEntry(ctx, path.Dir(nameRecord), path.Base(nameRecord)); err != nil { - t.Fatalf("the name record should still exist after the crash: %v", err) - } - - r, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) // the restarted process - if err != nil { - t.Fatal(err) - } - if info, replayed, err := r.SnapshotReplay(ctx, "v1", req); replayed || CodeOf(err) != CodeSnapshotDeleting { - t.Errorf("the replay check of a snapshot being deleted: %+v replayed %v, %v; want snapshot_deleting", info, replayed, err) - } - if info, err := r.CreateSnapshot(ctx, "v1", req, h); CodeOf(err) != CodeSnapshotDeleting { - t.Errorf("a retry of the create of a snapshot being deleted: %+v, %v; want snapshot_deleting", info, err) - } - if l, _, err := r.ListSnapshots(ctx, "v1", ListOptions{}); err != nil || len(l) != 0 { - t.Fatalf("the snapshot being deleted is listed: %+v %v", l, err) - } - if l, _, err := r.ListSnapshots(ctx, "v1", ListOptions{IncludeDeleting: true}); err != nil || len(l) != 1 || l[0].State != SnapDeleting { - t.Fatalf("the snapshot must stay deleting: %+v %v", l, err) - } -} - -// peerPublishFiler models a peer (an earlier attempt of the same request) -// that, just before this create writes the attempt entry, publishes that -// same attempt and has it deleted: the create's initial replay check saw the -// attempt unpublished, and its exclusive create then finds the peer's entry, -// now deleting. -type peerPublishFiler struct { - manifestFilerBlobs - attemptDir string - peer func(ctx context.Context, dir string, e *filerpb.Entry) - done bool -} - -func (p *peerPublishFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error { - if !p.done && dir == p.attemptDir { - p.done = true - p.peer(ctx, dir, e) - } - return p.manifestFilerBlobs.CreateEntry(ctx, dir, e, oExcl) -} - -// TestCatalogCreateFindingItsAttemptDeletingIsNotSuccess: r1's first attempt -// at s1 died after its name record. A retry of r1 passes the replay check -// (the attempt is unpublished) and, as it writes the attempt entry, a peer -// with the same request publishes that attempt and deletes it. The retry's -// exclusive create finds the peer's entry, now deleting: it must refuse it -// as snapshot_deleting, not answer success. -func TestCatalogCreateFindingItsAttemptDeletingIsNotSuccess(t *testing.T) { - f, b, _, h := catalogFixture(t) - ctx := context.Background() - req := SnapshotRequest{Name: "s1", RequestID: "r1"} - nameRecord := path.Join(catBase, "v1", snapNamesDir, "s1") - crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: true, - match: func(op, p string) bool { return op == "create" && p == nameRecord }} - dying, err := NewCatalog(crashed, catBase) - if err != nil { - t.Fatal(err) - } - if _, err := dying.CreateSnapshot(ctx, "v1", req, h); err == nil { - t.Fatal("the first attempt returned success although its process died after the name record") - } - - inner := manifestFilerBlobs{f, gcBlobs{b}} - peer, err := NewCatalog(inner, catBase) - if err != nil { - t.Fatal(err) - } - pf := &peerPublishFiler{manifestFilerBlobs: inner, attemptDir: path.Join(catBase, "v1", snapsDir, "s1")} - pf.peer = func(ctx context.Context, dir string, e *filerpb.Entry) { - if err := inner.CreateEntry(ctx, dir, e, true); err != nil { - t.Errorf("the peer's publish of the same attempt: %v", err) - return - } - if st, err := peer.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting { - t.Errorf("the peer's delete: %q %v", st, err) - } - } - r, err := NewCatalog(pf, catBase) - if err != nil { - t.Fatal(err) - } - if info, replayed, err := r.SnapshotReplay(ctx, "v1", req); err != nil || replayed { - t.Fatalf("before the retry the replay check must see the attempt unpublished: %+v %v %v", info, replayed, err) - } - info, err := r.CreateSnapshot(ctx, "v1", req, h) - if !pf.done { - t.Fatal("the retry never reached the exclusive create of its attempt") - } - if CodeOf(err) != CodeSnapshotDeleting { - t.Fatalf("the retry found its attempt deleting: %+v, %v; want snapshot_deleting", info, err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go deleted file mode 100644 index b3fe22a6f5..0000000000 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package chunkstore - -import ( - "context" - "crypto/sha256" - "errors" - "sort" - "strings" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -var errTransport = errors.New("fake: transport error") - -func sha256Of(b []byte) [32]byte { return sha256.Sum256(b) } - -func intentsOf(t *testing.T, f *fakeFiler, vol string) []storage.ChunkIntent { - t.Helper() - r, _ := NewChunkRemote(f, newFakeBlobs(), catBase+"/"+vol) - got, err := r.ListIntents(context.Background()) - if err != nil { - t.Fatal(err) - } - return got -} - -func sortedKeysOf(h storage.ChunkHead, qualify string) []string { - var out []string - for _, k := range headKeys(h) { - if qualify != "" && !strings.HasPrefix(k, "@") { - k = "@" + qualify + "/" + k - } - out = append(out, k) - } - sort.Strings(out) - return out -} - -func sameStrings(a, b []string) bool { - sort.Strings(a) - sort.Strings(b) - return strings.Join(a, "\x00") == strings.Join(b, "\x00") -} - -// An uncertain snapshot create keeps the intent that protects the -// snapshot's keys (review of #111, P1). A retry with the same -// request id publishes the snapshot and deletes only its own intent: from -// the catalog's view the first create may still land, so its intent stays -// (W5 rule; second review). -func TestCatalog_SnapshotUncertainCreateKeepsIntent(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - f.failCreate = func(p string) error { - if isSnapPath(p, "v1", "s1") { - return errTransport - } - return nil - } - _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h) - if CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("uncertain create: %v, want outcome_unknown", err) - } - in := intentsOf(t, f, "v1") - if len(in) != 1 || !sameStrings(in[0].Keys, sortedKeysOf(h, "")) { - t.Fatalf("after an uncertain create the intent must still protect the snapshot's keys: %+v", in) - } - f.failCreate = nil - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatalf("retry: %v", err) - } - if got := intentsOf(t, f, "v1"); len(got) != 1 || got[0].ID != in[0].ID { - t.Fatalf("after the retry: intents %+v, want only the first attempt's %s", got, in[0].ID) - } -} - -// A create that applied but lost its response is confirmed by the re-read. -func TestCatalog_SnapshotAppliedResponseLostIsConfirmed(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - f.failCreateAfterApply = func(p string) error { - if isSnapPath(p, "v1", "s1") { - return errTransport - } - return nil - } - info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h) - if err != nil || info.HeadGen != h.Gen { - t.Fatalf("applied create with a lost response: %+v %v", info, err) - } - if in := intentsOf(t, f, "v1"); len(in) != 0 { - t.Fatalf("a confirmed snapshot left %d intents", len(in)) - } -} - -// The same for the fork's HEAD create, with the qualified keys protected in -// the target. -func TestFork_UncertainHeadCreateKeepsIntent(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - f.failCreate = func(p string) error { - if p == catBase+"/v2/HEAD" { - return errTransport - } - return nil - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("uncertain HEAD create: %v, want outcome_unknown", err) - } - in := intentsOf(t, f, "v2") - if len(in) != 1 || !sameStrings(in[0].Keys, sortedKeysOf(h, "v1")) { - t.Fatalf("after an uncertain HEAD create the intent must still protect the qualified keys: %+v", in) - } - f.failCreate = nil - res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}) - if err != nil || res.Replayed { - t.Fatalf("retry: %+v %v", res, err) - } - if got := intentsOf(t, f, "v2"); len(got) != 1 || got[0].ID != in[0].ID { - t.Fatalf("after the retry: intents %+v, want only the first attempt's %s", got, in[0].ID) - } - - // Applied, response lost: confirmed by the re-read. - f.failCreateAfterApply = func(p string) error { - if p == catBase+"/v3/HEAD" { - return errTransport - } - return nil - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "g"}); err != nil { - t.Fatalf("applied HEAD create with a lost response: %v", err) - } - if in := intentsOf(t, f, "v3"); len(in) != 0 { - t.Fatalf("a confirmed fork left %d intents", len(in)) - } -} - -// An incomplete fork resumes only onto the image its first attempt bound, -// and a request id reused with other parameters is refused (P1). -func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) { - f, b, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s2", RequestID: "r2"}, h); err != nil { - t.Fatal(err) - } - f.failCreate = func(p string) error { - if p == catBase+"/v2/HEAD" { - return errTransport - } - return nil - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("first attempt: %v", err) - } - f.failCreate = nil - - // The same request id with another snapshot is refused. - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("request id reused for another snapshot: %v, want target_exists", err) - } - - // Forks do not hold their parent: the delete goes through while the - // fork is incomplete, and the image binding below guards the retry. - // s1 is deleted and recreated over a newer source image. - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { // frees the name - t.Fatal(err) - } - r1, _ := NewChunkRemote(f, b, catBase+"/v1") - if err := r1.Put(ctx, "chunks/e1/c5/new", chunkBytes(0x55)); err != nil { - t.Fatal(err) - } - next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 99, Chunks: map[uint64]storage.ChunkRef{}} - for k, v := range h.Chunks { - next.Chunks[k] = v - } - next.Chunks[5] = storage.ChunkRef{Key: "chunks/e1/c5/new", SHA256: sha256Of(chunkBytes(0x55))} - next, ids, err := r1.PrepareManifest(ctx, h, next, h.ChunkBytes) - if err != nil { - t.Fatal(err) - } - gen, err := r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 1}, next) - if err != nil { - t.Fatal(err) - } - next.Gen = gen - for _, id := range ids { - if err := r1.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-new"}, next); err != nil { - t.Fatal(err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("resume after the snapshot changed image: %v, want target_exists", err) - } - if _, err := f.LookupEntry(ctx, catBase+"/v2", "HEAD"); err == nil { - t.Fatal("a fork resumed onto another image and wrote HEAD") - } -} - -// A completed fork replays its recorded result without reading the source: -// after the source snapshot is deleting, and after the target advanced (P2). -func TestFork_CompletedReplayIndependentOfSource(t *testing.T) { - f, b, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - first, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}) - if err != nil { - t.Fatal(err) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - again, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}) - if err != nil || !again.Replayed { - t.Fatalf("replay after the source snapshot started deleting: %+v %v", again, err) - } - again.Replayed = false - if again != first { - t.Fatalf("replayed %+v, recorded %+v", again, first) - } - // The target's holder advances HEAD; the replay still reports the fork. - r2, _ := NewChunkRemote(f, b, catBase+"/v2") - cur, _ := r2.GetHead(ctx) - adv := cur - adv.Epoch, adv.Holder, adv.RemoteLSN = 1, "host-2", 50 - if _, err := r2.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, adv); err != nil { - t.Fatal(err) - } - later, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}) - if err != nil || !later.Replayed || later.HeadGen != 1 || later.RemoteLSN != first.RemoteLSN || later.SourceGen != first.SourceGen { - t.Fatalf("replay after the target advanced: %+v %v", later, err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go deleted file mode 100644 index 0a93987366..0000000000 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ /dev/null @@ -1,677 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/json" - "path" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -const catBase = "/swblock/chunks" - -var catGeo = Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} - -// publishSource writes chunks for vol and installs a HEAD (epoch 1, -// remote_lsn 42) over the current one (the initial HEAD the VOLUME entry -// came with, if any) through the real ChunkRemote; it returns the HEAD. -func publishSource(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string, chunks map[uint64][]byte) storage.ChunkHead { - t.Helper() - ctx := context.Background() - r, err := NewChunkRemote(f, b, path.Join(catBase, vol)) - if err != nil { - t.Fatal(err) - } - h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} - for idx, data := range chunks { - key := "chunks/e1/c" + string(rune('0'+idx)) + "/k" - if err := r.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} - } - cur, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - h, intents, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) - if err != nil { - t.Fatal(err) - } - gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h) - if err != nil { - t.Fatal(err) - } - h.Gen = gen - for _, id := range intents { - if err := r.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - return h -} - -// snapPath is the attempt path the name record of vol/name points at. -func snapPath(t *testing.T, f *fakeFiler, vol, name string) string { - t.Helper() - e, err := f.LookupEntry(context.Background(), path.Join(catBase, vol, snapNamesDir), name) - if err != nil { - t.Fatalf("name record %s/%s: %v", vol, name, err) - } - return path.Join(catBase, vol, snapsDir, name, string(e.Extended[extAttempt])) -} - -// isSnapPath reports whether p is an attempt path of vol/name. -func isSnapPath(p, vol, name string) bool { - return strings.HasPrefix(p, path.Join(catBase, vol, snapsDir, name)+"/") -} - -func newCat(t *testing.T, f *fakeFiler) *Catalog { - t.Helper() - c, err := NewCatalog(f, catBase) - if err != nil { - t.Fatal(err) - } - return c -} - -func chunkBytes(fill byte) []byte { - return bytes.Repeat([]byte{fill}, int(catGeo.ChunkBlocks)*int(catGeo.BlockSize)) -} - -func catalogFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) { - t.Helper() - f, b := newFakeFiler(), newFakeBlobs() - c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) - if err != nil { - t.Fatal(err) - } - if _, err := c.EnsureVolume(context.Background(), "v1", catGeo); err != nil { - t.Fatal(err) - } - h := publishSource(t, f, b, "v1", map[uint64][]byte{0: chunkBytes(0x10), 3: chunkBytes(0x13)}) - return f, b, c, h -} - -func assertNoFilerChunks(t *testing.T, f *fakeFiler) { - t.Helper() - for _, e := range f.allWritten() { - if len(e.Chunks) != 0 { - t.Fatalf("entry %q written with filer chunks", e.Name) - } - } -} - -func TestCatalog_SnapshotCreateExclusive(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - s1, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req-a", Labels: map[string]string{"agent.step": "npm-ci"}}, h) - if err != nil { - t.Fatal(err) - } - if s1.Replayed || s1.HeadGen != h.Gen || s1.HeadEpoch != 1 || s1.CutLSN != 42 || s1.ChunkCount != 2 || s1.State != SnapActive || s1.Consistency != "crash" { - t.Fatalf("created %+v", s1) - } - again, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req-a"}, h) - if err != nil || !again.Replayed || again.HeadGen != s1.HeadGen { - t.Fatalf("same request id: %+v %v, want a replay", again, err) - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req-b"}, h); CodeOf(err) != CodeSnapshotExists { - t.Fatalf("other request id: %v, want snapshot_exists", err) - } - for _, bad := range []string{"", ".hidden", "HEAD", "snaps", "a/b", strings.Repeat("x", 129)} { - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: bad, RequestID: "r"}, h); CodeOf(err) != CodeInvalidName { - t.Errorf("name %q: %v, want invalid_name", bad, err) - } - } - assertNoFilerChunks(t, f) - // The stored HEAD copy is byte-for-byte the HEAD document. - sp := snapPath(t, f, "v1", "s1") - e, _ := f.LookupEntry(ctx, path.Dir(sp), path.Base(sp)) - var doc snapDoc - if err := json.Unmarshal(e.Content, &doc); err != nil { - t.Fatal(err) - } - headEnt, _ := f.LookupEntry(ctx, catBase+"/v1", "HEAD") - if !bytes.Equal(doc.Head, headEnt.Content) { - t.Fatal("snapshot's head is not the HEAD document") - } -} - -func TestCatalog_SnapshotEntryNeverCarriesChunks(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - assertNoFilerChunks(t, f) - sp := snapPath(t, f, "v1", "s1") - f.mu.Lock() - f.entries[sp].Chunks = []*filerpb.FileChunk{{FileId: "3,01"}} - f.mu.Unlock() - if _, _, err := c.ListSnapshots(ctx, "v1", ListOptions{}); err == nil || CodeOf(err) == CodeSnapshotNotFound { - t.Fatalf("a snapshot entry with filer chunks listed: %v", err) - } -} - -func TestCatalog_ListPagesAndFilters(t *testing.T) { - _, _, c, h := catalogFixture(t) - ctx := context.Background() - for _, n := range []string{"a1", "a2", "b1", "b2", "b3"} { - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: n, RequestID: n}, h); err != nil { - t.Fatal(err) - } - } - if _, err := c.DeleteSnapshot(ctx, "v1", "b2"); err != nil { - t.Fatal(err) - } - names := func(s []SnapshotInfo) string { - var out []string - for _, x := range s { - out = append(out, x.Name) - } - return strings.Join(out, ",") - } - page, next, err := c.ListSnapshots(ctx, "v1", ListOptions{Limit: 2}) - if err != nil || names(page) != "a1,a2" || next != "a2" { - t.Fatalf("page 1: %s next %q %v", names(page), next, err) - } - page, next, _ = c.ListSnapshots(ctx, "v1", ListOptions{Limit: 2, StartAfter: next}) - if names(page) != "b1,b3" || next != "b3" { - t.Fatalf("page 2 (deleting b2 skipped): %s next %q", names(page), next) - } - page, next, _ = c.ListSnapshots(ctx, "v1", ListOptions{Limit: 2, StartAfter: next}) - if names(page) != "" || next != "" { - t.Fatalf("page 3: %s next %q", names(page), next) - } - // A deleted snapshot no longer holds its name, so even includeDeleting - // does not list it (its attempt path stays for GC). - page, _, _ = c.ListSnapshots(ctx, "v1", ListOptions{Prefix: "b", IncludeDeleting: true}) - if names(page) != "b1,b3" { - t.Fatalf("prefix b with deleting: %s, want the deleted b2 gone with its name", names(page)) - } - if page, _, err := c.ListSnapshots(ctx, "v9", ListOptions{}); err != nil || len(page) != 0 { - t.Fatalf("volume without snapshots: %v %v", page, err) - } - vols, err := c.ListVolumes(ctx) - if err != nil { - t.Fatal(err) - } - _ = vols // the fake filer has no directory entries; the real filer is covered by the integration test -} - -func TestCatalog_DeleteMarksThenIdempotent(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - sp := snapPath(t, f, "v1", "s1") - before, _ := f.LookupEntry(ctx, path.Dir(sp), path.Base(sp)) - f.mu.Lock() - deletesBefore := f.deletes - f.mu.Unlock() - st, err := c.DeleteSnapshot(ctx, "v1", "s1") - if err != nil || st != SnapDeleting { - t.Fatalf("delete: %q %v", st, err) - } - after, _ := f.LookupEntry(ctx, path.Dir(sp), path.Base(sp)) - if !bytes.Equal(before.Content, after.Content) || string(after.Extended[extSnapState]) != SnapDeleting || len(after.Extended[extSnapDeletedNs]) == 0 { - t.Fatal("delete must only mark the attempt entry (content unchanged, state deleting, deleted_ns set)") - } - // The name is freed (its record removed); the attempt path stays. - if _, err := f.LookupEntry(ctx, catBase+"/v1/"+snapNamesDir, "s1"); err == nil { - t.Fatal("delete left the name record: the name is not freed") - } - if st, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapAbsent { - t.Fatalf("repeated delete: %q %v, want absent (the name is free)", st, err) - } - if st, err := c.DeleteSnapshot(ctx, "v1", "nope"); err != nil || st != SnapAbsent { - t.Fatalf("delete of a missing snapshot: %q %v", st, err) - } - f.mu.Lock() - removed := f.deletes - deletesBefore - f.mu.Unlock() - if removed != 1 { - t.Fatalf("DeleteSnapshot removed %d entries; it must remove only the name record", removed) - } -} - -func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) { - f, b, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - intentsAtHead := -1 - f.beforeCreate = func(p string) { - if p == catBase+"/v2/HEAD" { - intentsAtHead = 0 - for k := range f.entries { - if strings.HasPrefix(k, catBase+"/v2/intents/") { - intentsAtHead++ - } - } - } - } - res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"}) - if err != nil { - t.Fatal(err) - } - if intentsAtHead != 1 { - t.Fatalf("intents in v2 when its HEAD was written: %d, want 1", intentsAtHead) - } - if got, _ := f.ListEntries(ctx, catBase+"/v2/intents", "", "", 0); len(got) != 0 { - t.Fatalf("fork left %d intents", len(got)) - } - r2, _ := NewChunkRemote(f, b, catBase+"/v2") - head, err := r2.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if head.Gen != 1 || head.Epoch != 0 || head.Holder != "" || head.RemoteLSN != 42 || len(head.Chunks) != 2 { - t.Fatalf("fork HEAD %+v: want gen 1, epoch 0, no holder, the snapshot's remote_lsn 42", head) - } - for idx, ref := range head.Chunks { - src := h.Chunks[idx] - if ref.Key != qualifyManifestKey("v1", src.Key) || ref.SHA256 != src.SHA256 { - t.Fatalf("chunk %d ref %+v, want @v1/%s with the same hash", idx, ref, src.Key) - } - } - if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 1 || res.ChunkCount != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed { - t.Fatalf("result %+v", res) - } - v, ok, err := c.ReadVolume(ctx, "v2") - if err != nil || !ok || v.Origin != OriginFork || v.Geometry != catGeo || v.Parent == nil || v.Parent.VolumeID != "v1" || v.Parent.Snapshot != "s1" || v.Parent.Gen != h.Gen { - t.Fatalf("fork VOLUME %+v %v %v", v, ok, err) - } - again, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"}) - if err != nil || !again.Replayed { - t.Fatalf("retried fork: %+v %v", again, err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-2"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("fork onto an existing volume: %v, want target_exists", err) - } - assertNoFilerChunks(t, f) -} - -func TestFork_ForkOfForkKeepsOriginalOwner(t *testing.T) { - f, b, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f1"}); err != nil { - t.Fatal(err) - } - r2, _ := NewChunkRemote(f, b, catBase+"/v2") - h2, _ := r2.GetHead(ctx) - if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "t1", RequestID: "r2"}, h2); err != nil { - t.Fatal(err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v2", Snapshot: "t1", Target: "v3", RequestID: "f2"}); err != nil { - t.Fatal(err) - } - r3, _ := NewChunkRemote(f, b, catBase+"/v3") - h3, _ := r3.GetHead(ctx) - for idx, ref := range h3.Chunks { - if ref.Key != qualifyManifestKey("v1", h.Chunks[idx].Key) { - t.Fatalf("second-level fork chunk %d names %q, want the original owner @v1/%s", idx, ref.Key, h.Chunks[idx].Key) - } - if got, err := r3.Get(ctx, ref.Key); err != nil || sha256.Sum256(got) != ref.SHA256 { - t.Fatalf("v3 reads chunk %d through its ref: %v", idx, err) - } - } -} - -func TestFork_RefusalsAndDeadline(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "nope", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotNotFound { - t.Fatalf("fork of a missing snapshot: %v", err) - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "gone", RequestID: "g"}, h); err != nil { - t.Fatal(err) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "gone"); err != nil { - t.Fatal(err) - } - // Deleting frees the name: a fork of it finds no snapshot. - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "gone", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotNotFound { - t.Fatalf("fork of a deleted snapshot: %v, want snapshot_not_found", err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "../x", RequestID: "f"}); CodeOf(err) != CodeInvalidName { - t.Fatalf("fork onto a non-plain volume id: %v", err) - } - // The clock passes OpDeadline between reading the snapshot and the HEAD write. - start := time.Unix(1000, 0) - calls := 0 - c.SetClock(func() time.Time { - calls++ - if calls > 2 { - return start.Add(DefaultOpDeadline + time.Second) - } - return start - }) - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v4", RequestID: "late"}); CodeOf(err) != CodeDeadlineExceeded { - t.Fatalf("late fork: %v, want deadline_exceeded", err) - } - if _, err := f.LookupEntry(ctx, catBase+"/v4", "HEAD"); err == nil { - t.Fatal("a fork past its deadline wrote a HEAD") - } - c.SetClock(time.Now) - // A retry of the expired attempt succeeds under a fresh deadline. - if res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v4", RequestID: "late"}); err != nil || res.Replayed { - t.Fatalf("retry after the late attempt: %+v %v", res, err) - } - // A fork whose VOLUME is written but HEAD is not refuses to attach. - s1, err := c.readSnap(ctx, "v1", "s1") - if err != nil { - t.Fatal(err) - } - digest, _ := headDigest(s1.Head()) - vol := VolumeInfo{Format: volumeFormat, VolumeID: "v5", Geometry: catGeo, Origin: OriginFork, Parent: &Parent{VolumeID: "v1", Snapshot: "s1", Gen: h.Gen}, - Fork: &ForkRecord{RequestID: "crashed", Source: "v1", Snapshot: "s1", SourceGen: h.Gen, HeadSHA256: digest, RemoteLSN: 42, ChunkCount: 2, QualifiedRefs: 2}} - ve, _ := volumeEntry(vol, "crashed") - if err := f.CreateEntry(ctx, catBase+"/v5", ve, true); err != nil { - t.Fatal(err) - } - if _, err := c.EnsureVolume(ctx, "v5", catGeo); CodeOf(err) != CodeForkIncomplete { - t.Fatalf("attach of an incomplete fork: %v, want fork_incomplete", err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v5", RequestID: "crashed"}); err != nil { - t.Fatalf("retry completes the crashed fork: %v", err) - } - if _, err := c.EnsureVolume(ctx, "v5", catGeo); err != nil { - t.Fatalf("attach after the fork completed: %v", err) - } - if _, err := c.EnsureVolume(ctx, "v5", Geometry{NumBlocks: 128, BlockSize: 4096, ChunkBlocks: 8}); CodeOf(err) != CodeGeometryMismatch { - t.Fatalf("attach with other geometry: %v, want geometry_mismatch", err) - } -} - -// End to end over the walstore chunk layer: a fork attached as a fresh host -// reads exactly the snapshot's image, lazily, through the owner-qualified -// refs; its own first cut writes only into its own keys/. -func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) { - ctx := context.Background() - const blocks, chunkBlocks = 64, 8 - f, b := newFakeFiler(), newFakeBlobs() - c := newCat(t, f) - geo := Geometry{NumBlocks: blocks, BlockSize: 4096, ChunkBlocks: chunkBlocks} - dir := t.TempDir() - attach := func(vol string, fresh bool, epoch uint64) (*storage.WALStore, storage.ChunkLayer) { - if _, err := c.EnsureVolume(ctx, vol, geo); err != nil && !fresh { - t.Fatal(err) - } - p := filepath.Join(dir, vol) - s, err := storage.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks}) - if err != nil { - t.Fatal(err) - } - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - r, _ := NewChunkRemote(f, b, path.Join(catBase, vol)) - cfg := storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh} - if fresh { - // This low-level fixture bypasses the provider: perform the same - // takeover and durable frontier seed before attaching its layer. - head, err := storage.ClaimChunkHead(ctx, r, cfg) - if err != nil { - t.Fatal(err) - } - if err := s.SeedChunkFrontier(head.RemoteLSN); err != nil { - t.Fatal(err) - } - cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch} - } - l, err := storage.AttachChunkLayer(s, r, cfg) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = s.Close() }) - return s, l - } - src, layer := attach("v1", true, 1) // a new, empty source volume - want := map[uint32][]byte{} - for _, lba := range []uint32{0, 9, 17, 63} { - want[lba] = bytes.Repeat([]byte{byte(lba + 1)}, 4096) - if _, err := src.Write(lba, want[lba]); err != nil { - t.Fatal(err) - } - } - cut, err := layer.Cut(ctx) - if err != nil { - t.Fatal(err) - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, cut.Head); err != nil { - t.Fatal(err) - } - // The source keeps writing after the snapshot; the fork must not see it. - if _, err := src.Write(9, bytes.Repeat([]byte{0xee}, 4096)); err != nil { - t.Fatal(err) - } - if _, err := layer.Cut(ctx); err != nil { - t.Fatal(err) - } - fork, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}) - if err != nil { - t.Fatal(err) - } - dst, dlayer := attach("v2", true, 1) - dst.AdvanceFrontier(fork.RemoteLSN) // the fork's log continues from the copied remote_lsn (W4b's job in production) - zero := make([]byte, 4096) - for lba := uint32(0); lba < blocks; lba++ { - got, err := dst.Read(lba) - if err != nil { - t.Fatalf("fork read %d: %v", lba, err) - } - exp, ok := want[lba] - if !ok { - exp = zero - } - if !bytes.Equal(got, exp) { - t.Fatalf("fork block %d = %x..., want the snapshot's %x...", lba, got[:2], exp[:2]) - } - } - keysBefore, _ := f.ListEntries(ctx, catBase+"/v1/keys", "", "", 0) - if _, err := dst.Write(40, bytes.Repeat([]byte{0x40}, 4096)); err != nil { - t.Fatal(err) - } - r2, err := dlayer.Cut(ctx) - if err != nil { - t.Fatalf("fork's first cut: %v", err) - } - if r2.Head.Epoch != 1 || r2.Head.RemoteLSN < 1 { - t.Fatalf("fork's first HEAD %+v", r2.Head) - } - keysAfter, _ := f.ListEntries(ctx, catBase+"/v1/keys", "", "", 0) - if len(keysAfter) != len(keysBefore) { - t.Fatalf("the fork's cut wrote %d keys into the source volume", len(keysAfter)-len(keysBefore)) - } - if own, _ := f.ListEntries(ctx, catBase+"/v2/keys", "", "", 0); len(own) != 2 { - t.Fatalf("the fork's cut wrote %d keys of its own, want one data chunk and one manifest", len(own)) - } -} - -func TestCatalog_SnapshotIntentAroundEntry(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - seen := -1 - f.beforeCreate = func(p string) { - if isSnapPath(p, "v1", "s1") { - seen = 0 - for k := range f.entries { - if strings.HasPrefix(k, catBase+"/v1/intents/") { - seen++ - } - } - } - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - if seen != 1 { - t.Fatalf("intents when the snapshot entry was written: %d, want 1", seen) - } - if got, _ := f.ListEntries(ctx, catBase+"/v1/intents", "", "", 0); len(got) != 0 { - t.Fatalf("snapshot left %d intents", len(got)) - } -} - -// The HEAD document carries "state" ("active" by every normal cut) and, -// only when detached, "detachedBy" {holder, epoch, gen} naming its own -// holder, epoch and generation; a document without "state" reads as active, -// and an inconsistent detachedBy is refused. -func TestHeadDoc_StateAndDetachedBy(t *testing.T) { - f, b := newFakeFiler(), newFakeBlobs() - r, _ := NewChunkRemote(f, b, catBase+"/v1") - ctx := context.Background() - gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "h", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadActive}) - if err != nil { - t.Fatal(err) - } - e, _ := f.LookupEntry(ctx, catBase+"/v1", "HEAD") - if !strings.Contains(string(e.Content), `"state":"active"`) || strings.Contains(string(e.Content), "detachedBy") { - t.Fatalf("an active HEAD document: %s", e.Content) - } - det := storage.ChunkHead{Epoch: 1, Holder: "h", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadDetached, - DetachedBy: &storage.ChunkDetachedBy{Holder: "h", Epoch: 1, Gen: gen + 1}} - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: gen, Epoch: 1}, det); err != nil { - t.Fatal(err) - } - h, err := r.GetHead(ctx) - if err != nil || h.State != storage.ChunkHeadDetached || h.DetachedBy == nil || *h.DetachedBy != (storage.ChunkDetachedBy{Holder: "h", Epoch: 1, Gen: gen + 1}) { - t.Fatalf("detached HEAD read back as %+v %v", h, err) - } - - // An older document without "state" reads as active. - e, _ = f.LookupEntry(ctx, catBase+"/v1", "HEAD") - var doc map[string]any - _ = json.Unmarshal(e.Content, &doc) - delete(doc, "state") - delete(doc, "detachedBy") - old, _ := json.Marshal(doc) - f.mu.Lock() - f.entries[catBase+"/v1/HEAD"].Content = old - f.mu.Unlock() - if h, err := r.GetHead(ctx); err != nil || h.State == storage.ChunkHeadDetached { - t.Fatalf("a HEAD without state: %+v %v, want active", h, err) - } - // detachedBy that is not the HEAD's own holder/epoch/gen is refused. - doc["state"] = "detached" - doc["detachedBy"] = map[string]any{"holder": "h", "epoch": 1, "gen": gen} // stale gen - bad, _ := json.Marshal(doc) - f.mu.Lock() - f.entries[catBase+"/v1/HEAD"].Content = bad - f.mu.Unlock() - if _, err := r.GetHead(ctx); err == nil { - t.Fatal("a detached HEAD with another generation in detachedBy was accepted") - } -} - -// Production serialization end to end: the walstore chunk layer's Detach, -// over the SeaweedFS remote, writes HEAD to the filer with exactly the -// ruled fields, in one CAS with the final cut. -func TestDetach_ProductionSerializedHead(t *testing.T) { - ctx := context.Background() - f, b := newFakeFiler(), newFakeBlobs() - p := filepath.Join(t.TempDir(), "v1") - s, err := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = s.Close() }) - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - r, _ := NewChunkRemote(f, b, catBase+"/v1") - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 3, Holder: "host-a"}) - if err != nil { - t.Fatal(err) - } - if _, err := s.Write(9, bytes.Repeat([]byte{9}, 4096)); err != nil { - t.Fatal(err) - } - res, err := l.Detach(ctx) - if err != nil { - t.Fatal(err) - } - e, err := f.LookupEntry(ctx, catBase+"/v1", "HEAD") - if err != nil { - t.Fatal(err) - } - var doc struct { - Gen uint64 `json:"gen"` - Epoch uint64 `json:"epoch"` - Holder string `json:"holder"` - RemoteLSN uint64 `json:"remote_lsn"` - State string `json:"state"` - DetachedBy map[string]any `json:"detachedBy"` - } - if err := json.Unmarshal(e.Content, &doc); err != nil { - t.Fatal(err) - } - if doc.Gen != 1 || doc.State != "detached" || doc.Holder != "host-a" || doc.Epoch != 3 || doc.RemoteLSN != res.H { - t.Fatalf("serialized HEAD: %s", e.Content) - } - if len(doc.DetachedBy) != 3 || doc.DetachedBy["holder"] != "host-a" || doc.DetachedBy["epoch"] != float64(3) || doc.DetachedBy["gen"] != float64(1) { - t.Fatalf("serialized detachedBy %v, want exactly {holder host-a, epoch 3, gen 1}", doc.DetachedBy) - } - if string(e.Extended[extGen]) != "1" || len(e.Chunks) != 0 { - t.Fatalf("HEAD entry extended gen %q, filer chunks %d", e.Extended[extGen], len(e.Chunks)) - } -} - -// A created volume gets its initial HEAD with the VOLUME entry (integration -// ruling F1): gen 1, epoch 0, no holder, remote_lsn 0, no chunks. An existing -// HEAD is kept, and a missing one is created again on the next attach. -func TestCatalog_EnsureVolumeCreatesTheInitialHead(t *testing.T) { - ctx := context.Background() - f, b := newFakeFiler(), newFakeBlobs() - c := newCat(t, f) - if _, err := c.EnsureVolume(ctx, "v1", catGeo); err != nil { - t.Fatal(err) - } - h, ok, err := c.ReadHead(ctx, "v1") - if err != nil || !ok || h.Gen != 1 || h.Epoch != 0 || h.Holder != "" || h.RemoteLSN != 0 || len(h.Chunks) != 0 || h.State != storage.ChunkHeadActive { - t.Fatalf("initial HEAD: %+v ok=%v %v", h, ok, err) - } - if _, err := c.EnsureVolume(ctx, "v1", catGeo); err != nil { - t.Fatal(err) - } - if again, _, _ := c.ReadHead(ctx, "v1"); again.Gen != 1 { - t.Fatalf("a repeated attach replaced the HEAD: %+v", again) - } - - // A volume published before VOLUME entries existed keeps its HEAD. - pub := publishSource(t, f, b, "v2", map[uint64][]byte{0: chunkBytes(0x10)}) - if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { - t.Fatal(err) - } - if kept, _, _ := c.ReadHead(ctx, "v2"); kept.Gen != pub.Gen || manifestCount(kept) != 1 || kept.Segments[0] != pub.Segments[0] { - t.Fatalf("an existing HEAD was replaced by the initial one: %+v, published %+v", kept, pub) - } - - // VOLUME written, HEAD lost before it (an interrupted first attach). - f.mu.Lock() - delete(f.entries, catBase+"/v1/HEAD") - f.mu.Unlock() - if _, err := c.EnsureVolume(ctx, "v1", catGeo); err != nil { - t.Fatal(err) - } - if h, ok, _ := c.ReadHead(ctx, "v1"); !ok || h.Gen != 1 { - t.Fatalf("the initial HEAD was not created again: %+v ok=%v", h, ok) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_tombstone_test.go b/seaweed-block/core/frontend/chunkstore/catalog_tombstone_test.go deleted file mode 100644 index 1e95ef02cd..0000000000 --- a/seaweed-block/core/frontend/chunkstore/catalog_tombstone_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package chunkstore - -import ( - "context" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// A sweep settles a dead fork by claiming the target's HEAD, the fork's -// publishing entry, with an aborted HEAD tombstone (W5): the late HEAD -// insert fails, a retry is refused, and the volume -// never attaches. -func TestFork_SweepTombstonesADeadFork(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - holdFirst(f, catBase+"/v2/HEAD") - req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} - if _, err := c.Fork(ctx, req); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - if claimed, err := c.AbortFork(ctx, "v2"); err != nil || !claimed { - t.Fatalf("sweep over the dead fork: claimed=%v %v", claimed, err) - } - if n := f.releaseDeferredCreates(); n != 0 { - t.Fatalf("the dead fork's late HEAD landed over the tombstone (%d applied)", n) - } - if again, err := c.AbortFork(ctx, "v2"); err != nil || !again { - t.Fatalf("a repeated sweep: claimed=%v %v; want the tombstone found", again, err) - } - if hd, ok, err := c.ReadHead(ctx, "v2"); err != nil || !ok || hd.State != storage.ChunkHeadAborted || len(hd.Chunks) != 0 { - t.Fatalf("target HEAD after the sweep: %+v ok=%v %v", hd, ok, err) - } - if _, err := c.Fork(ctx, req); CodeOf(err) != CodeTargetExists { - t.Fatalf("retry of the aborted fork: %v; want target_exists", err) - } - if _, err := c.EnsureVolume(ctx, "v2", catGeo); CodeOf(err) != CodeForkIncomplete { - t.Fatalf("attach of the aborted fork: %v; want fork_incomplete", err) - } -} - -// The tombstone loses to a published fork: the fork's keys are reachable -// through its HEAD, and its replay still works. -func TestFork_TombstoneLosesToPublishedFork(t *testing.T) { - _, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} - if _, err := c.Fork(ctx, req); err != nil { - t.Fatal(err) - } - if claimed, err := c.AbortFork(ctx, "v2"); err != nil || claimed { - t.Fatalf("sweep over a published fork: claimed=%v %v; want published", claimed, err) - } - if res, err := c.Fork(ctx, req); err != nil || !res.Replayed { - t.Fatalf("replay after a refused sweep: %+v %v", res, err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go deleted file mode 100644 index 8462cfad23..0000000000 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ /dev/null @@ -1,645 +0,0 @@ -package chunkstore - -// ChunkRemote: the walstore chunk layer's remote (storage.ChunkRemote) on -// SeaweedFS, over the Filer and Blobs interfaces above. -// -// Layout under one volume's root directory: -// -// /HEAD the published HEAD: JSON in the entry content, -// {gen, epoch, holder} mirrored in extended attributes -// /keys/ one write-once entry per chunk key, naming the -// needle (fid) that holds the chunk's bytes -// /intents/ one entry per live intent (-): the keys a -// holder is about to publish; GC treats them as roots -// -// The chunk layer names chunks itself (immutable keys) while SeaweedFS -// assigns needle ids, so a key entry binds the two. -// -// A key may be owner-qualified, "@/": the binding then lives in -// the owner volume's keys/ directory, //keys/, where is -// the parent of this volume's root. A fork's HEAD names its parent's chunks -// this way, so the fork shares them without copying any binding. The layer -// never generates a key starting with "@"; Get resolves qualified keys and -// Put refuses them (a volume only ever writes its own keys). It is created with -// o_excl: a key that exists is never rebound, which is the "keys are -// immutable" rule of storage.ChunkRemote. -// -// The HEAD CAS is the filer's conditional update: UpdateEntry with -// expected_extended = {swb.gen, swb.epoch} of the HEAD the caller read. -// The first HEAD is an exclusive create. Only a definite refusal maps to -// storage.ErrChunkHeadPrecondition; every other error is returned as is, -// so the chunk layer treats the outcome as unknown and re-reads HEAD. -// -// No entry ever carries filer chunks: UpdateEntry deletes chunks the new -// entry drops, so needle ids live only in entry content and extended -// attributes, which the filer does not interpret. -// -// Not implemented: reclaiming needles. Delete reports ErrDeleteUnsupported; -// superseded chunks stay stored (the chunk layer never calls Delete). - -import ( - "context" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "net/url" - "path" - "strconv" - "strings" - "sync" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Extended attribute keys; the same names the D1 manifest entries use. -const ( - extGen = "swb.gen" - extEpoch = "swb.epoch" - extHolder = "swb.holder" - extKind = "swb.kind" - extFid = "swb.fid" - - kindChunkHead = "chunkhead" - kindChunkKey = "chunkkey" - kindChunkIntent = "chunkintent" - - headName = "HEAD" - keysDir = "keys" - intentsDir = "intents" - - // intentFormat is the only intent document format this code reads. - intentFormat = 1 - // listPage is the page size of a full directory listing. - listPage = 1000 - - // headFormat is the only HEAD document format this code reads. - headFormat = 1 -) - -// ErrDeleteUnsupported: this remote does not reclaim chunks. -var ErrDeleteUnsupported = errors.New("chunkstore: chunk delete not supported") - -// ChunkRemote implements storage.ChunkRemote for one volume. -type ChunkRemote struct { - f Filer - b Blobs - root string - - mu sync.Mutex - fids map[string]string // key -> fid; key entries are write-once - - assigns assignCounters // reservations made by upload rounds -} - -// NewChunkRemote returns the remote for the volume rooted at root, an -// absolute filer directory owned by that volume alone. -func NewChunkRemote(f Filer, b Blobs, root string) (*ChunkRemote, error) { - if f == nil || b == nil { - return nil, errors.New("chunkstore: chunk remote needs a filer and a blob store") - } - if !path.IsAbs(root) || path.Clean(root) != root || root == "/" { - return nil, fmt.Errorf("chunkstore: chunk remote root %q must be a clean absolute directory other than /", root) - } - return &ChunkRemote{f: f, b: b, root: root, fids: map[string]string{}}, nil -} - -func (r *ChunkRemote) keyDir() string { return path.Join(r.root, keysDir) } - -func keyName(key string) (string, error) { - if key == "" { - return "", errors.New("chunkstore: empty chunk key") - } - return url.PathEscape(key), nil // one flat directory: '/' is escaped -} - -// CheckVolumeID accepts a volume id that is one plain path element, so a -// volume's directory, or a qualified key's owner, stays inside the base. -func CheckVolumeID(id string) error { - if id == "" || id == "." || id == ".." || strings.ContainsAny(id, "/\\") { - return fmt.Errorf("chunkstore: volume id %q is not a plain path element", id) - } - return nil -} - -// keyLocation returns the directory and entry name holding key's binding: -// the owner's keys/ directory for "@/", this volume's otherwise. -func (r *ChunkRemote) keyLocation(key string) (dir, name string, err error) { - if err := storage.ValidChunkKey(key); err != nil { - return "", "", fmt.Errorf("%w: %v", ErrInvalidKey, err) - } - if !strings.HasPrefix(key, "@") { - name, err := keyName(key) - return r.keyDir(), name, err - } - owner, own, ok := strings.Cut(key[1:], "/") - if !ok || own == "" { - return "", "", fmt.Errorf("%w: %q is not \"@/\"", ErrInvalidKey, key) - } - if err := CheckVolumeID(owner); err != nil { - return "", "", fmt.Errorf("%w: %q: %v", ErrInvalidKey, key, err) - } - return path.Join(path.Dir(r.root), owner, keysDir), url.PathEscape(own), nil -} - -// Put stores data as a new needle, then binds key to it with an exclusive -// create. A key that is already bound fails with storage.ErrChunkKeyExists -// and its bytes are untouched. -func (r *ChunkRemote) Put(ctx context.Context, key string, data []byte) error { - return r.putObject(ctx, key, data, "") -} - -func (r *ChunkRemote) putObject(ctx context.Context, key string, data []byte, object string) error { - name, err := r.ownKeyName(key) - if err != nil { - return err - } - if r.knownKey(key) { - return storage.ErrChunkKeyExists - } - fid, err := r.b.Put(ctx, data) - if err != nil { - return err - } - return r.bindKey(ctx, key, name, fid, data, object) -} - -// ownKeyName checks that key is one of this volume's own keys and returns -// its binding's entry name. -func (r *ChunkRemote) ownKeyName(key string) (string, error) { - if err := storage.ValidChunkKey(key); err != nil { - return "", fmt.Errorf("%w: %v", ErrInvalidKey, err) - } - if strings.HasPrefix(key, "@") { - return "", fmt.Errorf("%w: %q is owner-qualified; a volume writes only its own keys", ErrInvalidKey, key) - } - return keyName(key) -} - -// knownKey reports whether key is already bound (as far as this remote saw). -func (r *ChunkRemote) knownKey(key string) bool { - r.mu.Lock() - defer r.mu.Unlock() - _, known := r.fids[key] - return known -} - -// bindKey binds key to the stored needle fid with an exclusive create. -func (r *ChunkRemote) bindKey(ctx context.Context, key, name, fid string, data []byte, object string) error { - now := time.Now().Unix() - e := &filerpb.Entry{ - Name: name, - Attributes: &filerpb.FuseAttributes{Mtime: now, Crtime: now, FileMode: 0o644}, - Extended: map[string][]byte{extKind: []byte(kindChunkKey), extFid: []byte(fid)}, - } - if object == "segment" { - e.Extended["swb.object"] = []byte("segment") - e.Attributes.FileSize = uint64(len(data)) - } - if err := r.f.CreateEntry(ctx, r.keyDir(), e, true); err != nil { - if errors.Is(err, ErrExists) { - return fmt.Errorf("%w: %s", storage.ErrChunkKeyExists, key) - } - return err - } - r.mu.Lock() - r.fids[key] = fid - r.mu.Unlock() - return nil -} - -// Get returns the bytes bound to key. The chunk layer checks them against -// the SHA-256 in HEAD. -func (r *ChunkRemote) Get(ctx context.Context, key string) ([]byte, error) { - dir, name, err := r.keyLocation(key) - if err != nil { - return nil, err - } - r.mu.Lock() - fid, ok := r.fids[key] - r.mu.Unlock() - if !ok { - e, err := r.f.LookupEntry(ctx, dir, name) - if err != nil { - return nil, fmt.Errorf("chunkstore: chunk key %q: %w", key, err) - } - if len(e.GetChunks()) != 0 || string(e.Extended[extKind]) != kindChunkKey || len(e.Extended[extFid]) == 0 { - return nil, fmt.Errorf("chunkstore: chunk key %q: entry is not a chunk key binding", key) - } - fid = string(e.Extended[extFid]) - r.mu.Lock() - r.fids[key] = fid - r.mu.Unlock() - } - return r.b.Get(ctx, fid) -} - -// ReclaimKey deletes the needle bound to one of this volume's own keys -// with GC's step (reclaimBinding): the binding is tombstoned, the exact fid -// deleted, the binding kept for ever and marked done. It decides nothing: -// the caller must know that no HEAD, snapshot, fork or intent references -// key. An owner-qualified key is refused. -func (r *ChunkRemote) ReclaimKey(ctx context.Context, key string, blobs BlobDeleter) error { - if err := storage.ValidChunkKey(key); err != nil { - return fmt.Errorf("%w: %v", ErrInvalidKey, err) - } - if strings.HasPrefix(key, "@") { - return fmt.Errorf("%w: %q is owner-qualified; a volume reclaims only its own keys", ErrInvalidKey, key) - } - name, err := keyName(key) - if err != nil { - return err - } - e, err := r.f.LookupEntry(ctx, r.keyDir(), name) - if err != nil { - return fmt.Errorf("chunkstore: chunk key %q: %w", key, err) - } - if len(e.GetChunks()) != 0 || string(e.Extended[extKind]) != kindChunkKey || len(e.Extended[extFid]) == 0 { - return fmt.Errorf("chunkstore: chunk key %q: entry is not a chunk key binding", key) - } - return reclaimBinding(ctx, r.f, blobs, r.keyDir(), e) -} - -// Delete is not supported; see ErrDeleteUnsupported. -func (r *ChunkRemote) Delete(context.Context, string) error { return ErrDeleteUnsupported } - -type intentDoc struct { - Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"` - ChunkBytes uint64 `json:"chunk_bytes,omitempty"` - Format int `json:"format"` - Gen uint64 `json:"gen"` - Epoch uint64 `json:"epoch"` - Holder string `json:"holder"` - Keys []string `json:"keys"` - CreatedNs int64 `json:"created_ns"` - // DeadlineNs: a copy intent's publication deadline (0: a capture intent). - DeadlineNs int64 `json:"deadline_ns,omitempty"` -} - -func (r *ChunkRemote) intentDir() string { return path.Join(r.root, intentsDir) } - -// PutIntent writes /intents/- with an exclusive create. -// The entry is durable when the filer's fsync rule covers the chunk path, -// the same condition as for HEAD. -func (r *ChunkRemote) PutIntent(ctx context.Context, in storage.ChunkIntent) (string, error) { - return putIntent(ctx, r.f, r.root, in) -} - -// putIntent writes an intent under /intents/; the catalog uses it for -// snapshots and forks, which have no ChunkRemote. -func putIntent(ctx context.Context, f Filer, root string, in storage.ChunkIntent) (string, error) { - for _, k := range in.Keys { - if err := storage.ValidChunkKey(k); err != nil { - return "", fmt.Errorf("%w: %v", ErrInvalidKey, err) - } - } - id, err := storage.NewChunkIntentID(in.Gen) - if err != nil { - return "", err - } - now := time.Now() - body, err := json.Marshal(intentDoc{Format: intentFormat, Gen: in.Gen, Epoch: in.Epoch, Holder: in.Holder, Keys: in.Keys, CreatedNs: now.UnixNano(), DeadlineNs: in.DeadlineNs, Segments: in.Segments, ChunkBytes: in.ChunkBytes}) - if err != nil { - return "", err - } - e := &filerpb.Entry{ - Name: id, - Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now.Unix(), Crtime: now.Unix(), FileMode: 0o644, Mime: "application/json"}, - Extended: map[string][]byte{ - extKind: []byte(kindChunkIntent), - extGen: []byte(strconv.FormatUint(in.Gen, 10)), - extEpoch: []byte(strconv.FormatUint(in.Epoch, 10)), - extHolder: []byte(in.Holder), - }, - Content: body, - } - if err := f.CreateEntry(ctx, path.Join(root, intentsDir), e, true); err != nil { - return "", fmt.Errorf("chunkstore: put intent %s: %w", id, err) - } - return id, nil -} - -// DeleteIntent removes /intents/ and nothing else; a missing -// intent is not an error. -func (r *ChunkRemote) DeleteIntent(ctx context.Context, id string) error { - if !storage.ValidChunkIntentID(id) { - return fmt.Errorf("chunkstore: intent id %q is not \"-\"", id) - } - return r.f.DeleteEntry(ctx, r.intentDir(), id, nil) -} - -// ListIntents lists every entry under /intents/. An entry that is not -// a well-formed intent fails the listing, so GC never misses a root. -func (r *ChunkRemote) ListIntents(ctx context.Context) ([]storage.ChunkIntent, error) { - var out []storage.ChunkIntent - after := "" - for { - page, err := r.f.ListEntries(ctx, r.intentDir(), "", after, listPage) - if err != nil { - return nil, err - } - for _, e := range page { - in, err := decodeIntent(path.Join(r.intentDir(), e.GetName()), e) - if err != nil { - return nil, err - } - out = append(out, in) - } - if len(page) < listPage { - return out, nil - } - after = page[len(page)-1].GetName() - } -} - -func decodeIntent(p string, e *filerpb.Entry) (storage.ChunkIntent, error) { - fail := func(format string, a ...any) (storage.ChunkIntent, error) { - return storage.ChunkIntent{}, fmt.Errorf("chunkstore: intent %s: "+format, append([]any{p}, a...)...) - } - if len(e.GetChunks()) != 0 { - return fail("carries %d filer chunks", len(e.Chunks)) - } - if k := string(e.Extended[extKind]); k != kindChunkIntent { - return fail("kind %q, want %q", k, kindChunkIntent) - } - if !storage.ValidChunkIntentID(e.GetName()) { - return fail("name is not \"-\"") - } - var doc intentDoc - if err := json.Unmarshal(e.GetContent(), &doc); err != nil { - return fail("decode: %v", err) - } - if doc.Format != intentFormat { - return fail("format %d not supported (want %d)", doc.Format, intentFormat) - } - if !strings.HasPrefix(e.GetName(), strconv.FormatUint(doc.Gen, 10)+"-") || - string(e.Extended[extEpoch]) != strconv.FormatUint(doc.Epoch, 10) || string(e.Extended[extHolder]) != doc.Holder { - return fail("name or extended gen/epoch/holder disagree with the document") - } - return storage.ChunkIntent{ID: e.GetName(), Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, - Keys: append([]string(nil), doc.Keys...), CreatedNs: doc.CreatedNs, DeadlineNs: doc.DeadlineNs, Segments: doc.Segments, ChunkBytes: doc.ChunkBytes}, nil -} - -type headDoc struct { - Levels int `json:"levels,omitempty"` - Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"` - ChunkBytes uint64 `json:"chunk_bytes,omitempty"` - ChunkCount int `json:"chunk_count,omitempty"` - Format int `json:"format"` - Gen uint64 `json:"gen"` - Epoch uint64 `json:"epoch"` - Holder string `json:"holder"` - RemoteLSN uint64 `json:"remote_lsn"` - Chunks map[uint64]refDoc `json:"chunks,omitempty"` - // State is "active" or "detached"; a document without it is active. - // DetachedBy names the holder whose final cut (this generation) a - // detached HEAD is; it is absent unless State is detached. - State string `json:"state,omitempty"` - DetachedBy *detachedByDoc `json:"detachedBy,omitempty"` -} - -type detachedByDoc struct { - Holder string `json:"holder"` - Epoch uint64 `json:"epoch"` - Gen uint64 `json:"gen"` -} - -type refDoc struct { - Key string `json:"key"` - SHA256 string `json:"sha256"` -} - -// GetHead returns the published HEAD, or the zero HEAD (Gen 0) when none -// was ever published. An entry that exists but does not decode is an -// error, never the zero HEAD. -func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { - h, err := r.getHeadRoot(ctx) - if err != nil { - return h, err - } - return r.resolveManifest(ctx, h) -} - -// GetHeadRoot validates publication identity without reading segment bodies. -func (r *ChunkRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) { - return r.getHeadRoot(ctx) -} - -// getHeadRoot validates the root and its CAS attributes without reading any -// immutable segment. CASHead only needs authority and lineage from this root. -func (r *ChunkRemote) getHeadRoot(ctx context.Context) (storage.ChunkHead, error) { - e, err := r.f.LookupEntry(ctx, r.root, headName) - if errors.Is(err, ErrNotFound) { - return storage.ChunkHead{}, nil - } - if err != nil { - return storage.ChunkHead{}, err - } - return decodeHead(path.Join(r.root, headName), e) -} - -// CASHead installs next, at generation expected.Gen+1, only if the stored -// HEAD is still at expected. Ownership only moves forward: a proposal that -// lowers the epoch is refused. -func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { - if next.Epoch < expected.Epoch { - return 0, storage.ErrChunkHeadPrecondition - } - if expected.Gen == 0 && expected.Epoch != 0 { - return 0, storage.ErrChunkHeadPrecondition // the absent HEAD has epoch 0 - } - // Read the LSN under the same generation/epoch guard used by UpdateEntry. - // A competing write after this read makes the conditional update fail; - // no successful CAS can lower the committed lineage frontier. - current, err := r.getHeadRoot(ctx) - if err != nil { - return 0, err - } - if current.State == storage.ChunkHeadDeleting || current.State == storage.ChunkHeadPurging || current.State == storage.ChunkHeadDeleted { - // A delete passed its linearization point: nothing moves this HEAD - // again (the catalog writes the delete's own transitions). - return 0, fmt.Errorf("%w: %w", storage.ErrChunkHeadPrecondition, storage.ErrChunkHeadDeleted) - } - if current.Gen != expected.Gen || current.Epoch != expected.Epoch || next.RemoteLSN < current.RemoteLSN { - return 0, storage.ErrChunkHeadPrecondition - } - next.Gen = expected.Gen + 1 - e, err := headEntry(next) - if err != nil { - return 0, err - } - if expected.Gen == 0 { - err = r.f.CreateEntry(ctx, r.root, e, true) - } else { - err = r.f.UpdateEntry(ctx, r.root, e, map[string][]byte{ - extGen: []byte(strconv.FormatUint(expected.Gen, 10)), - extEpoch: []byte(strconv.FormatUint(expected.Epoch, 10)), - }) - } - switch { - case err == nil: - return next.Gen, nil - case errors.Is(err, ErrPrecondition), errors.Is(err, ErrExists), errors.Is(err, ErrNotFound): - return 0, fmt.Errorf("%w: %v", storage.ErrChunkHeadPrecondition, err) - default: - return 0, err // outcome unknown: the caller re-reads HEAD - } -} - -func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { - doc := headDoc{Format: headFormat, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, - State: h.State} - if h.DetachedBy != nil { - doc.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen} - } - if h.Segments == nil { - if len(h.Chunks) != 0 { - return nil, errors.New("chunkstore: data HEAD requires a segmented manifest and geometry") - } - doc.Chunks = map[uint64]refDoc{} - } - if h.Segments != nil { - if err := validateRoot(h); err != nil { - return nil, err - } - doc.Format = 3 - doc.Levels = 1 - doc.Chunks = nil - doc.Segments = h.Segments - doc.ChunkBytes = h.ChunkBytes - doc.ChunkCount = h.ManifestChunkCount - } - body, err := json.Marshal(doc) - if err != nil { - return nil, err - } - now := time.Now().Unix() - return &filerpb.Entry{ - Name: headName, - Attributes: &filerpb.FuseAttributes{ - FileSize: uint64(len(body)), - Mtime: now, - Crtime: now, - FileMode: 0o644, - Mime: "application/json", - }, - Extended: map[string][]byte{ - extGen: []byte(strconv.FormatUint(h.Gen, 10)), - extEpoch: []byte(strconv.FormatUint(h.Epoch, 10)), - extHolder: []byte(h.Holder), - extKind: []byte(kindChunkHead), - }, - Content: body, - }, nil -} - -func decodeHead(p string, e *filerpb.Entry) (storage.ChunkHead, error) { - fail := func(format string, a ...any) (storage.ChunkHead, error) { - return storage.ChunkHead{}, fmt.Errorf("chunkstore: HEAD %s: "+format, append([]any{p}, a...)...) - } - if len(e.GetChunks()) != 0 { - return fail("carries %d filer chunks; refusing (an update would let the filer delete them)", len(e.Chunks)) - } - if k := string(e.Extended[extKind]); k != kindChunkHead { - return fail("kind %q, want %q", k, kindChunkHead) - } - h, err := decodeHeadDoc(p, e.GetContent()) - if err != nil { - return storage.ChunkHead{}, err - } - // The CAS compares the extended attributes, so they must agree with the - // document or a CAS could validate against a different state. - if string(e.Extended[extGen]) != strconv.FormatUint(h.Gen, 10) || - string(e.Extended[extEpoch]) != strconv.FormatUint(h.Epoch, 10) || - string(e.Extended[extHolder]) != h.Holder { - return fail("extended gen/epoch/holder (%q/%q/%q) disagree with the document (%d/%d/%q)", - e.Extended[extGen], e.Extended[extEpoch], e.Extended[extHolder], h.Gen, h.Epoch, h.Holder) - } - return h, nil -} - -// decodeHeadDoc decodes and checks a HEAD document: HEAD's own content, or -// the copy a snapshot embeds. -func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { - fail := func(format string, a ...any) (storage.ChunkHead, error) { - return storage.ChunkHead{}, fmt.Errorf("chunkstore: HEAD %s: "+format, append([]any{p}, a...)...) - } - doc, err := decodeFormatHead(content) - if err != nil { - return fail("decode: %v", err) - } - if doc.Gen == 0 { - return fail("generation 0") - } - switch doc.State { - case "", storage.ChunkHeadActive: - if doc.DetachedBy != nil { - return fail("detachedBy on a HEAD that is not detached") - } - case storage.ChunkHeadAborted: - // A sweep's tombstone over a dead fork's HEAD (gen 1, no chunks). - if doc.DetachedBy != nil || len(doc.Chunks) != 0 { - return fail("an aborted HEAD with content") - } - case storage.ChunkHeadDeleting, storage.ChunkHeadPurging: - // A delete's mark over the HEAD it read (deleting: still revertible; - // purging: committed): content and any detach record kept. - case storage.ChunkHeadDeleted: - // A deleted volume's tombstone (no chunks, no holder). - if doc.DetachedBy != nil || len(doc.Chunks) != 0 || doc.Holder != "" { - return fail("a deleted HEAD with content") - } - case storage.ChunkHeadDetached: - d := doc.DetachedBy - if d == nil || d.Gen != doc.Gen || d.Holder != doc.Holder || d.Epoch != doc.Epoch { - return fail("detached HEAD whose detachedBy %+v is not its own holder, epoch and generation", d) - } - default: - return fail("state %q", doc.State) - } - h := storage.ChunkHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN, - Chunks: make(map[uint64]storage.ChunkRef, len(doc.Chunks)), State: doc.State} - if doc.DetachedBy != nil { - h.DetachedBy = &storage.ChunkDetachedBy{Holder: doc.DetachedBy.Holder, Epoch: doc.DetachedBy.Epoch, Gen: doc.DetachedBy.Gen} - } - for idx, ref := range doc.Chunks { - sum, err := hex.DecodeString(ref.SHA256) - if err != nil || len(sum) != 32 || ref.Key == "" { - return fail("chunk %d ref invalid", idx) - } - cr := storage.ChunkRef{Key: ref.Key, Encoding: "full", BirthLSN: doc.RemoteLSN} - copy(cr.SHA256[:], sum) - h.Chunks[idx] = cr - } - if doc.Format == 2 || doc.Format == 3 { - if len(doc.Chunks) != 0 { - return fail("segmented root contains flat chunks") - } - h.Segments = doc.Segments - if h.Segments == nil { - h.Segments = map[uint64]storage.ChunkSegment{} - } - h.ChunkBytes = doc.ChunkBytes - h.ManifestChunkCount = doc.ChunkCount - if err := validateRoot(h); err != nil { - return h, err - } - } - return h, nil -} - -// NewSWFSChunkRemote is NewChunkRemote over one SWFS client, which serves -// as both the filer and the blob store. -func NewSWFSChunkRemote(c *SWFS, root string) (*ChunkRemote, error) { - return NewChunkRemote(c, c, root) -} - -var _ storage.ChunkRemote = (*ChunkRemote)(nil) - -// DecodeHeadDocument validates a persisted flat or segmented root without -// fetching data. Control-plane readers share the same representation checks. -func DecodeHeadDocument(name string, body []byte) (storage.ChunkHead, error) { - return decodeHeadDoc(name, body) -} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go deleted file mode 100644 index 2e3c15925a..0000000000 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go +++ /dev/null @@ -1,308 +0,0 @@ -//go:build chunkstore_integration - -// The chunk remote against real SeaweedFS processes (weed master, volume, -// filer) started as the current user. The cluster helpers are the D1 -// PoC's. Run with: -// -// CHUNKSTORE_WEED=/path/to/weed go test -tags chunkstore_integration -run Integration -v ./core/frontend/chunkstore/ -package chunkstore - -import ( - "bytes" - "context" - "errors" - "fmt" - "math/rand" - "net" - "os" - "os/exec" - "path/filepath" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -type weedCluster struct { - master, filerHTTP, filerGRPC string - dir string - weed string -} - -func freePortPair(t *testing.T, used map[int]bool) int { - t.Helper() - for i := 0; i < 200; i++ { - p := 20000 + rand.Intn(20000) - if used[p] || used[p+10000] { - continue - } - ok := true - for _, q := range []int{p, p + 10000} { - l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", q)) - if err != nil { - ok = false - break - } - l.Close() - } - if ok { - used[p], used[p+10000] = true, true - return p - } - } - t.Fatal("no free port pair") - return 0 -} - -func waitTCP(t *testing.T, addr string, d time.Duration) { - t.Helper() - deadline := time.Now().Add(d) - for time.Now().Before(deadline) { - if c, err := net.DialTimeout("tcp", addr, 200*time.Millisecond); err == nil { - c.Close() - return - } - time.Sleep(100 * time.Millisecond) - } - t.Fatalf("%s not listening after %v", addr, d) -} - -func startWeed(t *testing.T) *weedCluster { - t.Helper() - return startWeedWith(t, "") -} - -// startWeedWith starts the cluster with security (the contents of a -// security.toml in its working directory; "" for none). -func startWeedWith(t *testing.T, security string) *weedCluster { - t.Helper() - weed := os.Getenv("CHUNKSTORE_WEED") - if weed == "" { - t.Skip("CHUNKSTORE_WEED not set") - } - dir := t.TempDir() - used := map[int]bool{} - mp, vp, fp := freePortPair(t, used), freePortPair(t, used), freePortPair(t, used) - c := &weedCluster{ - master: fmt.Sprintf("127.0.0.1:%d", mp), - filerHTTP: fmt.Sprintf("127.0.0.1:%d", fp), - filerGRPC: fmt.Sprintf("127.0.0.1:%d", fp+10000), - dir: dir, - weed: weed, - } - run := func(name string, args ...string) { - logf, err := os.Create(filepath.Join(dir, name+".log")) - if err != nil { - t.Fatal(err) - } - cmd := exec.Command(weed, args...) - cmd.Stdout, cmd.Stderr = logf, logf - cmd.Dir = dir - if err := cmd.Start(); err != nil { - t.Fatalf("start %s: %v", name, err) - } - t.Cleanup(func() { - _ = cmd.Process.Kill() - _, _ = cmd.Process.Wait() - logf.Close() - if t.Failed() { - b, _ := os.ReadFile(logf.Name()) - if len(b) > 4000 { - b = b[len(b)-4000:] - } - t.Logf("---- %s log tail ----\n%s", name, b) - } - }) - } - for _, d := range []string{"m", "v", "f"} { - if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil { - t.Fatal(err) - } - } - if security != "" { - if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(security), 0o600); err != nil { - t.Fatal(err) - } - } - run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000") - waitTCP(t, c.master, 20*time.Second) - run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, "-max=32") - run("filer", "filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f")) - waitTCP(t, c.filerGRPC, 30*time.Second) - - // Wait until an assign succeeds (volume registered, volumes growable). - cl := c.client(t, "/swblock/vols/probe") - deadline := time.Now().Add(60 * time.Second) - for { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - _, err := cl.Put(ctx, []byte("probe")) - cancel() - if err == nil { - break - } - if time.Now().After(deadline) { - t.Fatalf("cluster never accepted a write: %v", err) - } - time.Sleep(500 * time.Millisecond) - } - return c -} - -func (c *weedCluster) client(t *testing.T, assignPath string) *SWFS { - t.Helper() - cl, err := DialSWFS(SWFSConfig{FilerGRPC: c.filerGRPC, Collection: "swblock", AssignPath: assignPath}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = cl.Close() }) - return cl -} - -func (c *weedCluster) remote(t *testing.T, root string) *ChunkRemote { - t.Helper() - r, err := NewSWFSChunkRemote(c.client(t, root), root) - if err != nil { - t.Fatal(err) - } - return r -} - -// publishIntegrationHead uses the real format-3 manifest path before publishing data. -func publishIntegrationHead(t *testing.T, r *ChunkRemote, base, next storage.ChunkHead, chunkBytes uint64) storage.ChunkHead { - t.Helper() - ctx := context.Background() - next, intents, err := r.PrepareManifest(ctx, base, next, chunkBytes) - if err != nil { - t.Fatal(err) - } - next.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, next) - if err != nil { - t.Fatal(err) - } - if next.Gen != base.Gen+1 { - t.Fatalf("published generation %d, want %d", next.Gen, base.Gen+1) - } - for _, id := range intents { - if err := r.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - return next -} - -func TestIntegration_ChunkRemoteContract(t *testing.T) { - c := startWeed(t) - ctx := context.Background() - const root = "/swblock/chunks/contract" - a, b := c.remote(t, root), c.remote(t, root) - - if h, err := a.GetHead(ctx); err != nil || h.Gen != 0 { - t.Fatalf("absent HEAD = %+v, %v", h, err) - } - d := bytes.Repeat([]byte("chunk-bytes-"), 1000) - const key = "chunks/e1/c4/nonce-1" - if err := a.Put(ctx, key, d); err != nil { - t.Fatalf("Put: %v", err) - } - if err := a.Put(ctx, key, []byte("other")); !errors.Is(err, storage.ErrChunkKeyExists) { - t.Fatalf("rebind on the same client: %v", err) - } - if err := b.Put(ctx, key, []byte("other")); !errors.Is(err, storage.ErrChunkKeyExists) { - t.Fatalf("rebind from another client (real o_excl): %v", err) - } - if got, err := b.Get(ctx, key); err != nil || !bytes.Equal(got, d) { - t.Fatalf("Get from another client: %d bytes, %v", len(got), err) - } - - h1 := publishIntegrationHead(t, a, storage.ChunkHead{}, storage.ChunkHead{Epoch: 1, Holder: "a", RemoteLSN: 7, Chunks: map[uint64]storage.ChunkRef{4: ref(key, d)}}, 16384) - if _, err := b.CASHead(ctx, storage.ChunkHeadVersion{}, h1); !isPrecondition(err) { - t.Fatalf("racing first CAS: %v; want precondition (real o_excl)", err) - } - got, err := b.GetHead(ctx) - if err != nil || got.Gen != 1 || got.Chunks[4] != h1.Chunks[4] || got.RemoteLSN != 7 { - t.Fatalf("HEAD from another client = %+v, %v", got, err) - } - // Takeover at epoch 2, then the old holder's CAS at the version it read. - takeover := h1 - takeover.Epoch, takeover.Holder = 2, "b" - if gen, err := b.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, takeover); err != nil || gen != 2 { - t.Fatalf("takeover CAS = %d, %v", gen, err) - } - _, err = a.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, storage.ChunkHead{Epoch: 1, Holder: "a", RemoteLSN: 9}) - if !isPrecondition(err) { - t.Fatalf("old holder's CAS after takeover: %v; want precondition (real FailedPrecondition)", err) - } - t.Logf("old holder refused: %v", err) - if _, err := a.CASHead(ctx, storage.ChunkHeadVersion{Gen: 2, Epoch: 2}, storage.ChunkHead{Epoch: 1, Holder: "a"}); !isPrecondition(err) { - t.Fatalf("epoch-lowering CAS: %v; want precondition", err) - } - e, err := c.client(t, root).LookupEntry(ctx, root, headName) - if err != nil { - t.Fatal(err) - } - if len(e.GetChunks()) != 0 || string(e.Extended[extGen]) != "2" || string(e.Extended[extEpoch]) != "2" { - t.Fatalf("stored HEAD entry: %d filer chunks, gen %q, epoch %q", len(e.GetChunks()), e.Extended[extGen], e.Extended[extEpoch]) - } -} - -func TestIntegration_ChunkLayerCaptureThenFreshHost(t *testing.T) { - c := startWeed(t) - ctx := context.Background() - const root = "/swblock/chunks/v1" - const blocks, chunkBlocks = 512, 64 // 256 KiB chunks - dir := t.TempDir() - attach := func(name string, fresh bool) (*storage.WALStore, storage.ChunkLayer) { - p := filepath.Join(dir, name) - s, err := storage.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks}) - if err != nil { - t.Fatal(err) - } - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - l, err := storage.AttachChunkLayer(s, c.remote(t, root), storage.ChunkLayerConfig{ - ChunkBlocks: chunkBlocks, Epoch: 1, Holder: name, FreshFromHead: fresh, - }) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = s.Close() }) - return s, l - } - src, layer := attach("a", true) // a new, empty source volume - want := map[uint32][]byte{} - rng := rand.New(rand.NewSource(1)) - for _, lba := range []uint32{0, 63, 64, 300, 511} { - b := make([]byte, 4096) - rng.Read(b) - want[lba] = b - if _, err := src.Write(lba, b); err != nil { - t.Fatal(err) - } - } - if _, err := src.Sync(); err != nil { - t.Fatal(err) - } - start := time.Now() - if _, err := layer.Capture(ctx); err != nil { - t.Fatalf("Capture: %v", err) - } - t.Logf("capture of 4 dirty chunks: %v", time.Since(start)) - _ = src.Close() - - dst, _ := attach("b", true) - zero := make([]byte, 4096) - for lba := uint32(0); lba < blocks; lba++ { - got, err := dst.Read(lba) - if err != nil { - t.Fatalf("fresh host read %d: %v", lba, err) - } - exp, ok := want[lba] - if !ok { - exp = zero - } - if !bytes.Equal(got, exp) { - t.Fatalf("fresh host block %d differs", lba) - } - } -} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_intent_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_intent_test.go deleted file mode 100644 index cf8cb9a5e3..0000000000 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_intent_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package chunkstore - -import ( - "context" - "path" - "strings" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Intents live in /intents/-, carry no filer chunks, list -// back with what was written, and DeleteIntent removes only its own id. -func TestChunkRemote_IntentsRoundTripAndNonce(t *testing.T) { - f, b := newFakeFiler(), newFakeBlobs() - r, err := NewChunkRemote(f, b, "/swblock/chunks/v1") - if err != nil { - t.Fatal(err) - } - ctx := context.Background() - a, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: 3, Epoch: 1, Holder: "h1", Keys: []string{"chunks/e1/c0/x-1", "@v0/chunks/e1/c1/y-2"}}) - if err != nil { - t.Fatal(err) - } - c, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: 3, Epoch: 1, Holder: "h1", Keys: []string{"chunks/e1/c2/z-3"}}) - if err != nil { - t.Fatal(err) - } - if a == c || !strings.HasPrefix(a, "3-") || !strings.HasPrefix(c, "3-") { - t.Fatalf("ids %q %q: want distinct \"3-\"", a, c) - } - if _, err := f.LookupEntry(ctx, "/swblock/chunks/v1/intents", a); err != nil { - t.Fatalf("intent %q not at /intents/: %v", a, err) - } - for _, e := range f.allWritten() { - if len(e.Chunks) != 0 { - t.Fatalf("entry %q written with filer chunks", e.Name) - } - } - got, err := r.ListIntents(ctx) - if err != nil || len(got) != 2 { - t.Fatalf("ListIntents: %+v %v", got, err) - } - for _, in := range got { - if in.ID == a && (in.Gen != 3 || in.Epoch != 1 || in.Holder != "h1" || len(in.Keys) != 2 || in.Keys[1] != "@v0/chunks/e1/c1/y-2" || in.CreatedNs == 0) { - t.Fatalf("intent %q listed as %+v", a, in) - } - } - if err := r.DeleteIntent(ctx, a); err != nil { - t.Fatal(err) - } - if err := r.DeleteIntent(ctx, a); err != nil { - t.Fatalf("deleting a missing intent: %v", err) - } - got, _ = r.ListIntents(ctx) - if len(got) != 1 || got[0].ID != c { - t.Fatalf("after DeleteIntent(%q): %+v", a, got) - } - if err := r.DeleteIntent(ctx, "../HEAD"); err == nil { - t.Fatal("DeleteIntent accepted an id that is not \"-\"") - } - if _, err := f.LookupEntry(ctx, "/swblock/chunks/v1", "HEAD"); err == nil { - t.Fatal("unexpected HEAD") - } -} - -// A malformed intent entry fails the listing: GC must never miss a root. -func TestChunkRemote_ListIntentsRefusesMalformed(t *testing.T) { - f, b := newFakeFiler(), newFakeBlobs() - r, _ := NewChunkRemote(f, b, "/swblock/chunks/v1") - ctx := context.Background() - if _, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: 1, Epoch: 1, Holder: "h", Keys: []string{"k"}}); err != nil { - t.Fatal(err) - } - got, _ := r.ListIntents(ctx) - f.mu.Lock() - f.entries[path.Join("/swblock/chunks/v1/intents", got[0].ID)].Content = []byte("{not json") - f.mu.Unlock() - if _, err := r.ListIntents(ctx); err == nil { - t.Fatal("a malformed intent listed without error") - } -} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_keydomain_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_keydomain_test.go deleted file mode 100644 index bfb7fc2239..0000000000 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_keydomain_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "errors" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// The SeaweedFS remote enforces the chunk key domain (non-empty valid UTF-8) -// at Put and PutIntent before anything is written, and keys inside the -// domain, Unicode and owner-qualified ones included, round-trip exactly -// through the key bindings and the intent documents. -func TestChunkRemote_KeyDomainEnforcedBeforePersistence(t *testing.T) { - f, b := newFakeFiler(), newFakeBlobs() - r, err := NewChunkRemote(f, b, "/swblock/chunks/v1") - if err != nil { - t.Fatal(err) - } - ctx := context.Background() - for _, bad := range []string{"chunks/\xff/c0", "a\xc3"} { - if err := r.Put(ctx, bad, []byte("x")); !errors.Is(err, ErrInvalidKey) { - t.Errorf("Put(%q): %v, want ErrInvalidKey", bad, err) - } - if _, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: 1, Epoch: 1, Holder: "h", Keys: []string{"ok", bad}}); !errors.Is(err, ErrInvalidKey) { - t.Errorf("PutIntent with %q: %v, want ErrInvalidKey", bad, err) - } - } - if puts, _, _ := b.counts(); puts != 0 || len(f.allWritten()) != 0 { - t.Fatalf("refused calls wrote %d needles and %d entries", puts, len(f.allWritten())) - } - - data := bytes.Repeat([]byte{0x33}, 4096) - if err := r.Put(ctx, "chunks/é/ü-1", data); err != nil { - t.Fatalf("Put of a Unicode key: %v", err) - } - fresh, _ := NewChunkRemote(f, b, "/swblock/chunks/v1") // no cached binding - if got, err := fresh.Get(ctx, "chunks/é/ü-1"); err != nil || !bytes.Equal(got, data) { - t.Fatalf("Get of a Unicode key through its stored binding: %v", err) - } - keys := []string{"chunks/é/ü-1", "@v0/chunks/e1/c0/x-1", "日本/鍵"} - if _, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: 2, Epoch: 1, Holder: "h", Keys: keys}); err != nil { - t.Fatal(err) - } - got, err := fresh.ListIntents(ctx) - if err != nil || len(got) != 1 { - t.Fatalf("ListIntents: %+v %v", got, err) - } - for i, k := range keys { - if got[0].Keys[i] != k { - t.Fatalf("intent key %d listed as %q, stored %q", i, got[0].Keys[i], k) - } - } -} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_qualified_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_qualified_test.go deleted file mode 100644 index cad60afc67..0000000000 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_qualified_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "errors" - "testing" -) - -func qualifiedRemotes(t *testing.T) (*fakeFiler, *fakeBlobs, *ChunkRemote, *ChunkRemote) { - t.Helper() - f, b := newFakeFiler(), newFakeBlobs() - src, err := NewChunkRemote(f, b, "/swblock/chunks/v1") - if err != nil { - t.Fatal(err) - } - dst, err := NewChunkRemote(f, b, "/swblock/chunks/v2") - if err != nil { - t.Fatal(err) - } - return f, b, src, dst -} - -// A fork's HEAD names its parent's chunks as "@/"; Get must find -// the binding in the owner volume's keys/ directory. -func TestChunkRemote_GetResolvesQualifiedKey(t *testing.T) { - _, _, src, dst := qualifiedRemotes(t) - ctx := context.Background() - data := bytes.Repeat([]byte{0x5a}, 4096) - if err := src.Put(ctx, "chunks/e1/c0/n-1", data); err != nil { - t.Fatal(err) - } - got, err := dst.Get(ctx, "@v1/chunks/e1/c0/n-1") - if err != nil { - t.Fatalf("Get of a key owned by v1 from v2: %v", err) - } - if !bytes.Equal(got, data) { - t.Fatal("qualified Get returned other bytes") - } - // The plain key in v2's own directory does not exist. - if _, err := dst.Get(ctx, "chunks/e1/c0/n-1"); !errors.Is(err, ErrNotFound) { - t.Fatalf("unqualified Get of v1's key from v2: %v, want ErrNotFound", err) - } -} - -// Writes only ever go to the volume's own directory: a qualified key is -// refused before any needle or binding is written. -func TestChunkRemote_PutRefusesQualifiedKey(t *testing.T) { - f, b, _, dst := qualifiedRemotes(t) - err := dst.Put(context.Background(), "@v1/chunks/e1/c0/n-1", []byte("x")) - if !errors.Is(err, ErrInvalidKey) { - t.Fatalf("Put of a qualified key: %v, want ErrInvalidKey", err) - } - if puts, _, _ := b.counts(); puts != 0 { - t.Fatalf("a refused Put stored %d needles", puts) - } - if n := len(f.allWritten()); n != 0 { - t.Fatalf("a refused Put wrote %d filer entries", n) - } -} - -// The owner of a qualified key is one plain path element, so a key can never -// reach outside the chunk base or into the volume's own HEAD. -func TestChunkRemote_QualifiedKeyOwnerIsValidated(t *testing.T) { - _, _, _, dst := qualifiedRemotes(t) - for _, key := range []string{"@", "@v1", "@v1/", "@/k", "@../v1/k", "@./k", `@v\1/k`} { - if _, err := dst.Get(context.Background(), key); !errors.Is(err, ErrInvalidKey) { - t.Errorf("Get(%q): %v, want ErrInvalidKey", key, err) - } - } -} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_round.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_round.go deleted file mode 100644 index 26c22fffaf..0000000000 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_round.go +++ /dev/null @@ -1,391 +0,0 @@ -package chunkstore - -// Upload rounds over batch assign. The n objects of one round are split into -// G = min(8, ceil(n/64)) groups (object i goes to group i % G, as slot i / G), -// and each group takes one reservation for all its slots, made when its -// first object is uploaded. So a round costs G assigns instead of n, its -// objects still spread over up to G volumes, and a round with no upload -// makes none. -// -// A slot is frozen once an upload was sent for it: until that upload is -// resolved (stored and bound, or definitely not stored), every retry uses -// the same fid, whatever happens to the group's ranges. Ranges change only -// for slots with no upload outstanding: -// - a short grant is topped up by a reservation for the remaining slots; -// - a refusal before append (read-only or full volume) moves this and the -// later slots of the group to a fresh range, at most roundMaxReplacements -// times per group; -// - a range whose token is past its stated expiry (less a skew) is never -// sent to: an upload is sent under that deadline, and a slot frozen on -// an expired range is resolved by reading its fid back first (the exact -// bytes: bind it; definitely absent: a fresh range takes it). -// A rejected token (401) and used-up replacements end the object for good -// (storage.ErrChunkPutFinal). A reservation reply that arrives after the -// group's ranges changed is discarded (its ids stay unused). AssignCounts -// counts every reservation attempt, by reason, failed ones included. - -import ( - "bytes" - "context" - "errors" - "fmt" - "sync" - "sync/atomic" - "time" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -const ( - roundGroupSize = 64 - roundMaxGroups = 8 - roundMaxReplacements = 3 -) - -// AssignCounts counts the reservation attempts this remote's upload rounds -// made. Each attempt is counted once, by why it was made, whether or not it -// succeeded; Failed counts the ones that returned no usable range. -type AssignCounts struct { - Initial int64 // the first attempt of each group - Short int64 // top-ups after a short grant - Capacity int64 // replacements after a refusal before append - Expired int64 // replacements of ranges whose token expired before use - Retry int64 // attempts after a failed, lost or discarded reply - Failed int64 // attempts that returned an error or were discarded -} - -// Extra is every attempt beyond the initial ones. -func (a AssignCounts) Extra() int64 { return a.Short + a.Capacity + a.Expired + a.Retry } - -type assignCounters struct{ initial, short, capacity, expired, retry, failed atomic.Int64 } - -// AssignCounts reports the reservation attempts made so far. -func (r *ChunkRemote) AssignCounts() AssignCounts { - return AssignCounts{ - Initial: r.assigns.initial.Load(), - Short: r.assigns.short.Load(), - Capacity: r.assigns.capacity.Load(), - Expired: r.assigns.expired.Load(), - Retry: r.assigns.retry.Load(), - Failed: r.assigns.failed.Load(), - } -} - -var _ storage.ChunkPutRounds = (*ChunkRemote)(nil) - -// BeginPutRound starts a round of n objects of objSize bytes. Without batch -// support in the blob store, the round is one Put per object. -func (r *ChunkRemote) BeginPutRound(n, objSize int) storage.ChunkPutRound { - rb, ok := r.b.(rangeBlobs) - if !ok || n <= 0 { - return plainRound{r} - } - g := min(roundMaxGroups, (n+roundGroupSize-1)/roundGroupSize) - rd := &putRound{r: r, rb: rb, n: n, size: uint64(max(objSize, 0)), groups: make([]*roundGroup, g)} - for j := range rd.groups { - // Group j holds objects j, j+g, j+2g, ... - rd.groups[j] = &roundGroup{slots: (n - j + g - 1) / g, pins: map[int]slotPin{}, owners: map[int]chan struct{}{}} - } - return rd -} - -type plainRound struct{ r *ChunkRemote } - -func (p plainRound) Put(ctx context.Context, _ int, key string, data []byte) error { - return p.r.Put(ctx, key, data) -} - -type putRound struct { - r *ChunkRemote - rb rangeBlobs - n int - size uint64 - groups []*roundGroup -} - -type reserveReason int - -const ( - reserveInitial reserveReason = iota - reserveShort - reserveCapacity - reserveExpired - reserveRetry -) - -// roundGroup's ranges cover its slots [0, end) as consecutive spans. -type roundGroup struct { - slots int - - mu sync.Mutex - spans []roundSpan - ver int // bumped by every change to spans other than an append - reserving chan struct{} // non-nil while a reservation is in flight - replacements int - next reserveReason // why the next reservation is made - pins map[int]slotPin - owners map[int]chan struct{} // slot -> held by one Put at a time -} - -type roundSpan struct { - from int - rng blobRange -} - -// slotPin freezes a slot on the fid an upload was sent to; stored records -// that the upload succeeded (only its binding is outstanding). -type slotPin struct { - rng blobRange - off int - stored bool -} - -func (g *roundGroup) end() int { - if len(g.spans) == 0 { - return 0 - } - last := g.spans[len(g.spans)-1] - return last.from + last.rng.count -} - -// lookup returns the range and offset of slot s, if reserved. g.mu held. -func (g *roundGroup) lookup(s int) (blobRange, int, bool) { - for _, sp := range g.spans { - if s >= sp.from && s < sp.from+sp.rng.count { - return sp.rng, s - sp.from, true - } - } - return blobRange{}, 0, false -} - -// own makes the caller the only Put working on slot s until release. -func (g *roundGroup) own(ctx context.Context, s int) (release func(), err error) { - for { - g.mu.Lock() - held, busy := g.owners[s] - if !busy { - done := make(chan struct{}) - g.owners[s] = done - g.mu.Unlock() - return func() { - g.mu.Lock() - delete(g.owners, s) - g.mu.Unlock() - close(done) - }, nil - } - g.mu.Unlock() - select { - case <-held: - case <-ctx.Done(): - return nil, ctx.Err() - } - } -} - -func (g *roundGroup) pin(s int, p slotPin) { - g.mu.Lock() - g.pins[s] = p - g.mu.Unlock() -} - -func (g *roundGroup) unpin(s int) { - g.mu.Lock() - delete(g.pins, s) - g.mu.Unlock() -} - -func (g *roundGroup) pinned(s int) (slotPin, bool) { - g.mu.Lock() - defer g.mu.Unlock() - p, ok := g.pins[s] - return p, ok -} - -// retire drops slots s and later of the span using rng, so they take a fresh -// range (slots with an upload outstanding keep their pinned fid); it reports -// false once the group's replacements are used up. A span already replaced -// (by a concurrent upload) is left as is. -func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool { - g.mu.Lock() - defer g.mu.Unlock() - for k, sp := range g.spans { - if sp.rng.base != rng.base { - continue - } - if g.replacements >= roundMaxReplacements { - return false - } - g.replacements++ - g.next = why - g.ver++ - if s <= sp.from { - g.spans = g.spans[:k] - } else { - g.spans[k].rng.count = s - sp.from - g.spans = g.spans[:k+1] - } - return true - } - return true -} - -func (rd *putRound) count(why reserveReason) { - switch why { - case reserveInitial: - rd.r.assigns.initial.Add(1) - case reserveShort: - rd.r.assigns.short.Add(1) - case reserveCapacity: - rd.r.assigns.capacity.Add(1) - case reserveExpired: - rd.r.assigns.expired.Add(1) - case reserveRetry: - rd.r.assigns.retry.Add(1) - } -} - -// slot returns slot s's range and offset, reserving the group's remaining -// slots when s is not covered yet. Concurrent callers share one reservation; -// waiting follows ctx. A reply after ctx ends, or after the group's ranges -// changed while it was in flight, is not used. -func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange, int, error) { - for { - g.mu.Lock() - if rng, off, ok := g.lookup(s); ok { - g.mu.Unlock() - return rng, off, nil - } - if wait := g.reserving; wait != nil { - g.mu.Unlock() - select { - case <-wait: - continue - case <-ctx.Done(): - return blobRange{}, 0, ctx.Err() - } - } - from, ver, why := g.end(), g.ver, g.next - done := make(chan struct{}) - g.reserving = done - g.mu.Unlock() - - rd.count(why) - rng, err := rd.rb.reserve(ctx, g.slots-from, rd.size) - if err == nil { - err = ctx.Err() - } - g.mu.Lock() - g.reserving = nil - close(done) - switch { - case err != nil: - rd.r.assigns.failed.Add(1) - g.next = reserveRetry - case g.ver != ver || g.end() != from: - // The ranges changed while this reply was in flight: its ids - // stay unused, and the uncovered slots are reserved again. - rd.r.assigns.failed.Add(1) - g.next = reserveRetry - default: - g.spans = append(g.spans, roundSpan{from: from, rng: rng}) - g.next = reserveShort // only a short grant leaves slots uncovered now - } - g.mu.Unlock() - if err != nil { - return blobRange{}, 0, err - } - } -} - -// final marks an outcome no retry can change. -func final(err error) error { return errors.Join(storage.ErrChunkPutFinal, err) } - -// Put stores object i under key in its group's range and binds key to it. -func (rd *putRound) Put(ctx context.Context, i int, key string, data []byte) error { - if i < 0 || i >= rd.n { - return fmt.Errorf("chunkstore: round object %d outside a round of %d", i, rd.n) - } - name, err := rd.r.ownKeyName(key) - if err != nil { - return err - } - if rd.r.knownKey(key) { - return storage.ErrChunkKeyExists - } - g := rd.groups[i%len(rd.groups)] - s := i / len(rd.groups) - release, err := g.own(ctx, s) - if err != nil { - return err - } - defer release() - for { - if err := ctx.Err(); err != nil { - return err - } - p, frozen := g.pinned(s) - if !frozen { - rng, off, err := rd.slot(ctx, g, s) - if err != nil { - return err - } - p = slotPin{rng: rng, off: off} - } - fid, err := p.rng.fid(p.off) - if err != nil { - return err - } - if p.stored { - if err := rd.r.bindKey(ctx, key, name, fid, data, ""); err != nil { - return err - } - g.unpin(s) - return nil - } - dl, hasDL := p.rng.sendDeadline() - if hasDL && !time.Now().Before(dl) { - if frozen { - // An earlier upload to fid is unresolved: read it back - // before giving the fid up. - got, perr := rd.rb.probe(ctx, p.rng, p.off) - switch { - case perr == nil && bytes.Equal(got, data): - g.pin(s, slotPin{rng: p.rng, off: p.off, stored: true}) - continue - case perr == nil: - return final(fmt.Errorf("chunkstore: round object %d: %s holds other bytes", i, fid)) - case !errors.Is(perr, errBlobAbsent): - return fmt.Errorf("chunkstore: round object %d: earlier upload to %s unresolved: %w", i, fid, perr) - } - g.unpin(s) - } - if !g.retire(p.rng, s, reserveExpired) { - return final(fmt.Errorf("chunkstore: round object %d: token expired before upload, replacements used up", i)) - } - continue - } - pctx, cancel := ctx, context.CancelFunc(func() {}) - if hasDL { - pctx, cancel = context.WithDeadline(ctx, dl) - } - g.pin(s, p) // sent: frozen until resolved - err = rd.rb.putRange(pctx, p.rng, p.off, data) - cancel() - switch { - case err == nil: - g.pin(s, slotPin{rng: p.rng, off: p.off, stored: true}) - continue - case errors.Is(err, errRangeRefused): - g.unpin(s) // definitely not stored - if !g.retire(p.rng, s, reserveCapacity) { - return final(fmt.Errorf("chunkstore: round object %d: %w (replacements used up)", i, err)) - } - continue - case errors.Is(err, errRangeAuth): - g.unpin(s) // definitely not stored - return final(err) - } - return err // outcome unknown: the slot stays frozen on fid - } -} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go deleted file mode 100644 index a86a5f9e64..0000000000 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_round_test.go +++ /dev/null @@ -1,726 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "errors" - "fmt" - "strings" - "sync" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// rangeFake is a blob store with batch reservations: each reserve hands out -// a new volume id; puts are recorded by fid. Hooks shape the replies. -type rangeFake struct { - *fakeBlobs - mu sync.Mutex - nextVid int - reserves []int // requested counts, in order - grant func(requested int) int - auth func() string - refuse func(fid string) error // non-nil: the put fails with it (nothing stored) - // reserveHook, when set, runs before each reserve (call counts from 1); - // an error fails the reserve. It decides itself whether to follow ctx. - reserveHook func(ctx context.Context, call int) error - // putHook, when set, decides each put: store the bytes or not, and the - // error to return (a stored put with an error is a lost reply). - putHook func(ctx context.Context, fid string) (store bool, err error) - puts []string - putAuth map[string]string - putDL map[string]time.Time // deadline of the context each put was sent under -} - -func newRangeFake() *rangeFake { - return &rangeFake{fakeBlobs: newFakeBlobs(), nextVid: 1, putAuth: map[string]string{}, putDL: map[string]time.Time{}} -} - -func (b *rangeFake) reserve(ctx context.Context, n int, _ uint64) (blobRange, error) { - b.mu.Lock() - b.reserves = append(b.reserves, n) - call := len(b.reserves) - hook := b.reserveHook - b.mu.Unlock() - if hook != nil { - if err := hook(ctx, call); err != nil { - return blobRange{}, err - } - } - b.mu.Lock() - defer b.mu.Unlock() - count := n - if b.grant != nil { - count = b.grant(n) - } - auth := "" - if b.auth != nil { - auth = b.auth() - } - vid := b.nextVid - b.nextVid++ - return blobRange{base: fmt.Sprintf("%d,0a0b0c0d0e", vid), count: count, url: "fake:1", auth: auth}, nil -} - -func (b *rangeFake) putRange(ctx context.Context, r blobRange, i int, data []byte) error { - fid, err := r.fid(i) - if err != nil { - return err - } - b.mu.Lock() - b.puts = append(b.puts, fid) - b.putAuth[fid] = r.auth - if dl, ok := ctx.Deadline(); ok { - b.putDL[fid] = dl - } - refuse, hook := b.refuse, b.putHook - b.mu.Unlock() - store, perr := true, error(nil) - if refuse != nil { - if err := refuse(fid); err != nil { - store, perr = false, err - } - } - if hook != nil { - store, perr = hook(ctx, fid) - } - if store { - b.fakeBlobs.mu.Lock() - b.fakeBlobs.data[fid] = append([]byte(nil), data...) - b.fakeBlobs.mu.Unlock() - } - return perr -} - -func (b *rangeFake) probe(_ context.Context, r blobRange, i int) ([]byte, error) { - fid, err := r.fid(i) - if err != nil { - return nil, err - } - b.fakeBlobs.mu.Lock() - defer b.fakeBlobs.mu.Unlock() - d, ok := b.fakeBlobs.data[fid] - if !ok { - return nil, fmt.Errorf("%w %s", errBlobAbsent, fid) - } - return append([]byte(nil), d...), nil -} - -func (b *rangeFake) putList() []string { - b.mu.Lock() - defer b.mu.Unlock() - return append([]string(nil), b.puts...) -} - -func (b *rangeFake) reserveCounts() []int { - b.mu.Lock() - defer b.mu.Unlock() - return append([]int(nil), b.reserves...) -} - -func roundRemote(t *testing.T, b *rangeFake) *ChunkRemote { - t.Helper() - r, err := NewChunkRemote(newFakeFiler(), b, "/swblock/vols/v1") - if err != nil { - t.Fatal(err) - } - return r -} - -func roundKey(i int) string { return fmt.Sprintf("k%05d", i) } - -// putAll runs one round of n objects with w concurrent workers. -func putAll(t *testing.T, r *ChunkRemote, n, w int) error { - t.Helper() - rd := r.BeginPutRound(n, 4096) - var mu sync.Mutex - next := 0 - var first error - var wg sync.WaitGroup - for j := 0; j < w; j++ { - wg.Add(1) - go func() { - defer wg.Done() - for { - mu.Lock() - i := next - next++ - mu.Unlock() - if i >= n { - return - } - if err := rd.Put(context.Background(), i, roundKey(i), []byte(roundKey(i))); err != nil { - mu.Lock() - if first == nil { - first = err - } - mu.Unlock() - } - } - }() - } - wg.Wait() - return first -} - -func checkBound(t *testing.T, r *ChunkRemote, n int) { - t.Helper() - for i := 0; i < n; i++ { - got, err := r.Get(context.Background(), roundKey(i)) - if err != nil || !bytes.Equal(got, []byte(roundKey(i))) { - t.Fatalf("key %d: %q %v", i, got, err) - } - } -} - -// D objects take G = min(8, ceil(D/64)) reservations, balanced across the -// groups; D = 0 makes none. Every key is bound to its own fid. -func TestChunkRound_GroupsPerRound(t *testing.T) { - for _, c := range []struct{ d, g int }{{0, 0}, {1, 1}, {64, 1}, {65, 2}, {512, 8}, {513, 8}, {1000, 8}} { - t.Run(fmt.Sprint(c.d), func(t *testing.T) { - b := newRangeFake() - r := roundRemote(t, b) - if err := putAll(t, r, c.d, 16); err != nil { - t.Fatal(err) - } - got := b.reserveCounts() - if len(got) != c.g { - t.Fatalf("%d reservations %v for %d objects, want %d", len(got), got, c.d, c.g) - } - total, lo, hi := 0, c.d, 0 - for _, n := range got { - total += n - lo, hi = min(lo, n), max(hi, n) - } - if total != c.d || (c.g > 0 && hi-lo > 1) { - t.Fatalf("reservations %v: want %d ids balanced within one", got, c.d) - } - checkBound(t, r, c.d) - seen := map[string]bool{} - for i := 0; i < c.d; i++ { - fid := r.fids[roundKey(i)] - if seen[fid] { - t.Fatalf("fid %s bound twice", fid) - } - seen[fid] = true - } - if a := r.AssignCounts(); a.Initial != int64(c.g) || a.Extra() != 0 { - t.Fatalf("assign counts %+v, want %d initial, no extras", a, c.g) - } - }) - } -} - -// A short grant is topped up by a reservation for the remainder, counted as -// an extra, not an initial assign. -func TestChunkRound_ShortGrantReservesRemainder(t *testing.T) { - b := newRangeFake() - first := true - b.grant = func(n int) int { - if first { - first = false - return n / 2 - } - return n - } - r := roundRemote(t, b) - if err := putAll(t, r, 10, 4); err != nil { - t.Fatal(err) - } - if got := b.reserveCounts(); len(got) != 2 || got[0] != 10 || got[1] != 5 { - t.Fatalf("reservations %v, want [10 5]", got) - } - checkBound(t, r, 10) - if a := r.AssignCounts(); a.Initial != 1 || a.Short != 1 || a.Extra() != 1 { - t.Fatalf("assign counts %+v", a) - } -} - -// A definite capacity refusal leaves objects already stored on the old range -// alone and moves the rest of the group to a fresh range; a volume that keeps -// refusing ends the round after a bounded number of replacements. -func TestChunkRound_CapacityRefusalReplacesRemainder(t *testing.T) { - b := newRangeFake() - b.refuse = func(fid string) error { - // The first volume is full from its third id on. - if fid == "1,0a0b0c0d0e_2" || fid == "1,0a0b0c0d0e_3" { - return errRangeRefused - } - return nil - } - r := roundRemote(t, b) - if err := putAll(t, r, 6, 1); err != nil { - t.Fatal(err) - } - checkBound(t, r, 6) - if r.fids[roundKey(0)] != "1,0a0b0c0d0e" || r.fids[roundKey(1)] != "1,0a0b0c0d0e_1" { - t.Fatalf("committed prefix moved: %s %s", r.fids[roundKey(0)], r.fids[roundKey(1)]) - } - if got := b.reserveCounts(); len(got) != 2 || got[1] != 4 { - t.Fatalf("reservations %v, want a fresh range for the remaining 4", got) - } - if a := r.AssignCounts(); a.Initial != 1 || a.Capacity != 1 { - t.Fatalf("assign counts %+v", a) - } - - b2 := newRangeFake() - b2.refuse = func(string) error { return errRangeRefused } - r2 := roundRemote(t, b2) - err := putAll(t, r2, 3, 1) - if !errors.Is(err, errRangeRefused) { - t.Fatalf("always-full volumes: %v; want the refusal after bounded replacements", err) - } - if got := b2.reserveCounts(); len(got) != 1+roundMaxReplacements { - t.Fatalf("%d reservations %v; want 1 + %d replacements, then stop", len(got), got, roundMaxReplacements) - } -} - -// An expired token is never sent: the remainder gets a fresh range. A 401 is -// terminal: no replacement. -func TestChunkRound_TokenExpiryAndAuth(t *testing.T) { - b := newRangeFake() - calls := 0 - b.auth = func() string { - calls++ - if calls == 1 { - return jwtWithExp(time.Now().Add(-time.Minute).Unix()) - } - return jwtWithExp(time.Now().Add(time.Hour).Unix()) - } - r := roundRemote(t, b) - if err := putAll(t, r, 3, 1); err != nil { - t.Fatal(err) - } - checkBound(t, r, 3) - b.mu.Lock() - for fid, a := range b.putAuth { - if exp, ok := (blobRange{auth: a}).sendDeadline(); !ok || exp.Before(time.Now()) { - t.Fatalf("upload to %s sent with an expired token", fid) - } - } - b.mu.Unlock() - if a := r.AssignCounts(); a.Initial != 1 || a.Expired != 1 { - t.Fatalf("assign counts %+v", a) - } - - b2 := newRangeFake() - b2.refuse = func(string) error { return errRangeAuth } - r2 := roundRemote(t, b2) - if err := putAll(t, r2, 2, 1); !errors.Is(err, errRangeAuth) { - t.Fatalf("401: %v", err) - } - if got := b2.reserveCounts(); len(got) != 1 { - t.Fatalf("reservations %v after a 401; want no replacement", got) - } -} - -// A transient failure leaves the slot frozen: the retry sends the same fid. -func TestChunkRound_RetryKeepsTheSlot(t *testing.T) { - b := newRangeFake() - failed := false - b.refuse = func(fid string) error { - if fid == "1,0a0b0c0d0e_1" && !failed { - failed = true - return errors.New("connection reset") - } - return nil - } - r := roundRemote(t, b) - rd := r.BeginPutRound(2, 4096) - ctx := context.Background() - if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil { - t.Fatal(err) - } - if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err == nil { - t.Fatal("transient failure reported success") - } - if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err != nil { - t.Fatal(err) - } - b.mu.Lock() - puts := append([]string(nil), b.puts...) - b.mu.Unlock() - if len(puts) != 3 || puts[1] != "1,0a0b0c0d0e_1" || puts[2] != "1,0a0b0c0d0e_1" { - t.Fatalf("uploads %v; want the retry on the same fid", puts) - } - if got := b.reserveCounts(); len(got) != 1 { - t.Fatalf("reservations %v; a transient failure takes no new range", got) - } - // A bound key is never rebound. - if err := rd.Put(ctx, 1, roundKey(1), []byte("other")); !errors.Is(err, storage.ErrChunkKeyExists) { - t.Fatalf("rebinding a key: %v", err) - } -} - -// waitFor waits for ch, failing t after a bound. -func waitFor(t *testing.T, ch <-chan struct{}, what string) { - t.Helper() - select { - case <-ch: - case <-time.After(10 * time.Second): - t.Fatalf("timed out waiting for %s", what) - } -} - -// releaser closes a channel once; registered as cleanup before any worker -// that waits on it starts, so a failing test never strands that worker. -func releaser(t *testing.T) (ch chan struct{}, release func()) { - ch = make(chan struct{}) - var once sync.Once - release = func() { once.Do(func() { close(ch) }) } - t.Cleanup(release) - return ch, release -} - -// A reservation waiting on the filer ends with the caller's context when it -// follows it; one that ignores it is still joined (Put does not return -// before it), and its late successful reply never starts an upload. -func TestChunkRound_ReserveFollowsTheCaller(t *testing.T) { - t.Run("cooperative", func(t *testing.T) { - b := newRangeFake() - hold, _ := releaser(t) - entered := make(chan struct{}) - b.reserveHook = func(ctx context.Context, _ int) error { - close(entered) - select { - case <-hold: - return nil - case <-ctx.Done(): - return ctx.Err() - } - } - r := roundRemote(t, b) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - done := make(chan error, 1) - joined := false - t.Cleanup(func() { // ends and joins the worker whatever happens below - cancel() - if joined { - return - } - select { - case <-done: - case <-time.After(10 * time.Second): - t.Error("Put never returned") - } - }) - go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }() - waitFor(t, entered, "the reservation call") - cancel() - select { - case err := <-done: - joined = true - if !errors.Is(err, context.Canceled) { - t.Fatalf("cancelled reservation: %v", err) - } - case <-time.After(10 * time.Second): - t.Fatal("Put did not end with its context") - } - }) - t.Run("uncooperative", func(t *testing.T) { - b := newRangeFake() - hold, release := releaser(t) - entered := make(chan struct{}) - b.reserveHook = func(context.Context, int) error { close(entered); <-hold; return nil } // ignores ctx - r := roundRemote(t, b) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - done := make(chan error, 1) - go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }() - t.Cleanup(func() { // joins the worker whatever happens below - release() - select { - case <-done: - case <-time.After(10 * time.Second): - t.Error("Put never returned") - } - }) - waitFor(t, entered, "the reservation call") - cancel() - select { - case err := <-done: - done <- err - t.Fatalf("Put returned (%v) while its admitted reservation call was still running", err) - case <-time.After(200 * time.Millisecond): - } - release() // the late reply is a success - select { - case err := <-done: - done <- err - if !errors.Is(err, context.Canceled) { - t.Fatalf("late reply after the caller gave up: %v", err) - } - case <-time.After(10 * time.Second): - t.Fatal("Put did not return after its reservation call did") - } - if puts := b.putList(); len(puts) != 0 { - t.Fatalf("uploads %v after the caller gave up", puts) - } - }) -} - -// A replacement reply that arrives after a lower slot retired the group's -// ranges is discarded: the group is reserved again from its first uncovered -// slot, so no slot is left uncovered (and no zero-id reservation is asked). -func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) { - b := newRangeFake() - r := roundRemote(t, b) - rd := r.BeginPutRound(4, 4096).(*putRound) - g := rd.groups[0] - second := make(chan struct{}) - var secondOnce sync.Once - release, releaseAll := releaser(t) - b.reserveHook = func(ctx context.Context, call int) error { - if call == 2 { - secondOnce.Do(func() { close(second) }) - select { - case <-release: - case <-ctx.Done(): - return ctx.Err() - } - } - return nil - } - slot0Sent := make(chan struct{}) - b.putHook = func(ctx context.Context, fid string) (bool, error) { - switch fid { - case "1,0a0b0c0d0e_1": // slot 1: refused at once - return false, errRangeRefused - case "1,0a0b0c0d0e": // slot 0: sent, refused once the replacement is in flight - close(slot0Sent) - select { - case <-second: - case <-ctx.Done(): - return false, ctx.Err() - } - return false, errRangeRefused - } - return true, nil - } - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - defer cancel() - errs := make(chan error, 2) - started := 0 - t.Cleanup(func() { // release and join every worker started - releaseAll() - cancel() - for ; started > 0; started-- { - select { - case <-errs: - case <-time.After(10 * time.Second): - t.Error("a round worker never returned") - return - } - } - }) - started++ - go func() { errs <- rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))) }() - waitFor(t, slot0Sent, "slot 0's upload") - started++ - go func() { errs <- rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))) }() - waitFor(t, second, "the replacement reservation") - deadline := time.Now().Add(10 * time.Second) - for { // slot 0's refusal retires the rest of the group meanwhile - g.mu.Lock() - v := g.ver - g.mu.Unlock() - if v == 2 { - break - } - if time.Now().After(deadline) { - t.Fatalf("group version %d; slot 0's refusal never retired the range", v) - } - time.Sleep(time.Millisecond) - } - releaseAll() - for started > 0 { - select { - case err := <-errs: - started-- // joined, before any Fatal: cleanup must not wait for it again - if err != nil { - t.Fatal(err) - } - case <-time.After(10 * time.Second): - t.Fatal("a round worker did not finish") - } - } - got := b.reserveCounts() - for _, n := range got { - if n <= 0 { - t.Fatalf("reservations %v: asked for %d ids", got, n) - } - } - if len(got) != 3 || got[0] != 4 || got[1] != 3 || got[2] != 4 { - t.Fatalf("reservations %v; want [4 3 4] (the stale [1,4) reply discarded)", got) - } - for i := 0; i < 2; i++ { - if fid := r.fids[roundKey(i)]; !strings.HasPrefix(fid, "3,") { - t.Fatalf("slot %d bound to %s; want the fresh range", i, fid) - } - } - if a := r.AssignCounts(); a.Initial != 1 || a.Capacity != 1 || a.Retry != 1 || a.Failed != 1 { - t.Fatalf("assign counts %+v", a) - } -} - -// A lost reservation reply is counted: the retry is an extra attempt. -func TestChunkRound_LostReservationReplyIsCounted(t *testing.T) { - b := newRangeFake() - b.reserveHook = func(_ context.Context, call int) error { - if call == 1 { - return errors.New("lost assign reply") - } - return nil - } - r := roundRemote(t, b) - rd := r.BeginPutRound(1, 4096) - ctx := context.Background() - if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); err == nil { - t.Fatal("lost reply reported success") - } - if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); err != nil { - t.Fatal(err) - } - if a := r.AssignCounts(); a.Initial != 1 || a.Retry != 1 || a.Failed != 1 || a.Extra() != 1 { - t.Fatalf("assign counts %+v; want 1 initial + 1 retry, 1 failed", a) - } -} - -// An upload whose reply was lost keeps its fid: a retry after the group's -// lower slot retired the range, or after the token expired, does not move -// it. Past expiry the fid is read back: the exact bytes are bound there, -// definitely absent bytes go to a fresh range. -func TestChunkRound_AmbiguousUploadKeepsItsFid(t *testing.T) { - ctx := context.Background() - t.Run("lower slot retires the range", func(t *testing.T) { - b := newRangeFake() - lost := true - b.putHook = func(_ context.Context, fid string) (bool, error) { - switch { - case fid == "1,0a0b0c0d0e_1" && lost: - lost = false - return false, errors.New("connection reset") // outcome unknown to the client - case fid == "1,0a0b0c0d0e": - return false, errRangeRefused - } - return true, nil - } - r := roundRemote(t, b) - rd := r.BeginPutRound(2, 4096) - if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err == nil { - t.Fatal("lost reply reported success") - } - if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil { - t.Fatal(err) - } - if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err != nil { - t.Fatal(err) - } - if fid := r.fids[roundKey(1)]; fid != "1,0a0b0c0d0e_1" { - t.Fatalf("retried slot bound to %s; want its first fid", fid) - } - if fid := r.fids[roundKey(0)]; !strings.HasPrefix(fid, "2,") { - t.Fatalf("refused slot bound to %s; want the fresh range", fid) - } - }) - for _, stored := range []bool{true, false} { - t.Run(fmt.Sprintf("token expires, stored=%v", stored), func(t *testing.T) { - b := newRangeFake() - calls := 0 - b.auth = func() string { - calls++ - if calls == 1 { // expires (less skew) about a second from now - return jwtWithExp(time.Now().Add(jwtSendSkew + time.Second).Unix()) - } - return jwtWithExp(time.Now().Add(time.Hour).Unix()) - } - lost := true - b.putHook = func(context.Context, string) (bool, error) { - if lost { - lost = false - return stored, errors.New("reply lost") - } - return true, nil - } - r := roundRemote(t, b) - rd := r.BeginPutRound(1, 4096) - if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err == nil { - t.Fatal("lost reply reported success") - } - b.mu.Lock() - first := b.putAuth["1,0a0b0c0d0e"] - b.mu.Unlock() - dl, _ := (blobRange{auth: first}).sendDeadline() - time.Sleep(time.Until(dl) + 10*time.Millisecond) - if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil { - t.Fatal(err) - } - fid, puts := r.fids[roundKey(0)], b.putList() - if stored { - if fid != "1,0a0b0c0d0e" || len(puts) != 1 { - t.Fatalf("stored upload: bound %s after uploads %v; want its first fid, no resend", fid, puts) - } - return - } - if !strings.HasPrefix(fid, "2,") || len(puts) != 2 { - t.Fatalf("absent upload: bound %s after uploads %v; want a fresh range", fid, puts) - } - if a := r.AssignCounts(); a.Initial != 1 || a.Expired != 1 { - t.Fatalf("assign counts %+v", a) - } - }) - } -} - -// An upload is sent under its token's send deadline: a queued upload ends -// there, not at the caller's later deadline. -func TestChunkRound_UploadCarriesTheTokenDeadline(t *testing.T) { - b := newRangeFake() - b.auth = func() string { return jwtWithExp(time.Now().Add(jwtSendSkew + time.Second).Unix()) } - b.putHook = func(ctx context.Context, _ string) (bool, error) { - <-ctx.Done() // queued until its context ends - return false, ctx.Err() - } - r := roundRemote(t, b) - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - start := time.Now() - err := r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) - if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 10*time.Second { - t.Fatalf("queued upload: %v after %v; want it ended at the token's deadline", err, time.Since(start)) - } - b.mu.Lock() - defer b.mu.Unlock() - for f, a := range b.putAuth { - dl, _ := (blobRange{auth: a}).sendDeadline() - if !b.putDL[f].Equal(dl) { - t.Fatalf("upload to %s sent under deadline %v; want the token's %v", f, b.putDL[f], dl) - } - } -} - -// A rejected token and used-up replacements are final for the caller; a -// transient failure is not. -func TestChunkRound_FinalOutcomes(t *testing.T) { - put := func(b *rangeFake) error { - return roundRemote(t, b).BeginPutRound(1, 4096).Put(context.Background(), 0, roundKey(0), []byte("x")) - } - b := newRangeFake() - b.refuse = func(string) error { return errRangeAuth } - if err := put(b); !errors.Is(err, storage.ErrChunkPutFinal) { - t.Fatalf("401: %v; want final", err) - } - b2 := newRangeFake() - b2.refuse = func(string) error { return errRangeRefused } - if err := put(b2); !errors.Is(err, storage.ErrChunkPutFinal) { - t.Fatalf("replacements used up: %v; want final", err) - } - b3 := newRangeFake() - b3.refuse = func(string) error { return errors.New("connection reset") } - if err := put(b3); err == nil || errors.Is(err, storage.ErrChunkPutFinal) { - t.Fatalf("transient failure: %v; want retryable", err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go deleted file mode 100644 index 70a1f172ff..0000000000 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go +++ /dev/null @@ -1,328 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "crypto/sha256" - "errors" - "path/filepath" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -const testRoot = "/swblock/chunks/v1" - -func newTestRemote(t *testing.T, f *fakeFiler, b *fakeBlobs) *ChunkRemote { - t.Helper() - r, err := NewChunkRemote(f, b, testRoot) - if err != nil { - t.Fatal(err) - } - return r -} - -func ref(key string, data []byte) storage.ChunkRef { - return storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} -} - -func head(epoch uint64, holder string, lsn uint64, chunks map[uint64]storage.ChunkRef) storage.ChunkHead { - return storage.ChunkHead{Epoch: epoch, Holder: holder, RemoteLSN: lsn, Chunks: chunks} -} - -func isPrecondition(err error) bool { return errors.Is(err, storage.ErrChunkHeadPrecondition) } - -func TestChunkRemote_RootMustBeCleanAbsolute(t *testing.T) { - for _, root := range []string{"", "/", "rel/dir", "/a/../b", "/a/"} { - if _, err := NewChunkRemote(newFakeFiler(), newFakeBlobs(), root); err == nil { - t.Errorf("root %q accepted", root) - } - } -} - -func TestChunkRemote_HeadRoundTripAndCAS(t *testing.T) { - ctx := context.Background() - f, b := newFakeFiler(), newFakeBlobs() - r := newTestRemote(t, f, b) - - h0, err := r.GetHead(ctx) - if err != nil || h0.Gen != 0 || len(h0.Chunks) != 0 { - t.Fatalf("absent HEAD = %+v, %v; want the zero HEAD", h0, err) - } - d := bytes.Repeat([]byte{7}, 64) - if err := r.Put(ctx, "chunks/e1/c3/n-1", d); err != nil { - t.Fatal(err) - } - want := head(1, "a", 42, map[uint64]storage.ChunkRef{3: ref("chunks/e1/c3/n-1", d)}) - legacy := want.Chunks[3] - legacy.Encoding, legacy.BirthLSN = "full", want.RemoteLSN - want.Chunks[3] = legacy - want, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, want, 4096) - if err != nil { - t.Fatal(err) - } - gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, want) - if err != nil || gen != 1 { - t.Fatalf("first CAS = %d, %v; want gen 1", gen, err) - } - for _, id := range intents { - if err := r.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - got, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if got.Gen != 1 || got.Epoch != 1 || got.Holder != "a" || got.RemoteLSN != 42 || len(got.Chunks) != 1 || got.Chunks[3] != want.Chunks[3] { - t.Fatalf("HEAD read back = %+v; want gen 1 of %+v", got, want) - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, want); !isPrecondition(err) { - t.Fatalf("second first-HEAD CAS: %v; want precondition", err) - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 0}, want); !isPrecondition(err) { - t.Fatalf("CAS at a wrong epoch: %v; want precondition", err) - } - gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(1, "a", 50, nil)) - if err != nil || gen != 2 { - t.Fatalf("CAS at the current version = %d, %v; want gen 2", gen, err) - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(1, "a", 60, nil)); !isPrecondition(err) { - t.Fatalf("CAS at a stale generation: %v; want precondition", err) - } - got, _ = r.GetHead(ctx) - if got.Gen != 2 || got.RemoteLSN != 50 || len(got.Chunks) != 0 { - t.Fatalf("HEAD after refused CAS = %+v; want gen 2 at LSN 50", got) - } - for _, e := range f.allWritten() { - if len(e.GetChunks()) != 0 { - t.Fatalf("entry %s written with filer chunks", e.Name) - } - } -} - -// An absent HEAD has epoch 0; an expectation of gen 0 at another epoch can -// never match and must not create HEAD. -func TestChunkRemote_AbsentHeadOnlyMatchesZeroVersion(t *testing.T) { - ctx := context.Background() - f := newFakeFiler() - r := newTestRemote(t, f, newFakeBlobs()) - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Epoch: 2}, head(2, "a", 1, nil)); !isPrecondition(err) { - t.Fatalf("CAS {0,2} on an absent HEAD: %v; want precondition", err) - } - if h, _ := r.GetHead(ctx); h.Gen != 0 { - t.Fatalf("HEAD created by a refused CAS: %+v", h) - } -} - -func TestChunkRemote_EpochNeverLowers(t *testing.T) { - ctx := context.Background() - r := newTestRemote(t, newFakeFiler(), newFakeBlobs()) - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, head(5, "b", 1, nil)); err != nil { - t.Fatal(err) - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 5}, head(4, "a", 2, nil)); !isPrecondition(err) { - t.Fatalf("CAS lowering the epoch: %v; want precondition", err) - } - if h, _ := r.GetHead(ctx); h.Gen != 1 || h.Epoch != 5 || h.Holder != "b" { - t.Fatalf("HEAD after refused lowering = %+v", h) - } -} - -// A takeover raises the epoch; the old holder's next CAS, at the version -// it read, is refused (the chunk layer then fences). -func TestChunkRemote_TakeoverRefusesOldHolder(t *testing.T) { - ctx := context.Background() - f, b := newFakeFiler(), newFakeBlobs() - a, nb := newTestRemote(t, f, b), newTestRemote(t, f, b) - if _, err := a.CASHead(ctx, storage.ChunkHeadVersion{}, head(1, "a", 1, nil)); err != nil { - t.Fatal(err) - } - if _, err := nb.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(2, "b", 1, nil)); err != nil { - t.Fatal(err) - } - if _, err := a.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(1, "a", 9, nil)); !isPrecondition(err) { - t.Fatalf("old holder's CAS after takeover: %v; want precondition", err) - } -} - -// Only a definite refusal is a precondition failure. An error whose -// outcome is unknown must come back as something else, whether or not -// the update was applied, so the chunk layer re-reads HEAD. -func TestChunkRemote_UncertainCASIsNotPrecondition(t *testing.T) { - ctx := context.Background() - boom := errors.New("transport reset") - for _, applied := range []bool{false, true} { - f := newFakeFiler() - r := newTestRemote(t, f, newFakeBlobs()) - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, head(1, "a", 1, nil)); err != nil { - t.Fatal(err) - } - if applied { - f.failUpdateAfterApply = func(string) error { return boom } - } else { - f.failUpdate = func(string) error { return boom } - } - _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(1, "a", 2, nil)) - if err == nil || isPrecondition(err) || !errors.Is(err, boom) { - t.Fatalf("applied=%v: uncertain CAS returned %v; want the transport error, not a precondition", applied, err) - } - f.failUpdate, f.failUpdateAfterApply = nil, nil - h, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if wantGen := map[bool]uint64{false: 1, true: 2}[applied]; h.Gen != wantGen { - t.Fatalf("applied=%v: HEAD re-read gen %d; want %d", applied, h.Gen, wantGen) - } - } -} - -func TestChunkRemote_KeysAreWriteOnce(t *testing.T) { - ctx := context.Background() - f, b := newFakeFiler(), newFakeBlobs() - r := newTestRemote(t, f, b) - first, second := []byte("first"), []byte("second") - if err := r.Put(ctx, "chunks/e1/c0/n-1", first); err != nil { - t.Fatal(err) - } - if err := r.Put(ctx, "chunks/e1/c0/n-1", second); !errors.Is(err, storage.ErrChunkKeyExists) { - t.Fatalf("rebinding a key on the same client: %v; want ErrChunkKeyExists", err) - } - if puts, _, _ := b.counts(); puts != 1 { // a known key uploads no orphan needle - t.Fatalf("refused rebind on the same client stored %d needles; want 1", puts) - } - // A second client has no cache: the exclusive create is the authority. - other := newTestRemote(t, f, b) - if err := other.Put(ctx, "chunks/e1/c0/n-1", second); !errors.Is(err, storage.ErrChunkKeyExists) { - t.Fatalf("rebinding a key from another client: %v; want ErrChunkKeyExists", err) - } - for _, c := range []*ChunkRemote{r, other, newTestRemote(t, f, b)} { - got, err := c.Get(ctx, "chunks/e1/c0/n-1") - if err != nil || !bytes.Equal(got, first) { - t.Fatalf("Get after refused rebind = %q, %v; want %q", got, err, first) - } - } - if _, err := r.Get(ctx, "chunks/e1/c0/never"); err == nil { - t.Fatal("Get of an unbound key succeeded") - } - if err := r.Delete(ctx, "chunks/e1/c0/n-1"); !errors.Is(err, ErrDeleteUnsupported) { - t.Fatalf("Delete: %v; want ErrDeleteUnsupported", err) - } -} - -// A HEAD entry that exists but cannot be trusted is an error, never the -// zero HEAD (which would let a new holder start over the volume). -func TestChunkRemote_UntrustedHeadIsAnError(t *testing.T) { - ctx := context.Background() - cases := map[string]func(e *filerpb.Entry){ - "filer chunks": func(e *filerpb.Entry) { e.Chunks = []*filerpb.FileChunk{{FileId: "3,01"}} }, - "wrong kind": func(e *filerpb.Entry) { e.Extended[extKind] = []byte("head") }, - "gen disagrees": func(e *filerpb.Entry) { e.Extended[extGen] = []byte("9") }, - "epoch disagrees": func(e *filerpb.Entry) { e.Extended[extEpoch] = []byte("9") }, - "holder disagrees": func(e *filerpb.Entry) { e.Extended[extHolder] = []byte("z") }, - "not json": func(e *filerpb.Entry) { e.Content = []byte("{") }, - "no content": func(e *filerpb.Entry) { e.Content = nil }, - "generation 0": func(e *filerpb.Entry) { - e.Content = bytes.Replace(e.Content, []byte(`"gen":1`), []byte(`"gen":0`), 1) - e.Extended[extGen] = []byte("0") - }, - "bad chunk hash": func(e *filerpb.Entry) { - e.Content = bytes.Replace(e.Content, []byte(`"sha256":"`), []byte(`"sha256":"zz`), 1) - }, - "unsupported format": func(e *filerpb.Entry) { - e.Content = bytes.Replace(e.Content, []byte(`"format":1`), []byte(`"format":2`), 1) - }, - } - for name, corrupt := range cases { - t.Run(name, func(t *testing.T) { - f := newFakeFiler() - r := newTestRemote(t, f, newFakeBlobs()) - h := head(1, "a", 1, map[uint64]storage.ChunkRef{0: ref("k", []byte("x"))}) - h.Gen = 1 - if err := f.CreateEntry(ctx, testRoot, legacyHeadFixture(t, h), true); err != nil { - t.Fatal(err) - } - f.mu.Lock() - corrupt(f.entries[testRoot+"/"+headName]) - f.mu.Unlock() - got, err := r.GetHead(ctx) - if err == nil { - t.Fatalf("untrusted HEAD read as %+v", got) - } - }) - } -} - -// The chunk layer end to end over this remote: a host writes and captures, -// then a fresh host reads every block lazily from HEAD. -func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) { - ctx := context.Background() - const blocks, chunkBlocks = 64, 8 - f, b := newFakeFiler(), newFakeBlobs() - dir := t.TempDir() - - attach := func(name string, fresh bool) (*storage.WALStore, storage.ChunkLayer) { - p := filepath.Join(dir, name) - s, err := storage.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks}) - if err != nil { - t.Fatal(err) - } - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - r := newTestRemote(t, f, b) - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ - ChunkBlocks: chunkBlocks, Epoch: 1, Holder: name, FreshFromHead: fresh, - }) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = s.Close() }) - return s, l - } - - src, layer := attach("a", true) // a new, empty source volume - want := map[uint32][]byte{} - for _, lba := range []uint32{0, 9, 17, 63} { - want[lba] = bytes.Repeat([]byte{byte(lba + 1)}, 4096) - if _, err := src.Write(lba, want[lba]); err != nil { - t.Fatal(err) - } - } - if _, err := src.Sync(); err != nil { - t.Fatal(err) - } - h, err := layer.Capture(ctx) - if err != nil { - t.Fatalf("Capture: %v", err) - } - if layer.RemoteLSN() != h { - t.Fatalf("RemoteLSN %d after capture at %d", layer.RemoteLSN(), h) - } - puts, _, _ := b.counts() - if puts != 5 { // chunks 0, 1, 2 and 7, plus their manifest segment - t.Fatalf("capture stored %d needles; want 4 data chunks plus one manifest", puts) - } - _ = src.Close() - - dst, _ := attach("b", true) - zero := make([]byte, 4096) - for lba := uint32(0); lba < blocks; lba++ { - got, err := dst.Read(lba) - if err != nil { - t.Fatalf("fresh host read %d: %v", lba, err) - } - exp, ok := want[lba] - if !ok { - exp = zero - } - if !bytes.Equal(got, exp) { - t.Fatalf("fresh host block %d = %x...; want %x...", lba, got[:4], exp[:4]) - } - } - if _, gets, _ := b.counts(); gets != 5 { // four data chunks and one manifest fetched once - t.Fatalf("fresh host fetched %d needles; want 4 data chunks plus one manifest", gets) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/clean_b.go b/seaweed-block/core/frontend/chunkstore/clean_b.go new file mode 100644 index 0000000000..5fa92ad5ed --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/clean_b.go @@ -0,0 +1,65 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "strconv" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// cleanPage is the number of pool names one removal step plans at once +// (a variable only so tests can page with a small one). +var cleanPage uint32 = 1000 + +// CleanResult is what one cleaning pass removed. +type CleanResult struct { + Shards int // pool shards listed + Planned int // candidate names read + Removed int // names deleted +} + +// RemoveUnreachableAll is the cleaning's removal step over every pool shard +// of v, page by page, for a holder whose clean(session) is open on HEAD +// (opened by the holder's layout remote, LayoutRemote.Clean): +// layout.RemoveUnreachable validates HEAD after reading each page's tags, +// so it removes nothing unless clean(session) is this holder's. +func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me layout.HolderID, session string) (res CleanResult, err error) { + s, r, err := c.open(v) + if err != nil { + return res, err + } + shards, err := s.List(ctx, path.Join(c.base, v.Dir(), layout.PoolDir)) + if err != nil { + return res, err + } + for _, name := range shards { + shard, perr := strconv.ParseUint(name, 10, 64) + if perr != nil || strconv.FormatUint(shard, 10) != name { + return res, errors.Join(layout.ErrCorrupt, errors.New("chunkstore: pool shard "+strconv.Quote(name))) + } + res.Shards++ + after := "" + for { + page, err := s.ListChunkCandidates(ctx, shard, after, cleanPage) + if err != nil { + return res, err + } + if len(page) == 0 { + break + } + res.Planned += len(page) + removed, err := layout.RemoveUnreachable(ctx, s, r, s, me, session, shard, page) + res.Removed += len(removed) + if err != nil { + return res, err + } + if uint32(len(page)) < cleanPage { + break + } + after = page[len(page)-1].String() + } + } + return res, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/clean_b_test.go b/seaweed-block/core/frontend/chunkstore/clean_b_test.go new file mode 100644 index 0000000000..5b6c3b1e02 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/clean_b_test.go @@ -0,0 +1,300 @@ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "path" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// cleanFixture is v with chunk 1 live in the current root and in snapshot +// "s", plus orphans: chunk 2 in shard 0 and chunk ShardSize+3 in shard 1. +func cleanFixture(t *testing.T) (*BCatalog, VolumeRef, *LayoutStore, []layout.ChunkName) { + t.Helper() + ctx := context.Background() + c, err := NewBCatalog(NewMemFiler(), newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + v := newRef(t, "v1") + if _, err := c.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + commitSnapshot(t, c, v, bytes.Repeat([]byte{7}, 4096), "s") + s, err := c.Store(v) + if err != nil { + t.Fatal(err) + } + var orphans []layout.ChunkName + for _, idx := range []uint64{2, layout.ShardSize + 3} { + data := bytes.Repeat([]byte{byte(idx)}, 4096) + n := layout.NameChunk(idx, data) + if err := layout.EnsureObject(ctx, s, n.Path(), data, "dead-session"); err != nil { + t.Fatal(err) + } + orphans = append(orphans, n) + } + // A real filer lists the shard directories it created for these + // entries; the in-memory filer keeps only the entries, so add them. + pool := path.Join(c.base, v.Dir(), layout.PoolDir) + for _, d := range []string{"0", "1"} { + if err := c.f.CreateEntry(ctx, pool, &filerpb.Entry{Name: d, IsDirectory: true}, false); err != nil { + t.Fatal(err) + } + } + return c, v, s, orphans +} + +func present(t *testing.T, s *LayoutStore, n layout.ChunkName) bool { + t.Helper() + _, found, err := s.Stat(context.Background(), n.Path()) + if err != nil { + t.Fatal(err) + } + return found +} + +var cleanHolder = layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + +// cleanVia runs one cleaning pass the way the holder's maintenance does: +// through the holder's layout remote (LayoutRemote.Clean) with the +// catalog's removal step. +func cleanVia(ctx context.Context, c *BCatalog, v VolumeRef, me layout.HolderID) (CleanResult, *LayoutRemote, error) { + r, err := NewLayoutRemote(c, v, me) + if err != nil { + return CleanResult{}, nil, err + } + var res CleanResult + err = r.Clean(ctx, func(ctx context.Context, me layout.HolderID, s string) error { + var rerr error + res, rerr = c.RemoveUnreachableAll(ctx, v, me, s) + return rerr + }) + return res, r, err +} + +// The holder's pass removes every orphan in every shard, keeps what the +// current root and the snapshot name, and leaves HEAD idle. With a page of +// one name the shard cursor is exercised too. +func TestBCatalog_CleanRemovesOnlyUnreachable(t *testing.T) { + ctx := context.Background() + prev := cleanPage + cleanPage = 1 + t.Cleanup(func() { cleanPage = prev }) + c, v, s, orphans := cleanFixture(t) + live := layout.NameChunk(1, bytes.Repeat([]byte{7}, 4096)) + + res, _, err := cleanVia(ctx, c, v, cleanHolder) + if err != nil { + t.Fatal(err) + } + if res.Shards != 2 || res.Planned != 3 || res.Removed != 2 { + t.Fatalf("clean: %+v; want 2 shards, 3 planned, 2 removed", res) + } + for _, n := range orphans { + if present(t, s, n) { + t.Fatalf("orphan %s survived the cleaning", n) + } + } + if !present(t, s, live) { + t.Fatal("the chunk the roots name was removed") + } + h, _, err := c.ReadHead(ctx, v) + if err != nil || h.Activity.Kind != layout.ActIdle { + t.Fatalf("HEAD after clean: %+v %v; want idle", h.Activity, err) + } + // A second pass finds nothing more. + if res, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil || res.Removed != 0 { + t.Fatalf("second clean: %+v %v", res, err) + } +} + +// Only the holder at HEAD's epoch cleans: another holder, an old epoch or +// another claim is refused at Begin, and nothing is removed. +func TestBCatalog_CleanIsHolderOnly(t *testing.T) { + ctx := context.Background() + c, v, s, orphans := cleanFixture(t) + for name, me := range map[string]layout.HolderID{ + "other holder": {Epoch: 1, Holder: "x/y", ClaimID: "k"}, + "other claim": {Epoch: 1, Holder: "s/r", ClaimID: "other"}, + "old epoch": {Epoch: 0, Holder: "s/r", ClaimID: "k"}, + } { + if _, _, err := cleanVia(ctx, c, v, me); err == nil { + t.Fatalf("%s: clean succeeded; want refused", name) + } + } + for _, n := range orphans { + if !present(t, s, n) { + t.Fatalf("a refused clean removed %s", n) + } + } + h, _, err := c.ReadHead(ctx, v) + if err != nil || h.Activity.Kind != layout.ActIdle { + t.Fatalf("HEAD after refusals: %+v %v; want idle", h.Activity, err) + } +} + +// While the holder's cut session is open the cleaning cannot begin +// (ErrBusy) and removes nothing; the open session is left as it was. +func TestBCatalog_CleanWaitsForAnOpenSnapshot(t *testing.T) { + ctx := context.Background() + c, v, s, orphans := cleanFixture(t) + r, err := NewLayoutRemote(c, v, cleanHolder) + if err != nil { + t.Fatal(err) + } + snap, err := r.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if err := r.Clean(ctx, func(ctx context.Context, me layout.HolderID, s string) error { + _, rerr := c.RemoveUnreachableAll(ctx, v, me, s) + return rerr + }); !errors.Is(err, layout.ErrBusy) { + t.Fatalf("clean during a snapshot: %v; want ErrBusy", err) + } + for _, n := range orphans { + if !present(t, s, n) { + t.Fatalf("clean during a snapshot removed %s", n) + } + } + h, _, err := c.ReadHead(ctx, v) + if err != nil || h.Activity != (layout.Activity{Kind: layout.ActSnap, Session: snap}) { + t.Fatalf("HEAD after the refused clean: %+v %v; want the snapshot session open", h.Activity, err) + } +} + +// A pass that fails after Begin still closes the cleaning, so snapshots are +// not blocked by it. +func TestBCatalog_CleanClosesOnError(t *testing.T) { + ctx := context.Background() + c, v, _, _ := cleanFixture(t) + s, err := c.Store(v) + if err != nil { + t.Fatal(err) + } + pool := path.Join(c.base, v.Dir(), layout.PoolDir) + if err := s.f.CreateEntry(ctx, pool, layoutEntry("x", nil), true); err != nil { + t.Fatal(err) + } + if _, _, err := cleanVia(ctx, c, v, cleanHolder); !errors.Is(err, layout.ErrCorrupt) { + t.Fatalf("clean over a malformed shard: %v; want ErrCorrupt", err) + } + h, _, err := c.ReadHead(ctx, v) + if err != nil || h.Activity.Kind != layout.ActIdle { + t.Fatalf("HEAD after a failed clean: %+v %v; want idle", h.Activity, err) + } +} + +// commitImage commits, as cleanHolder in a fresh session, the manifest next +// (prev is HEAD's current manifest), uploading data, at position, with a +// named snapshot of it. +func commitImage(t *testing.T, s *LayoutStore, vol string, session string, prev, next map[uint64]layout.Ref, data map[uint64][]byte, position uint64, snapshot string) { + t.Helper() + ctx := context.Background() + if _, err := layout.RunBegin(ctx, s, cleanHolder, session); err != nil { + t.Fatal(err) + } + for idx, ref := range next { + if b, ok := data[idx]; ok { + if err := layout.EnsureObject(ctx, s, ref.Chunk.Path(), b, session); err != nil { + t.Fatal(err) + } + } + } + root, segs, err := layout.Build(next) + if err != nil { + t.Fatal(err) + } + for n, b := range segs { + if err := layout.EnsureObject(ctx, s, n.Path(), b, session); err != nil { + t.Fatal(err) + } + } + rn, rb, err := layout.NameRoot(root) + if err != nil { + t.Fatal(err) + } + if err := layout.EnsureObject(ctx, s, rn.Path(), rb, session); err != nil { + t.Fatal(err) + } + if _, err := layout.RunCommit(ctx, s, s, vol, cleanHolder, layout.CommitRequest{Session: session, Prev: prev, Next: next, Position: position, Snapshot: snapshot}); err != nil { + t.Fatal(err) + } +} + +// Release-blocking (cleaning end to end on the catalog): snapshot s1 of X, +// overwrite the chunk with Y, snapshot s2, delete s1, clean: X's chunk is +// gone, the pool shrinks by exactly it, and the current image and s2 still +// read Y. +func TestBCatalog_CleanAfterOverwriteAndSnapshotDelete(t *testing.T) { + ctx := context.Background() + c, err := NewBCatalog(NewMemFiler(), newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + v := newRef(t, "v1") + if _, err := c.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + s, err := c.Store(v) + if err != nil { + t.Fatal(err) + } + if _, err := layout.Start(ctx, s, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + x, y := bytes.Repeat([]byte{'X'}, 4096), bytes.Repeat([]byte{'Y'}, 4096) + cx, cy := layout.NameChunk(1, x), layout.NameChunk(1, y) + m1 := map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: cx}} + m2 := map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: cy}} + commitImage(t, s, v.Name, "w1", map[uint64]layout.Ref{}, m1, map[uint64][]byte{1: x}, 1, "s1") + commitImage(t, s, v.Name, "w2", m1, m2, map[uint64][]byte{1: y}, 2, "s2") + if err := c.f.CreateEntry(ctx, path.Join(c.base, v.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil { + t.Fatal(err) + } + // Control: while s1 still names X, the cleaning removes nothing. + if res, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil || res.Removed != 0 || !present(t, s, cx) { + t.Fatalf("clean with s1 held: %+v %v; want nothing removed", res, err) + } + if _, err := c.DeleteSnapshot(ctx, v, "s1"); err != nil { + t.Fatal(err) + } + before, err := c.listObjects(ctx, v) + if err != nil { + t.Fatal(err) + } + res, _, err := cleanVia(ctx, c, v, cleanHolder) + if err != nil || res.Removed != 1 { + t.Fatalf("clean: %+v %v; want exactly X's chunk removed", res, err) + } + after, err := c.listObjects(ctx, v) + if err != nil { + t.Fatal(err) + } + if len(after) != len(before)-1 || present(t, s, cx) || !present(t, s, cy) { + t.Fatalf("objects %d -> %d, X present %v, Y present %v; want one fewer, X gone, Y kept", len(before), len(after), present(t, s, cx), present(t, s, cy)) + } + h, _, err := c.ReadHead(ctx, v) + if err != nil { + t.Fatal(err) + } + _, r, err := c.open(v) + if err != nil { + t.Fatal(err) + } + for name, rn := range map[string]layout.RootName{"current": *h.Current, "s2": h.Snapshots["s2"].Root} { + img, err := r.Open(ctx, rn) + if err != nil { + t.Fatal(err) + } + ch, err := img.Chunk(ctx, 1) + if err != nil || !bytes.Equal(ch.Data, y) { + t.Fatalf("%s reads chunk 1: %v (Y=%v); want Y intact", name, err, bytes.Equal(ch.Data, y)) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/concurrent_cas_integration_test.go b/seaweed-block/core/frontend/chunkstore/concurrent_cas_integration_test.go deleted file mode 100644 index 98ffff65c0..0000000000 --- a/seaweed-block/core/frontend/chunkstore/concurrent_cas_integration_test.go +++ /dev/null @@ -1,235 +0,0 @@ -//go:build chunkstore_integration - -package chunkstore - -import ( - "bytes" - "context" - "crypto/sha256" - "errors" - "fmt" - "io" - "os" - "strconv" - "sync" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -const concurrentCASWeedSHA256 = "5fafd54e10ee307a7fd7246ca6763d0069cefbef47f9a86ce722f304b162da7b" - -type casRPCResult struct { - index int - code codes.Code -} -type casRPCGate struct { - filerpb.SeaweedFilerClient - index int - arrived chan<- int - release <-chan struct{} - responses chan<- casRPCResult - expected storage.ChunkHeadVersion -} - -// This gate does not implement CAS: every operation delegates to a real filer -// RPC. It holds updates AFTER all client pre-reads so a client-side refusal -// cannot masquerade as evidence of the server's conditional-write contract. -func (c *casRPCGate) UpdateEntry(ctx context.Context, in *filerpb.UpdateEntryRequest, opts ...grpc.CallOption) (*filerpb.UpdateEntryResponse, error) { - if in.Entry.GetName() != headName || string(in.ExpectedExtended[extGen]) != strconv.FormatUint(c.expected.Gen, 10) || string(in.ExpectedExtended[extEpoch]) != strconv.FormatUint(c.expected.Epoch, 10) { - return nil, fmt.Errorf("unexpected HEAD CAS precondition: gen=%q epoch=%q", in.ExpectedExtended[extGen], in.ExpectedExtended[extEpoch]) - } - select { - case c.arrived <- c.index: - case <-ctx.Done(): - return nil, ctx.Err() - } - select { - case <-c.release: - case <-ctx.Done(): - return nil, ctx.Err() - } - resp, err := c.SeaweedFilerClient.UpdateEntry(ctx, in, opts...) - c.responses <- casRPCResult{c.index, status.Code(err)} - return resp, err -} - -func requireConcurrentCASWeed(t *testing.T) { - t.Helper() - binary := os.Getenv("CHUNKSTORE_WEED") - if binary == "" { - t.Skip("CHUNKSTORE_WEED not set") - } - f, err := os.Open(binary) - if err != nil { - t.Fatal(err) - } - defer f.Close() - h := sha256.New() - if _, err := io.Copy(h, f); err != nil { - t.Fatal(err) - } - if got := fmt.Sprintf("%x", h.Sum(nil)); got != concurrentCASWeedSHA256 { - t.Fatalf("weed must be pinned mono 8b582399d build: SHA256=%s want %s", got, concurrentCASWeedSHA256) - } - t.Logf("real filer binary SHA256=%s (mono 8b582399d)", concurrentCASWeedSHA256) -} - -func TestIntegration_ConcurrentHEADCASRealFiler(t *testing.T) { - requireConcurrentCASWeed(t) - cluster := startWeed(t) - const root = "/swblock/chunks/concurrent-cas" - reader := cluster.remote(t, root) - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) - defer cancel() - initial := storage.ChunkHead{Epoch: 1, Holder: "initial", RemoteLSN: 1, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{}} - if gen, err := reader.CASHead(ctx, storage.ChunkHeadVersion{}, initial); err != nil || gen != 1 { - t.Fatalf("seed: gen=%d err=%v", gen, err) - } - // Multiple expected values exercise generation advancement, not just create. - for round := 0; round < 4; round++ { - t.Run(fmt.Sprintf("generation-%d", round+1), func(t *testing.T) { - current, err := reader.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - expected := storage.ChunkHeadVersion{Gen: current.Gen, Epoch: current.Epoch} - const n = 16 - roundCtx, roundCancel := context.WithTimeout(ctx, 30*time.Second) - arrived := make(chan int, n) - release := make(chan struct{}) - responses := make(chan casRPCResult, n) - var once sync.Once - var wg sync.WaitGroup - joined := make(chan struct{}) - type result struct { - index int - gen uint64 - err error - } - results := make(chan result, n) - proposals := make([]storage.ChunkHead, n) - // Construct clients on the test goroutine: each has its own real connection. - remotes := make([]*ChunkRemote, n) - for i := 0; i < n; i++ { - client := cluster.client(t, root) - client.fc = &casRPCGate{SeaweedFilerClient: client.fc, index: i, arrived: arrived, release: release, responses: responses, expected: expected} - remotes[i], err = NewSWFSChunkRemote(client, root) - if err != nil { - t.Fatal(err) - } - proposals[i] = storage.ChunkHead{Epoch: current.Epoch, Holder: fmt.Sprintf("writer-%d-%d", round, i), RemoteLSN: current.RemoteLSN + uint64(i) + 1, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{}} - } - defer func() { - roundCancel() - once.Do(func() { close(release) }) - select { - case <-joined: - case <-time.After(5 * time.Second): - t.Error("CAS callers did not join after cancellation") - } - }() - for i := 0; i < n; i++ { - wg.Add(1) - go func(i int) { - defer wg.Done() - gen, err := remotes[i].CASHead(roundCtx, expected, proposals[i]) - results <- result{i, gen, err} - }(i) - } - go func() { wg.Wait(); close(joined) }() - seen := map[int]bool{} - for i := 0; i < n; i++ { - select { - case id := <-arrived: - if seen[id] { - t.Fatalf("duplicate RPC admission %d", id) - } - seen[id] = true - case <-roundCtx.Done(): - t.Fatalf("only %d/%d reached actual UpdateEntry after pre-read: %v", len(seen), n, roundCtx.Err()) - } - } - once.Do(func() { close(release) }) - winners := []int{} - losers := 0 - for i := 0; i < n; i++ { - select { - case r := <-results: - if r.err == nil { - if r.gen != expected.Gen+1 { - t.Fatalf("winner gen=%d want %d", r.gen, expected.Gen+1) - } - winners = append(winners, r.index) - } else if errors.Is(r.err, storage.ErrChunkHeadPrecondition) { - losers++ - } else { - t.Fatalf("caller %d has non-conflict failure: %v", r.index, r.err) - } - case <-roundCtx.Done(): - t.Fatal("CAS results timed out", roundCtx.Err()) - } - } - if len(winners) != 1 || losers != n-1 { - t.Fatalf("same expected %+v: winners=%v typed conflicts=%d; want 1 and %d", expected, winners, losers, n-1) - } - rpcOK, rpcConflict := 0, 0 - rpcSeen := map[int]bool{} - for i := 0; i < n; i++ { - select { - case r := <-responses: - if rpcSeen[r.index] { - t.Fatalf("duplicate RPC response %d", r.index) - } - rpcSeen[r.index] = true - switch r.code { - case codes.OK: - rpcOK++ - if r.index != winners[0] { - t.Fatalf("RPC winner %d != caller winner %d", r.index, winners[0]) - } - case codes.FailedPrecondition: - rpcConflict++ - default: - t.Fatalf("unexpected real RPC status %s", r.code) - } - case <-roundCtx.Done(): - t.Fatal("missing real RPC result", roundCtx.Err()) - } - } - if rpcOK != 1 || rpcConflict != n-1 { - t.Fatalf("real RPC OK=%d FailedPrecondition=%d", rpcOK, rpcConflict) - } - winner := proposals[winners[0]] - winner.Gen = expected.Gen + 1 - wantEntry, err := headEntry(winner) - if err != nil { - t.Fatal(err) - } - // An independent client verifies exact winner bytes, not just generation. - fresh := cluster.client(t, root) - gotEntry, err := fresh.LookupEntry(roundCtx, root, headName) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(gotEntry.Content, wantEntry.Content) { - t.Fatalf("final HEAD does not equal winner %d", winners[0]) - } - for _, key := range []string{extGen, extEpoch, extHolder} { - if !bytes.Equal(gotEntry.Extended[key], wantEntry.Extended[key]) { - t.Fatalf("winner xattr %s mismatch", key) - } - } - got, err := reader.GetHead(roundCtx) - if err != nil || got.Gen != winner.Gen || got.Epoch != winner.Epoch || got.Holder != winner.Holder || got.RemoteLSN != winner.RemoteLSN { - t.Fatalf("decoded final HEAD=%+v err=%v want winner %+v", got, err, winner) - } - t.Logf("expected gen=%d epoch=%d: %d actual RPCs, winner=%d gen=%d, %d typed server/caller conflicts, final HEAD exact", expected.Gen, expected.Epoch, n, winners[0], winner.Gen, losers) - }) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/control_types.go b/seaweed-block/core/frontend/chunkstore/control_types.go new file mode 100644 index 0000000000..f76f0e8e22 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/control_types.go @@ -0,0 +1,150 @@ +package chunkstore + +// Control response types and error codes are shared by the layout catalog, +// the status HTTP routes and the operator CLI. +import ( + "errors" + "fmt" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// DefaultOpDeadline bounds a snapshot or fork from reading its source to +// its final write (spec §2.3). +const DefaultOpDeadline = 5 * time.Minute + +// ErrNotAdmitted marks a delete admission error that is a definite refusal +// (nothing was recorded). Any other admission error leaves the outcome +// unknown. +var ErrNotAdmitted = errors.New("chunkstore: volume delete not admitted") + +const ( + // SnapActive and SnapDeleting are a snapshot's states. + SnapActive = "active" + SnapDeleting = "deleting" + // SnapAbsent is DeleteSnapshot's answer for a snapshot that is not there. + SnapAbsent = "absent" + + // DefaultScheduleKeep is the count kept when the newest scheduled + // snapshot carries no valid retain.LabelScheduleKeep (the label, on a + // scheduled snapshot, is how many its schedule keeps). + DefaultScheduleKeep = 7 + + CodeInvalidClass = "invalid_class" + CodeInvalidPolicy = "invalid_policy" +) + +// Error codes of the control plane (spec §2.2), as the HTTP API and the CLI +// report them. +const ( + CodeNotChunkVolume = "not_chunk_volume" + CodeInvalidName = "invalid_name" + CodeSnapshotExists = "snapshot_exists" + CodeSnapshotNotFound = "snapshot_not_found" + CodeSnapshotDeleting = "snapshot_deleting" + CodeTargetExists = "target_exists" + CodeGeometryMismatch = "geometry_mismatch" + CodeDeadlineExceeded = "deadline_exceeded" + CodeRemoteUnavailable = "remote_unavailable" + CodeOutcomeUnknown = "outcome_unknown" + CodeInvalidLabel = "invalid_label" +) + +// CatalogError is a typed control-plane failure. +type CatalogError struct { + Code string + Message string + Retryable bool + Err error +} + +func (e *CatalogError) Error() string { + if e.Err != nil { + return fmt.Sprintf("chunkstore: %s: %s: %v", e.Code, e.Message, e.Err) + } + return fmt.Sprintf("chunkstore: %s: %s", e.Code, e.Message) +} + +func (e *CatalogError) Unwrap() error { return e.Err } + +// Detail is the error without its code: the message, and the cause if any +// (an error body carries the code in its own field). +func (e *CatalogError) Detail() string { + if e.Err != nil { + return fmt.Sprintf("%s: %v", e.Message, e.Err) + } + return e.Message +} + +// CodeOf returns the control-plane code of err, or "" when it has none. +func CodeOf(err error) string { + var ce *CatalogError + if errors.As(err, &ce) { + return ce.Code + } + return "" +} + +func catErr(code string, retryable bool, err error, format string, a ...any) error { + return &CatalogError{Code: code, Message: fmt.Sprintf(format, a...), Retryable: retryable, Err: err} +} + +// remoteErr wraps a filer failure as remote_unavailable, keeping the cause. +func remoteErr(err error, format string, a ...any) error { + return catErr(CodeRemoteUnavailable, true, err, format, a...) +} + +// Parent is a forked volume's source. +type Parent struct { + VolumeID string `json:"volume_id"` + Snapshot string `json:"snapshot"` + Gen uint64 `json:"gen"` +} + +// SnapshotInfo describes one snapshot, with the field names of the HTTP API +// (spec §3.2-§3.3). +type SnapshotInfo struct { + Root string `json:"root,omitempty"` + Dependents []layout.Dependent `json:"dependents,omitempty"` + VolumeID string `json:"volumeID"` + Name string `json:"name"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + CutLSN uint64 `json:"cutLSN"` + CreatedNs int64 `json:"createdNs"` + State string `json:"state"` + ChunkCount int `json:"chunkCount"` + ManifestBytes int `json:"manifestBytes"` + Consistency string `json:"consistency"` + Labels map[string]string `json:"labels"` + Parent *Parent `json:"parent"` + ExpiresAtNs int64 `json:"expiresAtNs"` + Replayed bool `json:"replayed"` + Class string `json:"class"` + + attempt string // the attempt the name resolved to, when read by name + + head storage.ChunkHead +} + +// Head returns the HEAD the snapshot copied. +func (s SnapshotInfo) Head() storage.ChunkHead { return s.head } + +type ListOptions struct { + Prefix string + StartAfter string + Limit int + IncludeDeleting bool +} + +// ValidateSnapshotClass refuses a class other than "", "semantic", +// "pinned" and "scheduled" (invalid_class). +func ValidateSnapshotClass(class string) error { + switch class { + case "", layout.ClassSemantic, layout.ClassPinned, layout.ClassScheduled: + return nil + } + return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q, %q or %q", class, layout.ClassSemantic, layout.ClassPinned, layout.ClassScheduled) +} diff --git a/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go b/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go deleted file mode 100644 index ea28bc0c35..0000000000 --- a/seaweed-block/core/frontend/chunkstore/decode_fuzz_test.go +++ /dev/null @@ -1,146 +0,0 @@ -package chunkstore - -import ( - "crypto/sha256" - "encoding/json" - "reflect" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Fuzz targets for the persisted chunkstore documents: the manifest JSON -// reader (duplicate keys, nesting, trailing bytes) and the HEAD document. -// Under `go test` (no -fuzz) they run their seeds. - -func fuzzHeadSeeds(tb testing.TB) [][]byte { - tb.Helper() - sum := sha256.Sum256([]byte("chunk")) - heads := []storage.ChunkHead{ - {Gen: 1, Epoch: 2, Holder: "r1", RemoteLSN: 7, Chunks: map[uint64]storage.ChunkRef{0: {Key: "k0", SHA256: sum}, 5: {Key: "@v2/k5", SHA256: sum}}}, - {Gen: 3, Epoch: 4, Holder: "r2", RemoteLSN: 9, State: storage.ChunkHeadDetached, - DetachedBy: &storage.ChunkDetachedBy{Holder: "r2", Epoch: 4, Gen: 3}, Chunks: map[uint64]storage.ChunkRef{}}, - {Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 3, ChunkBytes: 4 << 20, ManifestChunkCount: 2, - Segments: map[uint64]storage.ChunkSegment{0: {Key: "@v1/seg/00", SHA256: sum, Owner: "v1", Count: 2, SegFormat: 2, MaxBirthLSN: 3}}}, - } - var out [][]byte - for _, h := range heads { - if h.Segments == nil && len(h.Chunks) > 0 { - out = append(out, legacyHeadFixture(tb, h).Content) - continue - } - e, err := headEntry(h) - if err != nil { - tb.Fatalf("seed %+v: %v", h, err) - } - out = append(out, e.Content) - } - return append(out, - []byte(`{"format":1,"gen":1,"epoch":1,"holder":"a","remote_lsn":0,"gen":2}`), // duplicate key - []byte(`{"format":1,"gen":1}{"x":1}`), // trailing value - []byte(`{"format":2,"gen":1,"segments":{"0":{"Key":"","Owner":"v","Count":1}},"chunk_bytes":4096,"chunk_count":1}`), - []byte(`[[[[[[[[[[1]]]]]]]]]]`), // nesting - []byte(``), - ) -} - -// FuzzDecodeManifestJSON: never panics; when it accepts a document, the -// value equals what encoding/json alone decodes from the same bytes. -func FuzzDecodeManifestJSON(f *testing.F) { - for _, s := range fuzzHeadSeeds(f) { - f.Add(s) - } - f.Fuzz(func(t *testing.T, body []byte) { - var got any - if err := decodeManifestJSON(body, &got); err != nil { - return - } - var want any - if err := json.Unmarshal(body, &want); err != nil { - t.Fatalf("accepted a document encoding/json rejects: %v", err) - } - if !reflect.DeepEqual(got, want) { - t.Fatalf("decoded %v, encoding/json decodes %v", got, want) - } - }) -} - -// canonicalHead normalises the empty-collection forms the codec does not -// distinguish (an absent and an empty chunk map). -func canonicalHead(h storage.ChunkHead) storage.ChunkHead { - if len(h.Chunks) == 0 { - h.Chunks = nil - } - return h -} - -// FuzzDecodeHeadDocument: never panics; a rejected document yields the zero -// head (no partial value); an accepted one re-encodes (headEntry) and -// decodes back to the same head, including through decodeHead with the -// entry's extended attributes. -func FuzzDecodeHeadDocument(f *testing.F) { - for _, s := range fuzzHeadSeeds(f) { - f.Add(s) - } - f.Fuzz(func(t *testing.T, body []byte) { - h, err := DecodeHeadDocument("fuzz", body) - if err != nil { - if gap := knownHeadDecodeGap(h, err); gap != "" { - return // pinned below - } - if !reflect.DeepEqual(h, storage.ChunkHead{}) { - t.Fatalf("error %v with a partial head %+v", err, h) - } - return - } - e, err := headEntry(h) - if h.Segments == nil && len(h.Chunks) > 0 { - if err == nil { - t.Fatal("read-only legacy data was writable as flat HEAD") - } - return - } - if err != nil { - if gap := knownHeadEncodeGap(h); gap != "" { - return - } - t.Fatalf("an accepted head does not re-encode: %v (%+v)", err, h) - } - again, err := decodeHead("fuzz", e) - if err != nil { - t.Fatalf("re-encoded head does not decode: %v", err) - } - if !reflect.DeepEqual(canonicalHead(again), canonicalHead(h)) { - t.Fatalf("head round trip: %+v, want %+v", again, h) - } - }) -} - -// knownHeadDecodeGap names the rejections that return a partial head: -// decodeHeadDoc returns the half-built segmented head when validateRoot -// fails (chunk_remote.go, "return h, err"). Found by FuzzDecodeHeadDocument; -// reported, not changed here: no caller reads the head on that error. -func knownHeadDecodeGap(h storage.ChunkHead, err error) string { - if err != nil && h.Segments != nil { - return "segmented head returned with a validateRoot error" - } - return "" -} - -// knownHeadEncodeGap names accepted heads headEntry refuses (none known). -func knownHeadEncodeGap(storage.ChunkHead) string { return "" } - -// Pins the known partial-value gap that knownHeadDecodeGap exempts: a -// segmented root whose segment reference is invalid is rejected, but the -// half-built head comes back with the error. If this starts failing, the -// gap is closed: drop knownHeadDecodeGap. -func TestDecodeHeadDocumentReturnsAPartialHeadOnAnInvalidRoot(t *testing.T) { - body := []byte(`{"format":2,"gen":1,"segments":{"0":{"Key":"","Owner":"v","Count":1}},"chunk_bytes":4096,"chunk_count":1}`) - h, err := DecodeHeadDocument("fuzz", body) - if err == nil { - t.Fatal("an invalid segment reference was accepted") - } - if h.Gen != 1 || h.Segments == nil { - t.Fatalf("expected the known partial head with the error, got %+v", h) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/delete_sites_test.go b/seaweed-block/core/frontend/chunkstore/delete_sites_test.go index cae327fd80..bab1b22e59 100644 --- a/seaweed-block/core/frontend/chunkstore/delete_sites_test.go +++ b/seaweed-block/core/frontend/chunkstore/delete_sites_test.go @@ -19,12 +19,14 @@ import ( // master's volume record, never from a name given plus an id read from // that same directory. A new site fails until it is classified here. var deleteSites = map[string]string{ - "core/frontend/chunkstore/catalog.go Catalog.dropIntent -> DeleteEntry": "an intent entry (old store)", - "core/frontend/chunkstore/catalog.go Catalog.DeleteSnapshot -> DeleteEntry": "a snapshot name entry, conditional on its attempt (old store)", - "core/frontend/chunkstore/chunk_remote.go ChunkRemote.DeleteIntent -> DeleteEntry": "an intent entry (old store)", - "core/frontend/chunkstore/retention.go Catalog.freeName -> DeleteEntry": "a snapshot name entry, conditional on its attempt (old store)", + "cmd/blockvolume/main.go parseFlags -> VolumeDir": "validated master layout id and volume name; TestBlockvolumeLayoutIdentitySelectsTheLocalRoot", + "core/launcher/k8s_renderer.go durableRoot -> VolumeDir": "persisted workload plan layout id and name; launcher layout identity controls", + "core/frontend/chunkstore/swfs.go SWFS.DeleteEntry -> DeleteEntry": "the filer client itself", - "core/frontend/chunkstore/layout/read.go Image.Chunk -> VolumeDir": "a foreign chunk's directory from the reference's owner name and id", + "cmd/sw-block/chunk_b.go chunkSnapshots -> VolumeDir": "prints a dependent's directory from HEAD's dependent record (its name and id); nothing is read or written there", + "core/frontend/chunkstore/catalog_b.go VolumeRef.Dir -> VolumeDir": "a VolumeRef is the master's record (name, layout id) or a reference's owner name and id (foreignOwners)", + "core/frontend/chunkstore/layout_store.go LayoutStore.deleteObject -> DeleteEntry": "only canonical pool, segment or root files under the configured volume root; HEAD, VOLUME and directory paths refused (TestLayoutStoreDeleteNeverRemovesControlRecords)", + "core/frontend/chunkstore/layout/read.go Reader.ReadRef -> VolumeDir": "a foreign chunk's directory from the reference's owner name and id", } func TestDeleteAndDirectorySites_Enumeration(t *testing.T) { diff --git a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go index fefdaee1fb..d97b8f6085 100644 --- a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go +++ b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go @@ -13,7 +13,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.6 -// protoc v3.12.4 +// protoc v7.34.1 // source: filer_subset.proto package filerpb @@ -421,11 +421,13 @@ func (x *Entry) GetContent() []byte { return nil } -// Only file_id is modelled: chunkstore never writes chunks, and reads them -// only to refuse a HEAD entry that carries any. +// A layout object is one ordinary filer file backed by one complete needle. +// These field numbers match SeaweedFS's FileChunk. type FileChunk struct { state protoimpl.MessageState `protogen:"open.v1"` FileId string `protobuf:"bytes,1,opt,name=file_id,json=fileId,proto3" json:"file_id,omitempty"` + Offset int64 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` + Size uint64 `protobuf:"varint,3,opt,name=size,proto3" json:"size,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -467,6 +469,20 @@ func (x *FileChunk) GetFileId() string { return "" } +func (x *FileChunk) GetOffset() int64 { + if x != nil { + return x.Offset + } + return 0 +} + +func (x *FileChunk) GetSize() uint64 { + if x != nil { + return x.Size + } + return 0 +} + type FuseAttributes struct { state protoimpl.MessageState `protogen:"open.v1"` FileSize uint64 `protobuf:"varint,1,opt,name=file_size,json=fileSize,proto3" json:"file_size,omitempty"` @@ -1489,9 +1505,11 @@ const file_filer_subset_proto_rawDesc = "" + "\acontent\x18\t \x01(\fR\acontent\x1a;\n" + "\rExtendedEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"$\n" + + "\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"P\n" + "\tFileChunk\x12\x17\n" + - "\afile_id\x18\x01 \x01(\tR\x06fileId\"\xb0\x01\n" + + "\afile_id\x18\x01 \x01(\tR\x06fileId\x12\x16\n" + + "\x06offset\x18\x02 \x01(\x03R\x06offset\x12\x12\n" + + "\x04size\x18\x03 \x01(\x04R\x04size\"\xb0\x01\n" + "\x0eFuseAttributes\x12\x1b\n" + "\tfile_size\x18\x01 \x01(\x04R\bfileSize\x12\x14\n" + "\x05mtime\x18\x02 \x01(\x03R\x05mtime\x12\x1b\n" + diff --git a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto index e0fab4e1ef..601343588e 100644 --- a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto +++ b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto @@ -59,10 +59,12 @@ message Entry { bytes content = 9; // if not empty, the file content } -// Only file_id is modelled: chunkstore never writes chunks, and reads them -// only to refuse a HEAD entry that carries any. +// A layout object is one ordinary filer file backed by one complete needle. +// These field numbers match SeaweedFS's FileChunk. message FileChunk { string file_id = 1; + int64 offset = 2; + uint64 size = 3; } message FuseAttributes { diff --git a/seaweed-block/core/frontend/chunkstore/flat_head_test.go b/seaweed-block/core/frontend/chunkstore/flat_head_test.go deleted file mode 100644 index b83d032c70..0000000000 --- a/seaweed-block/core/frontend/chunkstore/flat_head_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "path" - "testing" -) - -func TestForkGrandchildReadsEveryBlockWithoutAncestorImages(t *testing.T) { - f, b, c, source := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "seed", RequestID: "seed"}, source); err != nil { - t.Fatal(err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "seed", Target: "v2", RequestID: "parent"}); err != nil { - t.Fatal(err) - } - parent, err := NewChunkRemote(f, b, catBase+"/v2") - if err != nil { - t.Fatal(err) - } - ph, err := parent.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "template", RequestID: "template"}, ph); err != nil { - t.Fatal(err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v2", Snapshot: "template", Target: "v3", RequestID: "grandchild"}); err != nil { - t.Fatal(err) - } - // Remove only ancestor image metadata, preserving immutable object bindings. - for vol, name := range map[string]string{"v1": "seed", "v2": "template"} { - attempt := snapPath(t, f, vol, name) - for _, entry := range []string{attempt, path.Join(catBase, vol, snapNamesDir, name), path.Join(catBase, vol, headName)} { - if err := f.DeleteEntry(ctx, path.Dir(entry), path.Base(entry), nil); err != nil { - t.Fatal(err) - } - if _, err := f.LookupEntry(ctx, path.Dir(entry), path.Base(entry)); err == nil { - t.Fatalf("ancestor image metadata remains: %s", entry) - } - } - } - // Open a fresh reader: no cached parent HEAD or snapshot can supply data. - grandchild, err := NewChunkRemote(f, b, catBase+"/v3") - if err != nil { - t.Fatal(err) - } - h, err := grandchild.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if len(h.Chunks) != 2 { - t.Fatalf("grandchild lost its complete image: %d chunks", len(h.Chunks)) - } - for block := uint64(0); block < uint64(catGeo.NumBlocks); block++ { - got := make([]byte, catGeo.BlockSize) - if ref, ok := h.Chunks[block/uint64(catGeo.ChunkBlocks)]; ok { - data, err := grandchild.Get(ctx, ref.Key) - if err != nil { - t.Fatalf("block %d: %v", block, err) - } - off := (block % uint64(catGeo.ChunkBlocks)) * uint64(catGeo.BlockSize) - copy(got, data[off:off+uint64(catGeo.BlockSize)]) - } - var fill byte - switch block / uint64(catGeo.ChunkBlocks) { - case 0: - fill = 0x10 - case 3: - fill = 0x13 - } - if !bytes.Equal(got, bytes.Repeat([]byte{fill}, int(catGeo.BlockSize))) { - t.Fatalf("block %d differs after ancestor images were removed", block) - } - } -} diff --git a/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go b/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go deleted file mode 100644 index 237f018820..0000000000 --- a/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package chunkstore - -import ( - "context" - "path" - "strings" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" -) - -// A legacy catalog may already contain oversized geometry. A new fork is -// still a new volume: it must not bypass the creation cap by inheritance. -func TestForkRejectsLegacyOversizedGeometry(t *testing.T) { - for _, blocks := range []uint64{4294967295, 4294967296} { - f, b, c, _, _ := gcFixture(t) - ctx := context.Background() - v, ok, err := c.ReadVolume(ctx, "v1") - if err != nil || !ok { - t.Fatal(err) - } - v.NumBlocks = blocks - e, err := volumeEntry(v, "") - if err != nil { - t.Fatal(err) - } - if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { - t.Fatal(err) - } - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)}) - _, err = c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h) - if err != nil { - t.Fatal(err) - } - if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "fork", IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - _, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "fork", RequestID: "f"}) - if blocks == 4294967295 { - if err != nil { - t.Fatalf("at-cap fork: %v", err) - } - got, ok, e := c.ReadVolume(ctx, "fork") - if e != nil || !ok || got.NumBlocks != blocks { - t.Fatalf("at-cap geometry not inherited: %+v %v", got, e) - } - continue - } - if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { - t.Fatalf("oversized fork must refuse: %v", err) - } - if _, ok, e := c.ReadVolume(ctx, "fork"); e != nil || ok { - t.Fatalf("oversized fork persisted target: %v %v", ok, e) - } - // Observe claim cleanup through the public retention operation: an - // uncompleted fork claim would make this snapshot undeletable. - if _, deleteErr := c.DeleteSnapshot(ctx, "v1", "s1"); deleteErr != nil { - t.Fatalf("capacity refusal blocked snapshot deletion: %v", deleteErr) - } - } -} diff --git a/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go deleted file mode 100644 index ee4a1779e2..0000000000 --- a/seaweed-block/core/frontend/chunkstore/format_legacy_upgrade_test.go +++ /dev/null @@ -1,222 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "encoding/json" - "os" - "path" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Frozen output of the pre-format-3 CreateSnapshot/Fork producers at 3401cc60. -func preF4ForkFixture(t *testing.T, segmented bool) (*fakeFiler, *Catalog, *ChunkRemote) { - t.Helper() - suffix := "false" - if segmented { - suffix = "true" - } - data, err := os.ReadFile("testdata/pre_f4_fork_" + suffix + ".json") - if err != nil { - t.Fatal(err) - } - var frozen struct { - Entries map[string]*filerpb.Entry - Objects map[string][]byte - } - if err := json.Unmarshal(data, &frozen); err != nil { - t.Fatal(err) - } - f, b := newFakeFiler(), newFakeBlobs() - f.entries = frozen.Entries - c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) - if err != nil { - t.Fatal(err) - } - c.now = func() time.Time { return time.Unix(1000, 0) } - r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err != nil { - t.Fatal(err) - } - if err := r.Put(context.Background(), "legacy-data", bytes.Repeat([]byte{0x41}, 8*4096)); err != nil { - t.Fatal(err) - } - for key, body := range frozen.Objects { - if err := r.Put(context.Background(), key, body); err != nil { - t.Fatal(err) - } - } - return f, c, r -} -func assertLegacyImage(t *testing.T, r *ChunkRemote) { - t.Helper() - h, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - if h.RemoteLSN != 7 || len(h.Chunks) != 1 { - t.Fatalf("legacy image/frontier lost: %+v", h) - } - data, err := r.Get(context.Background(), h.Chunks[0].Key) - if err != nil || !bytes.Equal(data, bytes.Repeat([]byte{0x41}, 8*4096)) { - t.Fatalf("legacy bytes changed: %v", err) - } -} -func TestFormatUpgradeLegacyIncompleteFork(t *testing.T) { - for _, segmented := range []bool{false, true} { - name := "flat" - if segmented { - name = "segmented" - } - t.Run(name, func(t *testing.T) { - f, c, r := preF4ForkFixture(t, segmented) - _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}) - if err != nil { - t.Fatalf("old incomplete fork retry: %v", err) - } - dst, err := NewChunkRemote(f, r.b, path.Join(catBase, "v2")) - if err != nil { - t.Fatal(err) - } - assertLegacyImage(t, dst) - e, err := f.LookupEntry(context.Background(), path.Join(catBase, "v2"), headName) - if err != nil { - t.Fatal(err) - } - var doc struct{ Format int } - if json.Unmarshal(e.Content, &doc) != nil || doc.Format != 3 { - t.Fatal("fork data must be format3") - } - }) - } -} -func TestFormatUpgradeLegacyForkIdentityStillRefusesChangedImage(t *testing.T) { - for _, segmented := range []bool{false, true} { - t.Run(map[bool]string{false: "flat", true: "segmented"}[segmented], func(t *testing.T) { - f, c, _ := preF4ForkFixture(t, segmented) - p := snapPath(t, f, "v1", "s1") - var s snapDoc - if err := json.Unmarshal(f.entries[p].Content, &s); err != nil { - t.Fatal(err) - } - var h map[string]any - if err := json.Unmarshal(s.Head, &h); err != nil { - t.Fatal(err) - } - // Preserve generation/frontier: only immutable content identity changes. - if segmented { - ref := h["segments"].(map[string]any)["0"].(map[string]any) - sum := ref["sha256"].([]any) - sum[0] = float64((int(sum[0].(float64)) + 1) % 256) - } else { - ref := h["chunks"].(map[string]any)["0"].(map[string]any) - ref["sha256"] = strings.Repeat("0", 64) - } - s.Head, _ = json.Marshal(h) - f.entries[p].Content, _ = json.Marshal(s) - if _, err := c.Fork(context.Background(), ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "old-fork"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("changed image admitted or identity not reached: %v", err) - } - }) - } -} -func TestFormatUpgradeLegacySnapshotAndDelete(t *testing.T) { - t.Run("snapshot", func(t *testing.T) { - f, c, r := preF4ForkFixture(t, false) - h, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "upgraded", RequestID: "new-snapshot"}, h); err != nil { - t.Fatalf("legacy snapshot: %v", err) - } - e := f.entries[snapPath(t, f, "v1", "upgraded")] - var s snapDoc - if err := json.Unmarshal(e.Content, &s); err != nil { - t.Fatal(err) - } - var doc struct{ Format int } - json.Unmarshal(s.Head, &doc) - if doc.Format != 3 { - t.Fatal("snapshot contains flat data") - } - assertLegacyImage(t, r) - }) - t.Run("delete", func(t *testing.T) { - f, c, r := preF4ForkFixture(t, false) - for p := range f.entries { - if p != path.Join(catBase, "v1", headName) && p != path.Join(catBase, "v1", volumeName) && !bytes.Contains([]byte(p), []byte("/keys/")) { - delete(f.entries, p) - } - } - h, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - h.Holder = "" - h.Epoch = 0 - f.entries[path.Join(catBase, "v1", headName)] = legacyHeadFixture(t, h) - c.retainHook = func(stage, _ string) { - if stage == hookHeadMarked { - assertLegacyImage(t, r) - e := f.entries[path.Join(catBase, "v1", headName)] - var d struct{ Format int } - json.Unmarshal(e.Content, &d) - if d.Format != 3 { - t.Fatal("delete mark contains flat data") - } - } - } - res, err := c.DeleteVolume(context.Background(), "v1", nil) - if err != nil || !res.Completed { - t.Fatalf("legacy delete: %+v %v", res, err) - } - }) -} - -type legacyUpgradeView struct{} - -func (legacyUpgradeView) Projection() frontend.Projection { - return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, Healthy: true} -} -func TestFormatUpgradeLegacyProviderTakeover(t *testing.T) { - f, _, r := preF4ForkFixture(t, false) - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-new/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, legacyUpgradeView{}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { p.Close() }) - s, err := p.EnsureStorage("v1") - if err != nil { - t.Fatal(err) - } - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if _, err := p.RecoverVolume(ctx, "v1"); err != nil { - t.Fatalf("legacy provider takeover: %v", err) - } - h, err := r.GetHead(ctx) - if err != nil || h.Holder != "node-new/r1" || h.Epoch != 2 { - t.Fatalf("takeover not installed: %+v %v", h, err) - } - e := f.entries[path.Join(catBase, "v1", headName)] - var d struct{ Format int } - json.Unmarshal(e.Content, &d) - if d.Format != 3 { - t.Fatal("takeover wrote flat data") - } - for i := uint32(0); i < 8; i++ { - got, err := s.Read(i) - if err != nil || !bytes.Equal(got, bytes.Repeat([]byte{0x41}, 4096)) { - t.Fatalf("takeover bytes %d: %v", i, err) - } - } - assertLegacyImage(t, r) -} diff --git a/seaweed-block/core/frontend/chunkstore/format_refusal_test.go b/seaweed-block/core/frontend/chunkstore/format_refusal_test.go deleted file mode 100644 index 1fc6471d0a..0000000000 --- a/seaweed-block/core/frontend/chunkstore/format_refusal_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package chunkstore - -import ( - "context" - "crypto/sha256" - "encoding/json" - "path" - "testing" -) - -func TestManifestFormatUpgradeRejectsUnsupportedOrInconsistentObjects(t *testing.T) { - type mutation func(map[string]any) - for _, tc := range []struct { - name string - segment bool - change mutation - }{ - {"levels", false, func(v map[string]any) { v["levels"] = 2 }}, - {"missing-levels", false, func(v map[string]any) { delete(v, "levels") }}, - {"head-version", false, func(v map[string]any) { v["format"] = 4 }}, - {"head-unknown", false, func(v map[string]any) { v["future"] = true }}, - {"segment-version-ref", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["seg_format"] = 3 }}, - {"root-max", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["max_birth_lsn"] = 41 }}, - {"root-max-future", false, func(v map[string]any) { v["segments"].(map[string]any)["0"].(map[string]any)["max_birth_lsn"] = 43 }}, - {"segment-version", true, func(v map[string]any) { v["format"] = 3 }}, - {"segment-unknown", true, func(v map[string]any) { v["future"] = true }}, - {"segment-max", true, func(v map[string]any) { v["max_birth_lsn"] = 41 }}, - {"segment-max-missing", true, func(v map[string]any) { delete(v, "max_birth_lsn") }}, - {"computed-max", true, func(v map[string]any) { - for _, entry := range v["chunks"].(map[string]any) { - entry.(map[string]any)["birth_lsn"] = 41 - } - }}, - {"encoding", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["enc"] = "zstd" }}, - {"birth-future", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["birth_lsn"] = 43 }}, - {"birth-missing", true, func(v map[string]any) { delete(v["chunks"].(map[string]any)["0"].(map[string]any), "birth_lsn") }}, - {"hash-shape", true, func(v map[string]any) { v["chunks"].(map[string]any)["0"].(map[string]any)["sha256"] = "bad" }}, - } { - t.Run(tc.name, func(t *testing.T) { - f, b, _, _, _ := gcFixture(t) - r, h := publishSegmented(t, f, b) - ctx := context.Background() - e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) - if err != nil { - t.Fatal(err) - } - var root map[string]any - if err := json.Unmarshal(e.Content, &root); err != nil { - t.Fatal(err) - } - if tc.segment { - body, err := r.Get(ctx, h.Segments[0].Key) - if err != nil { - t.Fatal(err) - } - var object map[string]any - if err := json.Unmarshal(body, &object); err != nil { - t.Fatal(err) - } - tc.change(object) - body, err = json.Marshal(object) - if err != nil { - t.Fatal(err) - } - if err := r.Put(ctx, "malformed-segment", body); err != nil { - t.Fatal(err) - } - ref := root["segments"].(map[string]any)["0"].(map[string]any) - ref["key"] = qualifyManifestKey("v1", "malformed-segment") - ref["sha256"] = sha256.Sum256(body) - } else { - tc.change(root) - } - e.Content, err = json.Marshal(root) - if err != nil { - t.Fatal(err) - } - if err := f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { - t.Fatal(err) - } - if _, err := r.GetHead(ctx); err == nil { - t.Fatal("invalid persisted schema accepted") - } - }) - } -} - -func TestManifestFormatUpgradeReadsLegacyRootGoldens(t *testing.T) { - for _, body := range []string{ - `{"format":1,"gen":1,"epoch":1,"holder":"old","remote_lsn":7,"chunks":{"0":{"key":"old","sha256":"0000000000000000000000000000000000000000000000000000000000000000"}}}`, - `{"format":2,"gen":1,"epoch":1,"holder":"old","remote_lsn":7,"chunk_bytes":4096,"chunk_count":1,"segments":{"0":{"key":"@v1/old","sha256":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"owner":"v1","count":1}}}`, - } { - h, err := DecodeHeadDocument("legacy", []byte(body)) - if err != nil { - t.Fatal(err) - } - if h.Segments == nil { - if h.Chunks[0].Encoding != "full" || h.Chunks[0].BirthLSN != 7 { - t.Fatal("legacy flat frontier not inherited") - } - } else if h.Segments[0].SegFormat != 1 || h.Segments[0].MaxBirthLSN != 7 { - t.Fatal("legacy segment maximum not inherited") - } - } -} diff --git a/seaweed-block/core/frontend/chunkstore/format_reuse_test.go b/seaweed-block/core/frontend/chunkstore/format_reuse_test.go deleted file mode 100644 index 7b738b075d..0000000000 --- a/seaweed-block/core/frontend/chunkstore/format_reuse_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package chunkstore - -import ( - "context" - "crypto/sha256" - "encoding/json" - "fmt" - "path" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func legacySegmentedFixture(t *testing.T) (*ChunkRemote, *fakeBlobs, storage.ChunkHead) { - t.Helper() - f, b, _, _, _ := gcFixture(t) - r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err != nil { - t.Fatal(err) - } - ctx := context.Background() - doc := segmentedHeadDoc{headIdentityDoc: headIdentityDoc{Format: 2, Gen: 1, Epoch: 1, Holder: "old", RemoteLSN: 42}, Segments: map[uint64]legacySegmentRefDoc{}, ChunkBytes: 4096, ChunkCount: 2} - for group := uint64(0); group < 2; group++ { - key := fmt.Sprintf("legacy-data-%d", group) - data := []byte{byte(0x41 + group)} - if err := r.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - idx := group * (manifestSegmentBytes / 4096) - segment := legacySegmentDoc{Format: 1, Range: group, ChunkBytes: 4096, Owner: "v1", Chunks: map[uint64]legacyChunkRefDoc{idx: {Key: qualifyManifestKey("v1", key), SHA256: sha256.Sum256(data)}}} - body, err := json.Marshal(segment) - if err != nil { - t.Fatal(err) - } - segmentKey := fmt.Sprintf("legacy-segment-%d", group) - if err := r.Put(ctx, segmentKey, body); err != nil { - t.Fatal(err) - } - doc.Segments[group] = legacySegmentRefDoc{Key: qualifyManifestKey("v1", segmentKey), SHA256: sha256.Sum256(body), Owner: "v1", Count: 1} - } - e := legacyHeadFixture(t, storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "old", RemoteLSN: 42}) - e.Content, err = json.Marshal(doc) - if err != nil { - t.Fatal(err) - } - if err := f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { - t.Fatal(err) - } - h, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - return r, b.fakeBlobs, h -} - -func TestManifestFormatUpgradeReusesColdSegmentsWithoutUploads(t *testing.T) { - r, b, base := legacySegmentedFixture(t) - ctx := context.Background() - before, _, _ := b.counts() - unchanged, ids, err := r.PrepareManifest(ctx, base, base, base.ChunkBytes) - if err != nil { - t.Fatal(err) - } - after, _, _ := b.counts() - if before != after || len(ids) != 0 || unchanged.Segments[0] != base.Segments[0] || unchanged.Segments[1] != base.Segments[1] { - t.Fatal("zero changed groups uploaded a segment or intent") - } - next := base - next.RemoteLSN = 43 - next.Chunks = map[uint64]storage.ChunkRef{} - for idx, ref := range base.Chunks { - next.Chunks[idx] = ref - } - data := []byte{0x53} - if err := r.Put(ctx, "changed-data", data); err != nil { - t.Fatal(err) - } - idx := manifestSegmentBytes / base.ChunkBytes - next.Chunks[idx] = storage.ChunkRef{Key: qualifyManifestKey("v1", "changed-data"), SHA256: sha256.Sum256(data), Encoding: "full", BirthLSN: 43} - before, _, _ = b.counts() - updated, ids, err := r.PrepareManifest(ctx, base, next, base.ChunkBytes) - if err != nil { - t.Fatal(err) - } - after, _, _ = b.counts() - if after-before != 1 || len(ids) != 1 || updated.Segments[0] != base.Segments[0] || updated.Segments[1].SegFormat != 2 || updated.Segments[1].MaxBirthLSN != 43 { - t.Fatal("one changed group rewrote cold segments or lost the new format") - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, updated); err != nil { - t.Fatal(err) - } - for _, id := range ids { - if err := r.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - h, err := r.GetHead(ctx) - if err != nil || h.Segments[0].SegFormat != 1 || h.Chunks[0].BirthLSN != 42 || h.Chunks[idx].BirthLSN != 43 { - t.Fatalf("mixed legacy/new image did not resolve: %+v %v", h, err) - } - got, err := r.Get(ctx, h.Chunks[idx].Key) - if err != nil || len(got) != 1 || got[0] != 0x53 { - t.Fatal("mixed root changed bytes") - } -} - -func TestManifestFormatUpgradeAllowsInheritedZeroBirth(t *testing.T) { - f, b, _, _, _ := gcFixture(t) - r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err != nil { - t.Fatal(err) - } - ctx := context.Background() - base, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - data := []byte{0x57} - if err := r.Put(ctx, "zero-birth", data); err != nil { - t.Fatal(err) - } - next := storage.ChunkHead{Epoch: 1, Holder: "base", Chunks: map[uint64]storage.ChunkRef{0: {Key: "zero-birth", SHA256: sha256.Sum256(data), Encoding: "full", BirthLSN: 0}}} - next, ids, err := r.PrepareManifest(ctx, base, next, 4096) - if err != nil { - t.Fatal(err) - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, next); err != nil { - t.Fatal(err) - } - for _, id := range ids { - if err := r.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - h, err := r.GetHead(ctx) - if err != nil || h.Chunks[0].BirthLSN != 0 || h.Segments[0].MaxBirthLSN != 0 { - t.Fatalf("fresh base zero birth refused: %+v %v", h, err) - } -} - -func TestManifestFormatUpgradeSnapshotAndForkPreserveMetadata(t *testing.T) { - f, b, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "format3", RequestID: "format3"}, h); err != nil { - t.Fatal(err) - } - snapshotPath := snapPath(t, f, "v1", "format3") - e, err := f.LookupEntry(ctx, path.Dir(snapshotPath), path.Base(snapshotPath)) - if err != nil { - t.Fatal(err) - } - var snapshot struct { - Head struct { - Format int `json:"format"` - Levels int `json:"levels"` - } `json:"head"` - } - if err := json.Unmarshal(e.Content, &snapshot); err != nil || snapshot.Head.Format != 3 || snapshot.Head.Levels != 1 { - t.Fatalf("data snapshot embedded flat HEAD: %s %v", e.Content, err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "format3", Target: "v2", RequestID: "format3-fork"}); err != nil { - t.Fatal(err) - } - r, err := NewChunkRemote(f, b, path.Join(catBase, "v2")) - if err != nil { - t.Fatal(err) - } - fork, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if fork.RemoteLSN != h.RemoteLSN || len(fork.Chunks) != len(h.Chunks) { - t.Fatal("fork lost inherited frontier or chunk count") - } - for idx, ref := range h.Chunks { - if fork.Chunks[idx] != ref { - t.Fatal("fork changed owner, encoding, birth or stored-byte hash") - } - } - for group, ref := range h.Segments { - if fork.Segments[group] != ref { - t.Fatal("fork changed segment version or maximum") - } - } -} diff --git a/seaweed-block/core/frontend/chunkstore/format_sustained_test.go b/seaweed-block/core/frontend/chunkstore/format_sustained_test.go deleted file mode 100644 index 3d514e261b..0000000000 --- a/seaweed-block/core/frontend/chunkstore/format_sustained_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "encoding/json" - "path" - "path/filepath" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func TestManifestFormatUpgradeSustainedWritesPastWALWithPeriodicFlush(t *testing.T) { - const blocks, blockSize, chunkBlocks = 1024, 4096, 64 - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) - defer cancel() - f, b := newFakeFiler(), newFakeBlobs() - r, err := NewChunkRemote(f, b, path.Join(catBase, "sustained")) - if err != nil { - t.Fatal(err) - } - s, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "source"), blocks, blockSize, storage.WALStoreOptions{ChunkBlocks: chunkBlocks, WMode: storage.WModeStrict}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { s.Close() }) - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: 1, Holder: "source", FreshFromHead: true, BarrierBound: 2, UploadConcurrency: 2}) - if err != nil { - t.Fatal(err) - } - walBytes := s.WALCapacityBytes() - if walBytes == 0 || walBytes > 128<<20 { - t.Fatalf("smoke WAL capacity outside bounded fixture: %d", walBytes) - } - batchBytes := uint64(blocks * blockSize) - rounds := int(walBytes/batchBytes) + 1 - var payload, last uint64 - var finalByte byte - for round := 0; round < rounds; round++ { - finalByte = byte(round%251 + 1) - data := bytes.Repeat([]byte{finalByte}, blocks*blockSize) - batch := make([][]byte, blocks) - for i := range batch { - batch[i] = data[i*blockSize : (i+1)*blockSize] - } - if _, err := s.WriteBatch(0, batch); err != nil { - t.Fatal(err) - } - last, err = s.Sync() - if err != nil { - t.Fatal(err) - } - payload += batchBytes - // Use the production periodic flusher, not a second checkpoint path. - for s.CheckpointLSN() < last { - select { - case <-ctx.Done(): - t.Fatalf("periodic Flush did not cover batch %d: %v", round, ctx.Err()) - case <-time.After(10 * time.Millisecond): - } - } - if (round+1)%4 == 0 || round+1 == rounds { - if _, err := l.Cut(ctx); err != nil { - t.Fatal(err) - } - } - } - if payload <= walBytes || s.FlushCount() == 0 { - t.Fatal("sustained fixture did not exceed WAL with periodic Flush") - } - h, err := r.GetHead(ctx) - if err != nil || h.RemoteLSN != last { - t.Fatalf("final frontier: %+v %v", h, err) - } - e, err := f.LookupEntry(ctx, path.Join(catBase, "sustained"), headName) - if err != nil { - t.Fatal(err) - } - var shape struct { - Format int `json:"format"` - Levels int `json:"levels"` - } - if err := json.Unmarshal(e.Content, &shape); err != nil || shape.Format != 3 || shape.Levels != 1 { - t.Fatal("sustained cut did not publish format3") - } - fresh, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "fresh"), blocks, blockSize, storage.WALStoreOptions{ChunkBlocks: chunkBlocks, WMode: storage.WModeStrict}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { fresh.Close() }) - if _, err := fresh.Recover(); err != nil { - t.Fatal(err) - } - if err := fresh.SeedChunkFrontier(last); err != nil { - t.Fatal(err) - } - if _, err := storage.AttachChunkLayer(fresh, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: 2, Holder: "fresh", FreshFromHead: true}); err != nil { - t.Fatal(err) - } - want := bytes.Repeat([]byte{finalByte}, blockSize) - for lba := uint32(0); lba < blocks; lba++ { - got, err := fresh.Read(lba) - if err != nil || !bytes.Equal(got, want) { - t.Fatalf("fresh read block%d: %v", lba, err) - } - } - t.Logf("payload=%d > WAL=%d, checkpoint drains=%d, FlushCount=%d; full fresh lazy read exact", payload, walBytes, rounds, s.FlushCount()) -} diff --git a/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go b/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go deleted file mode 100644 index f758d1f4d0..0000000000 --- a/seaweed-block/core/frontend/chunkstore/format_upgrade_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/json" - "path" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func TestManifestFormatUpgradeFlatWriterNeverStoresData(t *testing.T) { - dataHead := storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: {Key: "k"}}} - if _, err := headEntry(dataHead); err == nil { - t.Fatal("flat writer accepted chunk-bearing HEAD without a manifest") - } - f, b, _, _, _ := gcFixture(t) - r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err != nil { - t.Fatal(err) - } - cur, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - if _, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, dataHead); err == nil { - t.Fatal("direct CAS accepted geometry-free data") - } - after, err := r.GetHead(context.Background()) - if err != nil || after.Gen != cur.Gen { - t.Fatal("refused flat CAS changed HEAD") - } - empty, err := headEntry(storage.ChunkHead{Gen: 1, State: storage.ChunkHeadActive}) - if err != nil { - t.Fatal(err) - } - var shape struct { - Format int `json:"format"` - } - if err := json.Unmarshal(empty.Content, &shape); err != nil || shape.Format != 1 { - t.Fatal("empty flat root must remain writable") - } -} - -func TestManifestFormatUpgradeWritesVersionedStoredByteReferences(t *testing.T) { - f, b, _, _, _ := gcFixture(t) - r, h := publishSegmented(t, f, b) - ctx := context.Background() - entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) - if err != nil { - t.Fatal(err) - } - var root struct { - Format int `json:"format"` - Levels int `json:"levels"` - Segments map[string]struct { - Format int `json:"seg_format"` - Max uint64 `json:"max_birth_lsn"` - } `json:"segments"` - } - if err := json.Unmarshal(entry.Content, &root); err != nil { - t.Fatal(err) - } - if root.Format != 3 || root.Levels != 1 || root.Segments["0"].Format != 2 || root.Segments["0"].Max != h.RemoteLSN { - t.Fatalf("missing format3/levels/segment2 metadata: %s", entry.Content) - } - body, err := r.Get(ctx, h.Segments[0].Key) - if err != nil { - t.Fatal(err) - } - var segment struct { - Format int `json:"format"` - Max uint64 `json:"max_birth_lsn"` - Chunks map[string]struct { - Encoding string `json:"enc"` - Birth uint64 `json:"birth_lsn"` - Hash string `json:"sha256"` - } `json:"chunks"` - } - if err := json.Unmarshal(body, &segment); err != nil { - t.Fatal(err) - } - if segment.Format != 2 || segment.Max != h.RemoteLSN || len(segment.Chunks) != 2 { - t.Fatalf("missing segment format/max: %s", body) - } - for _, ref := range segment.Chunks { - if ref.Encoding != "full" || ref.Birth != h.RemoteLSN || len(ref.Hash) != 64 { - t.Fatalf("invalid inherited chunk reference: %+v", ref) - } - } - resolved, err := r.GetHead(ctx) - if err != nil || len(resolved.Chunks) != 2 { - t.Fatalf("format3 roundtrip: %+v %v", resolved, err) - } -} - -func TestManifestFormatUpgradeRefusesUnknownSegmentField(t *testing.T) { - f, b, _, _, _ := gcFixture(t) - r, h := publishSegmented(t, f, b) - ctx := context.Background() - if _, err := r.GetHead(ctx); err != nil { - t.Fatalf("valid legacy segment refused: %v", err) - } - ref := h.Segments[0] - body, err := r.Get(ctx, ref.Key) - if err != nil { - t.Fatal(err) - } - // Keep the object hash valid: the refusal must come from the segment schema. - body = append(bytes.TrimSuffix(body, []byte("}")), []byte(",\"future_encoding\":\"unsupported\"}")...) - if err := r.Put(ctx, "format-upgrade-unknown-field", body); err != nil { - t.Fatal(err) - } - ref.Key = qualifyManifestKey(ref.Owner, "format-upgrade-unknown-field") - ref.SHA256 = sha256.Sum256(body) - h.Segments[0] = ref - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, h); err != nil { - t.Fatal(err) - } - if _, err := r.GetHead(ctx); err == nil { - t.Fatal("published segment with unknown field accepted") - } -} diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go deleted file mode 100644 index 2416e85f58..0000000000 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ /dev/null @@ -1,485 +0,0 @@ -package chunkstore - -import ( - "context" - "crypto/sha256" - "errors" - "fmt" - "net/url" - "path" - "sort" - "strings" - "sync" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" - "google.golang.org/protobuf/proto" -) - -const extGCDeleted = "swb.gc.deleted" - -// ErrBlobDeleteRejected identifies a definite per-object refusal (HTTP400). -// It never proves the needle absent; GC retains its tombstone and reports it. -var ErrBlobDeleteRejected = errors.New("chunkstore: blob DELETE rejected") - -// DefaultGCClockSkew is the allowed pairwise difference between timestamp -// writers and collectors. Deployments with a larger bound must raise ClockSkew; -// no finite time-based grace can be safe with unbounded clock differences. -const DefaultGCClockSkew = time.Minute - -// BlobDeleter deletes one immutable needle. Missing needles are success. -// Implementations must not reuse a deleted fid. -type BlobDeleter interface { - DeleteBlob(context.Context, string) error -} - -// GCConfig binds a collector to the authoritative blockmaster epoch reader. -// IssuedEpoch must read the highest epoch issued for this volume, never a -// lease expiry or a cached guess. Unknown authority retains the intent. -type GCConfig struct { - Grace, IntentTTL time.Duration - // ClockSkew bounds pairwise wall-clock differences. Zero uses the default. - // Binding creation timestamps additionally lose up to one second of precision. - ClockSkew time.Duration - // CASApplyBound is the margin for a publish applied after its fork's - // deadline check. Zero uses the catalog operation deadline. A publish - // known to have succeeded was applied before its context ended, and that - // context ends at readAt + deadline, so it is inside the deadline; an - // unknown outcome keeps the fork intent, which roots the keys until the - // target is resolved, with no time bound. This bound covers apply delay - // and clock-rate drift beyond those two. NewCollector requires - // Grace >= operation deadline + ClockSkew + CASApplyBound, so a snapshot - // deleted while a fork of it is in flight stays rooted until the fork can - // no longer publish (INV-SNAP-DELETE-ANY-ORDER-001). - CASApplyBound time.Duration - IssuedEpoch func(context.Context, string) (uint64, error) - Now func() time.Time -} - -type GCRoot struct { - Kind string `json:"kind"` - Volume string `json:"volume"` - ID string `json:"id"` - Keys []string `json:"keys"` - Epoch uint64 `json:"epoch,omitempty"` - Holder string `json:"holder,omitempty"` -} -type GCObject struct { - Volume string `json:"volume"` - Key string `json:"key"` - FID string `json:"fid"` -} -type GCDeleteFailure struct { - GCObject - Error string `json:"error"` -} - -type GCResult struct { - FailedDeletes []GCDeleteFailure `json:"failed_deletes"` - Roots []GCRoot `json:"roots"` - WouldDelete []GCObject `json:"would_delete"` - WouldExpireIntents []string `json:"would_expire_intents"` - Volumes, Intents, ExpiredIntents, Candidates, Reclaimed int - // Pre-binding needles cannot be enumerated by this API. They are retained; - // UnknownUnbound is true rather than inventing a report-only count. - UnknownUnbound bool -} - -type gcCandidate struct { - since time.Time - digest [32]byte -} -type gcBinding struct { - volume string - entry *filerpb.Entry - digest [32]byte -} -type gcIntent struct { - remote *ChunkRemote - intent storage.ChunkIntent -} - -// Collector traces all catalog roots. Calls are serialized per collector; -// restarting loses candidates, which adds delay rather than authorizing a -// deletion. No WAL, publication or shard lock is held during remote I/O. -// Different collectors may duplicate idempotent blob deletes but cannot -// shorten either collector's independent two-mark grace requirement. -type Collector struct { - scope string // empty traces and reclaims the entire namespace - cat *Catalog - blobs BlobDeleter - cfg GCConfig - mu sync.Mutex - candidates map[string]gcCandidate - last time.Time -} - -func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, error) { - if cat == nil || blobs == nil || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil { - return nil, errors.New("chunkstore: GC requires catalog, blob deletion, positive intent TTL and epoch authority") - } - if cfg.ClockSkew == 0 { - cfg.ClockSkew = DefaultGCClockSkew - } - if cfg.ClockSkew < 0 || cfg.ClockSkew > time.Duration(1<<63-1)-time.Second { - return nil, errors.New("chunkstore: invalid GC clock skew bound") - } - if cfg.CASApplyBound == 0 { - cfg.CASApplyBound = cat.deadline() - } - const maxDur = time.Duration(1<<63 - 1) - d := cat.deadline() - if cfg.CASApplyBound < 0 || cfg.CASApplyBound > maxDur-d-cfg.ClockSkew { - return nil, errors.New("chunkstore: invalid GC CAS apply bound") - } - if need := d + cfg.ClockSkew + cfg.CASApplyBound; cfg.Grace < need { - return nil, fmt.Errorf("chunkstore: GC grace %v is below operation deadline %v + clock skew %v + CAS apply bound %v = %v", cfg.Grace, d, cfg.ClockSkew, cfg.CASApplyBound, need) - } - if cfg.Now == nil { - cfg.Now = time.Now - } - return &Collector{cat: cat, blobs: blobs, cfg: cfg, candidates: map[string]gcCandidate{}}, nil -} - -// Run completes a mark before any chunk deletion. Any failed mark discards -// previous candidates. Roots include active and deleting snapshots until -// the catalog has actually removed them; this collector never infers their -// absence from an age or a retention label. -func (g *Collector) Run(ctx context.Context) (GCResult, error) { return g.run(ctx, true) } - -// Preview performs the same mark and admission as Run, with no metadata, -// blob, intent or candidate-state mutations. -func (g *Collector) Preview(ctx context.Context) (GCResult, error) { return g.run(ctx, false) } - -func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err error) { - g.mu.Lock() - defer g.mu.Unlock() - result.UnknownUnbound = true - result.Roots = []GCRoot{} - result.WouldDelete = []GCObject{} - result.WouldExpireIntents = []string{} - result.FailedDeletes = []GCDeleteFailure{} - defer func() { - if err != nil && apply { - g.candidates = map[string]gcCandidate{} - } - }() - start := g.cfg.Now() - if !g.last.IsZero() && start.Before(g.last) { - // Discard coverage across a backward clock step; a fresh complete mark - // can still make progress without borrowing time from the future. - if apply { - g.candidates = map[string]gcCandidate{} - } - // Preview must also ignore the old coverage without mutating it. - // Candidate lookup below is guarded by this same condition. - } - roots := map[string]bool{} - var bindings []gcBinding - var expired []gcIntent - volumes, err := g.cat.ListVolumes(ctx) - if err != nil { - return result, err - } - result.Volumes = len(volumes) - for _, vol := range volumes { - r, e := NewChunkRemote(g.cat.f, gcBlobReader{g.blobs}, path.Join(g.cat.base, vol)) - if e != nil { - return result, e - } - h, e := r.GetHead(ctx) - if e != nil { - return result, e - } - addHead := func(kind, id string, head storage.ChunkHead) error { - var err error - head, err = r.resolveManifest(ctx, head) - if err != nil { - return err - } - for _, ref := range head.Segments { - dir, name, err := r.keyLocation(ref.Key) - if err != nil { - return err - } - roots[path.Join(dir, name)] = true - } - - keys := make([]string, 0, len(head.Chunks)+len(head.Segments)) - for _, ref := range head.Segments { - keys = append(keys, ref.Key) - } - for _, ref := range head.Chunks { - keys = append(keys, ref.Key) - } - sort.Strings(keys) - result.Roots = append(result.Roots, GCRoot{Kind: kind, Volume: vol, ID: id, Keys: keys, Epoch: head.Epoch, Holder: head.Holder}) - for _, ref := range head.Chunks { - dir, name, e := r.keyLocation(ref.Key) - if e != nil { - return e - } - roots[path.Join(dir, name)] = true - } - return nil - } - if e = addHead("HEAD", headName, h); e != nil { - return result, e - } - after := "" - for { - snaps, next, e := g.cat.ListSnapshots(ctx, vol, ListOptions{StartAfter: after, IncludeDeleting: true, Limit: maxListLimit}) - if e != nil { - return result, e - } - for _, snap := range snaps { - if e = addHead("snapshot", snap.Name, snap.Head()); e != nil { - return result, e - } - } - if next == "" { - break - } - if next <= after { - return result, errors.New("chunkstore: non-advancing snapshot listing") - } - after = next - } - attempts, e := g.snapshotAttemptHeads(ctx, vol, start) - if e != nil { - return result, e - } - for _, attempt := range attempts { - if e = addHead("snapshot_attempt", attempt.Name, attempt.Head); e != nil { - return result, e - } - } - intents, e := r.ListIntents(ctx) - if e != nil { - return result, e - } - for _, in := range intents { - result.Intents++ - if in.CreatedNs <= 0 { - return result, errors.New("chunkstore: invalid intent creation time") - } - expire := false - if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") && g.oldEnough(start, time.Unix(0, in.CreatedNs), g.cfg.IntentTTL, 0) { - issued, authorityErr := g.cfg.IssuedEpoch(ctx, vol) - // Catalog copy intents are retained: their exclusive creates - // are not epoch-fenced. For a capture, both the authority - // and the actual CAS domain must have - // advanced. Mere lease loss, or issuance without takeover, - // cannot authorize expiry of a paused publisher's intent. - expire = (g.scope == "" || g.scope == vol) && authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued - } - if expire { - expired = append(expired, gcIntent{r, in}) - result.WouldExpireIntents = append(result.WouldExpireIntents, path.Join(vol, in.ID)) - } else { - kind := "capture_intent" - if strings.HasPrefix(in.Holder, "snapshot:") || strings.HasPrefix(in.Holder, "fork:") { - kind = "retained_copy_intent" - } - if in.Segments != nil { - h := storage.ChunkHead{Segments: in.Segments, ChunkBytes: in.ChunkBytes} - // Intents protect keys without carrying a published frontier. - // Validate segment maxima against the reference maxima here. - for group, ref := range h.Segments { - if ref.SegFormat == 0 { - ref.SegFormat = 1 - h.Segments[group] = ref - } - h.RemoteLSN = max(h.RemoteLSN, ref.MaxBirthLSN) - } - for _, ref := range in.Segments { - h.ManifestChunkCount += ref.Count - } - if err := addHead(kind, in.ID, h); err != nil { - return result, err - } - } - result.Roots = append(result.Roots, GCRoot{Kind: kind, Volume: vol, ID: in.ID, Keys: append([]string{}, in.Keys...), Epoch: in.Epoch, Holder: in.Holder}) - for _, key := range in.Keys { - dir, name, e := r.keyLocation(key) - if e != nil { - return result, e - } - roots[path.Join(dir, name)] = true - } - } - } - // INV-MAINT-SCOPE: roots above remain catalog-wide; candidates are local. - if g.scope != "" && g.scope != vol { - continue - } - pageAfter := "" - for { - page, e := g.cat.f.ListEntries(ctx, r.keyDir(), "", pageAfter, listPage) - if e != nil { - return result, e - } - for _, entry := range page { - if entry.GetName() <= pageAfter || entry.GetIsDirectory() || len(entry.GetChunks()) != 0 || string(entry.Extended[extKind]) != kindChunkKey || len(entry.Extended[extFid]) == 0 || entry.Attributes == nil || entry.Attributes.Crtime <= 0 { - return result, fmt.Errorf("chunkstore: invalid GC binding %s/%s", r.keyDir(), entry.GetName()) - } - key, e := url.PathUnescape(entry.GetName()) - if e != nil { - return result, e - } - dir, name, e := r.keyLocation(key) - if e != nil || dir != r.keyDir() || name != entry.GetName() { - return result, errors.New("chunkstore: noncanonical GC binding") - } - raw, e := proto.MarshalOptions{Deterministic: true}.Marshal(entry) - if e != nil { - return result, e - } - bindings = append(bindings, gcBinding{vol, entry, sha256.Sum256(raw)}) - pageAfter = entry.GetName() - } - if len(page) < listPage { - break - } - } - } - if g.cfg.Now().Sub(start)+g.cat.deadline() >= g.cfg.Grace { - return result, errors.New("chunkstore: GC mark exceeded grace safety margin") - } - // An intent is retired only after the complete mark and confirmed fencing. - for _, x := range expired { - if !apply { - continue - } - if err = x.remote.DeleteIntent(ctx, x.intent.ID); err != nil { - return result, err - } - result.ExpiredIntents++ - } - nextCandidates := map[string]gcCandidate{} - for _, b := range bindings { - p := path.Join(g.cat.base, b.volume, keysDir, b.entry.Name) - if roots[p] { - if len(b.entry.Extended[extGCDeleted]) != 0 { - return result, fmt.Errorf("chunkstore: root references reclaimed binding %s", p) - } - continue - } - if string(b.entry.Extended[extGCDeleted]) == "done" { - continue - } - created := time.Unix(b.entry.Attributes.Crtime, 0) - if !g.oldEnough(start, created, g.cfg.Grace, time.Second) { - continue - } - candidate, seen := g.candidates[p] - if !g.last.IsZero() && start.Before(g.last) { - seen = false - } - if !seen || candidate.digest != b.digest { - candidate = gcCandidate{start, b.digest} - } - result.Candidates++ - if !g.oldEnough(start, candidate.since, g.cfg.Grace, 0) { - nextCandidates[p] = candidate - continue - } - result.WouldDelete = append(result.WouldDelete, GCObject{Volume: b.volume, Key: mustUnescapeGCKey(b.entry.Name), FID: string(b.entry.Extended[extFid])}) - if !apply { - continue - } - if err = ctx.Err(); err != nil { - return result, err - } - err = reclaimBinding(ctx, g.cat.f, g.blobs, path.Dir(p), b.entry) - if err != nil && ctx.Err() != nil { - err = ctx.Err() - } - if errors.Is(err, ErrBlobDeleteRejected) { - // INV-GC-DELETE-PROGRESS-001: a confirmed object rejection - // must not starve later candidates or invalidate a complete mark. - // Keep the fid/tombstone and retry; never record this object done. - result.FailedDeletes = append(result.FailedDeletes, GCDeleteFailure{ - GCObject: GCObject{Volume: b.volume, Key: mustUnescapeGCKey(b.entry.Name), FID: string(b.entry.Extended[extFid])}, Error: err.Error(), - }) - nextCandidates[p] = candidate - continue - } - if err != nil { - return result, err - } - result.Reclaimed++ - } - if apply { - g.candidates = nextCandidates - g.last = start - } - return result, nil -} - -// nilBlobs is used only for read-only metadata traversal, never chunk I/O. -type nilBlobs struct{} - -func (nilBlobs) Put(context.Context, []byte) (string, error) { - return "", errors.New("chunkstore: metadata-only remote") -} -func (nilBlobs) Get(context.Context, string) ([]byte, error) { - return nil, errors.New("chunkstore: metadata-only remote") -} - -// The binding name was already validated before reclamation admission. -func mustUnescapeGCKey(name string) string { k, _ := url.PathUnescape(name); return k } - -// GC needs immutable segment bytes as well as deletion. Flat-only legacy -// adapters remain usable; a segmented root without a reader refuses the mark. -type gcBlobReader struct{ BlobDeleter } - -func (b gcBlobReader) Put(context.Context, []byte) (string, error) { - return "", errors.New("chunkstore: GC is read-only during mark") -} -func (b gcBlobReader) Get(ctx context.Context, fid string) ([]byte, error) { - reader, ok := b.BlobDeleter.(interface { - Get(context.Context, string) ([]byte, error) - }) - if !ok { - return nil, errors.New("chunkstore: GC segment reader unavailable") - } - return reader.Get(ctx, fid) -} - -// reclaimBinding deletes the needle a key binding names, keeping the binding -// for ever: removing it would allow Put to rebind a key that once existed. -// The binding first gets a conditional swb.gc.deleted=1 tombstone (which -// also lets a failed physical delete be retried without losing the fid), -// then the exact fid is deleted, then the tombstone becomes done. A binding -// already done is left as it is. The caller decides that nothing references -// the key. -func reclaimBinding(ctx context.Context, f Filer, blobs BlobDeleter, dir string, entry *filerpb.Entry) error { - switch string(entry.Extended[extGCDeleted]) { - case "done": - return nil - case "1": - default: - e := proto.Clone(entry).(*filerpb.Entry) - e.Extended[extGCDeleted] = []byte("1") - expected := map[string][]byte{extKind: []byte(kindChunkKey), extFid: entry.Extended[extFid], extGCDeleted: nil} - if err := f.UpdateEntry(ctx, dir, e, expected); err != nil { - return err - } - } - if err := blobs.DeleteBlob(ctx, string(entry.Extended[extFid])); err != nil { - return err - } - e := proto.Clone(entry).(*filerpb.Entry) - e.Extended[extGCDeleted] = []byte("done") - return f.UpdateEntry(ctx, dir, e, map[string][]byte{extFid: entry.Extended[extFid], extGCDeleted: []byte("1")}) -} - -// INV-GC-CLOCK-SKEW-001: expiry uses a lower bound on elapsed time, -// never the raw difference of timestamps from different hosts. Subtracting -// separately avoids overflowing grace + skew for large configured durations. -func (g *Collector) oldEnough(now, stamp time.Time, grace, resolution time.Duration) bool { - age := now.Sub(stamp) - return age > grace && age-grace > g.cfg.ClockSkew+resolution -} diff --git a/seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go b/seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go deleted file mode 100644 index 427d0596cc..0000000000 --- a/seaweed-block/core/frontend/chunkstore/gc_clock_skew_test.go +++ /dev/null @@ -1,308 +0,0 @@ -package chunkstore - -import ( - "context" - "encoding/json" - "github.com/seaweedfs/seaweed-block/core/storage" - "path" - "strings" - "testing" - "time" -) - -// Exercise the default one-minute pairwise budget independently of the -// implementation constant. Wider clock differences require a larger config. -const testedGCSkew = time.Minute - -func TestGCSkewSnapshotDeleteGraceBothDirections(t *testing.T) { - for _, offset := range []time.Duration{-testedGCSkew, testedGCSkew} { - t.Run(offset.String(), func(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - realDelete := *now - c.SetClock(func() time.Time { return realDelete.Add(offset) }) - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)}) - snapshotDir(t, f, "v1", "s1") - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); err != nil { - t.Fatal(err) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - if offset < 0 { - *now = realDelete.Add(g.cfg.Grace - testedGCSkew/2) - } else { - *now = realDelete - } - roots, err := g.snapshotAttemptHeads(ctx, "v1", *now) - if err != nil || len(roots) != 1 { - t.Fatalf("skew shortened delete grace or blocked mark: roots=%d err=%v", len(roots), err) - } - *now = realDelete.Add(g.cfg.Grace + 2*testedGCSkew + time.Nanosecond) - roots, err = g.snapshotAttemptHeads(ctx, "v1", *now) - if err != nil || len(roots) != 0 { - t.Fatalf("old deleting attempt did not release: roots=%d err=%v", len(roots), err) - } - }) - } -} -func TestGCSkewIntentExpiryUsesConservativeAge(t *testing.T) { - f, b, _, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - id, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "old"}) - if err != nil { - t.Fatal(err) - } - ins, _ := r.ListIntents(ctx) - created := time.Unix(0, ins[0].CreatedNs) - head, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); err != nil { - t.Fatal(err) - } - g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil } - *now = created.Add(g.cfg.IntentTTL + testedGCSkew/2) - result, err := g.Run(ctx) - if err != nil || result.ExpiredIntents != 0 { - t.Fatalf("intent expired inside skew allowance: %+v %v", result, err) - } - *now = created.Add(g.cfg.IntentTTL + testedGCSkew + time.Nanosecond) - result, err = g.Run(ctx) - if err != nil || result.ExpiredIntents != 1 { - t.Fatalf("eligible intent %s retained: %+v %v", id, result, err) - } -} -func TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress(t *testing.T) { - f, b, _, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - for _, key := range []string{"rooted", "orphan"} { - if err := r.Put(ctx, key, []byte(key)); err != nil { - t.Fatal(err) - } - } - id, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "live", Keys: []string{"rooted"}}) - if err != nil { - t.Fatal(err) - } - dir := path.Join(catBase, "v1", intentsDir) - entry, err := f.LookupEntry(ctx, dir, id) - if err != nil { - t.Fatal(err) - } - var doc intentDoc - if err = json.Unmarshal(entry.Content, &doc); err != nil { - t.Fatal(err) - } - doc.CreatedNs = now.Add(testedGCSkew / 2).UnixNano() - entry.Content, _ = json.Marshal(doc) - if err = f.UpdateEntry(ctx, dir, entry, nil); err != nil { - t.Fatal(err) - } - for i := 0; i < 2; i++ { - out, err := g.Run(ctx) - if err != nil { - t.Fatalf("future intent blocked unrelated progress: %v", err) - } - if i == 1 && out.Reclaimed != 1 { - t.Fatalf("unrelated orphan did not progress: %+v", out) - } - *now = now.Add(2 * time.Hour) - } - if _, err = r.Get(ctx, "rooted"); err != nil { - t.Fatal("future root lost", err) - } -} -func TestGCSkewPersistedCoverageAcrossHosts(t *testing.T) { - for _, future := range []bool{false, true} { - t.Run(map[bool]string{false: "fast-reader", true: "future-writer"}[future], func(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { - t.Fatal(err) - } - first := *now - if future { - *now = first.Add(testedGCSkew) - } - if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil { - t.Fatal(err) - } - if future { - *now = first - } else { - *now = first.Add(g.cfg.Grace + testedGCSkew/2) - } - out, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) - if err != nil || out.Reclaimed != 0 { - t.Fatalf("cross-host coverage shortened grace or blocked pass: %+v %v", out, err) - } - *now = now.Add(g.cfg.Grace + testedGCSkew + time.Nanosecond) - out, err = c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) - if err != nil || out.Reclaimed != 1 { - t.Fatalf("fresh safe coverage did not reclaim: %+v %v", out, err) - } - }) - } -} -func TestGCSkewBindingAgeIncludesSecondResolution(t *testing.T) { - f, b, _, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { - t.Fatal(err) - } - born := time.Unix(now.Unix(), 900000000) - *now = born.Add(g.cfg.Grace) - dir := path.Join(catBase, "v1", keysDir) - entry, err := f.LookupEntry(ctx, dir, "orphan") - if err != nil { - t.Fatal(err) - } - entry.Attributes.Crtime = born.Add(-testedGCSkew).Unix() - if err = f.UpdateEntry(ctx, dir, entry, nil); err != nil { - t.Fatal(err) - } - out, err := g.Run(ctx) - if err != nil || out.Candidates != 0 { - t.Fatalf("binding age lost skew/second resolution: %+v %v", out, err) - } -} - -func TestGCSkewConfigAndMarkCoverage(t *testing.T) { - for _, skew := range []time.Duration{0, 2 * time.Minute} { - t.Run(skew.String(), func(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { - t.Fatal(err) - } - cfg := g.cfg - cfg.ClockSkew = skew - if _, err := c.ExecuteVolumeGC(ctx, "v1", b, cfg, true); err != nil { - t.Fatal(err) - } - entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), gcMarkName) - if err != nil { - t.Fatal(err) - } - var mark savedGCMark - if err = json.Unmarshal(entry.Content, &mark); err != nil { - t.Fatal(err) - } - if mark.ClockSkewNs <= 0 { - t.Fatal("normalized clock policy absent from mark") - } - // A legacy mark, or one from another skew policy, cannot authorize deletion. - mark.ClockSkewNs = 0 - entry.Content, _ = json.Marshal(mark) - if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), entry, nil); err != nil { - t.Fatal(err) - } - *now = now.Add(2 * time.Hour) - out, err := c.ExecuteVolumeGC(ctx, "v1", b, cfg, true) - if err != nil || out.Reclaimed != 0 { - t.Fatalf("legacy coverage borrowed: %+v %v", out, err) - } - *now = now.Add(2 * time.Hour) - out, err = c.ExecuteVolumeGC(ctx, "v1", b, cfg, true) - if err != nil || out.Reclaimed != 1 { - t.Fatalf("matching normalized policy lost coverage: %+v %v", out, err) - } - }) - } - _, b, c, g, _ := gcFixture(t) - for _, bad := range []time.Duration{-1, time.Duration(1<<63 - 1)} { - cfg := g.cfg - cfg.ClockSkew = bad - if _, err := NewCollector(c, b, cfg); err == nil { - t.Fatalf("bad skew %s accepted", bad) - } - } -} - -func TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate(t *testing.T) { - f, b, _, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err := r.Put(ctx, "orphan", []byte("orphan")); err != nil { - t.Fatal(err) - } - if _, err := g.Run(ctx); err != nil { - t.Fatal(err) - } - first := g.last - *now = now.Add(-time.Second) - if out, err := g.Preview(ctx); err != nil || out.Reclaimed != 0 { - t.Fatalf("backward preview: %+v %v", out, err) - } - if !g.last.Equal(first) || len(g.candidates) != 1 { - t.Fatal("preview changed coverage") - } - if out, err := g.Run(ctx); err != nil || out.Reclaimed != 0 { - t.Fatalf("backward mark: %+v %v", out, err) - } - *now = now.Add(g.cfg.Grace + g.cfg.ClockSkew + time.Nanosecond) - if out, err := g.Run(ctx); err != nil || out.Reclaimed != 1 { - t.Fatalf("fresh coverage made no progress: %+v %v", out, err) - } -} - -func TestGCSkewFutureCopyDoesNotBlockOtherSettlement(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - c.SetClock(func() time.Time { return *now }) - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x55)}) - for _, name := range []string{"future", "expired"} { - snapshotDir(t, f, "v1", name) - holdFirst(f, path.Join(catBase, "v1", snapsDir, name)+"/") - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: name}, h); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("held copy: %v", err) - } - } - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - ins, err := r.ListIntents(ctx) - if err != nil || len(ins) != 2 { - t.Fatalf("intents: %+v %v", ins, err) - } - *now = now.Add(DefaultOpDeadline + time.Second) - futureID := "" - for _, in := range ins { - if !strings.Contains(in.Holder, "/future/") { - continue - } - futureID = in.ID - dir := path.Join(catBase, "v1", intentsDir) - e, err := f.LookupEntry(ctx, dir, in.ID) - if err != nil { - t.Fatal(err) - } - var d intentDoc - if err = json.Unmarshal(e.Content, &d); err != nil { - t.Fatal(err) - } - d.CreatedNs = now.Add(testedGCSkew / 2).UnixNano() - e.Content, _ = json.Marshal(d) - if err = f.UpdateEntry(ctx, dir, e, nil); err != nil { - t.Fatal(err) - } - } - if futureID == "" { - t.Fatal("future copy fixture not found") - } - if count, err := g.SweepCopies(ctx); err != nil || count != 1 { - t.Fatalf("unrelated settlement blocked: %d %v", count, err) - } - left, err := r.ListIntents(ctx) - if err != nil || len(left) != 1 || left[0].ID != futureID { - t.Fatalf("future protection lost: %+v %v", left, err) - } - if out, err := g.Run(ctx); err != nil || len(out.Roots) == 0 { - t.Fatalf("future copy not rooted: %+v %v", out, err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy.go b/seaweed-block/core/frontend/chunkstore/gc_copy.go deleted file mode 100644 index 9d5e515dc5..0000000000 --- a/seaweed-block/core/frontend/chunkstore/gc_copy.go +++ /dev/null @@ -1,191 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "fmt" - "path" - "strconv" - "strings" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// SweepCopies settles expired copy attempts using permanent publication -// target claims; a deadline only admits a claim, never releases protection. -// It shares the collector pass mutex but acquires no storage locks. -func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) { - g.mu.Lock() - defer g.mu.Unlock() - now := g.cfg.Now() - vols, err := g.cat.ListVolumes(ctx) - if err != nil { - return 0, err - } - type copyAttempt struct { - vol string - remote *ChunkRemote - in storage.ChunkIntent - } - var pending []copyAttempt - for _, vol := range vols { - if g.scope != "" && g.scope != vol { - continue - } - r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol)) - if e != nil { - return 0, e - } - intents, e := r.ListIntents(ctx) - if e != nil { - return 0, e - } - for _, in := range intents { - if !strings.HasPrefix(in.Holder, "snapshot:") && !strings.HasPrefix(in.Holder, "fork:") { - continue - } - if in.CreatedNs <= 0 { - return 0, errors.New("chunkstore: invalid copy intent creation time") - } - // A future creation stamp retains protection, without preventing - // unrelated copy attempts from settling. Deadline alone never - // releases roots: the permanent target claim below is still required. - if in.CreatedNs > now.UnixNano() || in.DeadlineNs <= 0 || now.UnixNano() <= in.DeadlineNs { - continue - } - pending = append(pending, copyAttempt{vol, r, in}) - } - } - for _, a := range pending { - if err = ctx.Err(); err != nil { - return settled, err - } - if strings.HasPrefix(a.in.Holder, "snapshot:") { - parts := strings.Split(strings.TrimPrefix(a.in.Holder, "snapshot:"), "/") - if len(parts) != 3 || parts[0] != a.vol || CheckSnapshotName(parts[1]) != nil || !storage.ValidChunkIntentID(parts[2]) { - return settled, fmt.Errorf("chunkstore: malformed snapshot intent %s", a.in.ID) - } - // Claim the final attempt, never the reusable name record. - if _, err = g.cat.AbortSnapshot(ctx, a.vol, parts[1], parts[2]); err != nil { - return settled, err - } - dir := path.Join(g.cat.base, a.vol, snapsDir, parts[1]) - e, readErr := g.cat.f.LookupEntry(ctx, dir, parts[2]) - if readErr != nil { - return settled, readErr - } - info, _, readErr := decodeSnap(path.Join(dir, parts[2]), e) - if readErr != nil { - return settled, readErr - } - if info.VolumeID != a.vol || info.Name != parts[1] || (info.State != SnapAborted && string(e.Extended[extAttempt]) != parts[2]) { - return settled, errors.New("chunkstore: copy claim identity mismatch") - } - } else { - parts := strings.SplitN(strings.TrimPrefix(a.in.Holder, "fork:"), "/", 2) - if len(parts) != 2 || parts[0] != a.vol || parts[1] == "" { - return settled, fmt.Errorf("chunkstore: malformed fork intent %s", a.in.ID) - } - v, ok, readErr := g.cat.ReadVolume(ctx, a.vol) - if readErr != nil { - return settled, readErr - } - if !ok || !isForked(v.Origin) || v.Fork == nil || v.Fork.RequestID != parts[1] { - return settled, errors.New("chunkstore: fork intent has no matching target VOLUME") - } - if _, err = g.cat.AbortFork(ctx, a.vol); err != nil { - return settled, err - } - h, ok, readErr := g.cat.ReadHead(ctx, a.vol) - if readErr != nil { - return settled, readErr - } - if !ok || h.Gen == 0 { - return settled, errors.New("chunkstore: fork claim did not settle the publishing HEAD") - } - } - // Both a valid published immutable entry and a valid permanent aborted - // entry settle this attempt. Unknown claim/read never drops its intent. - if err = a.remote.DeleteIntent(ctx, a.in.ID); err != nil { - return settled, err - } - settled++ - } - return settled, nil -} - -func (g *Collector) gcEntries(ctx context.Context, dir string) ([]*filerpb.Entry, error) { - var out []*filerpb.Entry - after := "" - for { - page, err := g.cat.f.ListEntries(ctx, dir, "", after, listPage) - if err != nil { - return nil, err - } - for _, e := range page { - if e.GetName() <= after || path.Base(e.GetName()) != e.GetName() { - return nil, errors.New("chunkstore: invalid/non-advancing GC directory listing") - } - after = e.Name - out = append(out, e) - } - if len(page) < listPage { - return out, nil - } - } -} - -// snapshotAttemptHeads includes unnamed attempts left behind by DeleteSnapshot. -// Attempt entries are permanent. A deleting attempt stops rooting its keys -// only after its deleting timestamp ages past grace; ordinary two marks -// still apply afterward. An aborted attempt roots no keys. -type gcSnapshotHead struct { - Head storage.ChunkHead - Name string -} - -func (g *Collector) snapshotAttemptHeads(ctx context.Context, vol string, now time.Time) ([]gcSnapshotHead, error) { - root := path.Join(g.cat.base, vol, snapsDir) - dirs, err := g.gcEntries(ctx, root) - if err != nil { - return nil, err - } - var heads []gcSnapshotHead - for _, dir := range dirs { - if !dir.GetIsDirectory() || CheckSnapshotName(dir.Name) != nil { - return nil, errors.New("chunkstore: invalid snapshot attempt directory") - } - entries, err := g.gcEntries(ctx, path.Join(root, dir.Name)) - if err != nil { - return nil, err - } - for _, e := range entries { - if !storage.ValidChunkIntentID(e.Name) { - return nil, errors.New("chunkstore: invalid snapshot attempt identity") - } - info, _, err := decodeSnap(path.Join(root, dir.Name, e.Name), e) - if err != nil { - return nil, err - } - if info.VolumeID != vol || info.Name != dir.Name || (info.State != SnapAborted && string(e.Extended[extAttempt]) != e.Name) { - return nil, errors.New("chunkstore: snapshot attempt names another volume/name") - } - if info.State == SnapAborted { - continue - } - if info.State == SnapDeleting { - ns, err := strconv.ParseInt(string(e.Extended[extSnapDeletedNs]), 10, 64) - if err != nil || ns <= 0 { - return nil, errors.New("chunkstore: invalid deleted snapshot timestamp") - } - if g.oldEnough(now, time.Unix(0, ns), g.cfg.Grace, 0) { - continue - } - } - heads = append(heads, gcSnapshotHead{info.Head(), path.Join(dir.Name, e.Name)}) - } - } - return heads, nil -} diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go b/seaweed-block/core/frontend/chunkstore/gc_copy_test.go deleted file mode 100644 index 16e1994efa..0000000000 --- a/seaweed-block/core/frontend/chunkstore/gc_copy_test.go +++ /dev/null @@ -1,197 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "errors" - "github.com/seaweedfs/seaweed-block/core/storage" - "path" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" -) - -func snapshotDir(t *testing.T, f *fakeFiler, vol, name string) { - t.Helper() - if e := f.CreateEntry(context.Background(), path.Join(catBase, vol, snapsDir), &filerpb.Entry{Name: name, IsDirectory: true}, true); e != nil { - t.Fatal(e) - } -} - -func TestGC_CopySweepClaimsSnapshotAttemptBeforeRelease(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - c.SetClock(func() time.Time { return *now }) - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x31)}) - snapshotDir(t, f, "v1", "s1") - holdFirst(f, path.Join(catBase, "v1", snapsDir, "s1")+"/") - if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "dead"}, h); CodeOf(e) != CodeOutcomeUnknown { - t.Fatalf("held snapshot: %v", e) - } - oldPath := snapPath(t, f, "v1", "s1") - if count, e := g.SweepCopies(ctx); e != nil || count != 0 { - t.Fatalf("early sweep: %d %v", count, e) - } - *now = now.Add(DefaultOpDeadline + time.Second) - if count, e := g.SweepCopies(ctx); e != nil || count != 1 { - t.Fatalf("dead copy intent not settled by tombstone claim: count=%d err=%v", count, e) - } - if ins := intentsOf(t, f, "v1"); len(ins) != 0 { - t.Fatalf("intent retained after target claimed: %+v", ins) - } - e, err := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)) - if err != nil || string(e.Extended[extSnapState]) != SnapAborted { - t.Fatalf("permanent claim missing: %v", err) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "new"}, h); err != nil { - t.Fatal(err) - } - if p := snapPath(t, f, "v1", "s1"); p == oldPath { - t.Fatal("reused permanent attempt path") - } - if applied := f.releaseDeferredCreates(); applied != 0 { - t.Fatalf("late old snapshot insert landed after name reuse: %d", applied) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "newfork", RequestID: "fork"}); err != nil { - t.Fatal(err) - } - // The new name resolves to its new published attempt, never old tombstone. - info, err := c.readSnap(ctx, "v1", "s1") - if err != nil || info.Head().Gen != h.Gen { - t.Fatalf("new snapshot: %+v %v", info, err) - } -} - -func TestGC_CopySweepClaimsForkHEADNotExistingVolume(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - c.SetClock(func() time.Time { return *now }) - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)}) - snapshotDir(t, f, "v1", "s1") - if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h); e != nil { - t.Fatal(e) - } - if e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil { - t.Fatal(e) - } - holdFirst(f, path.Join(catBase, "v2", headName)) - if _, e := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "dead"}); CodeOf(e) != CodeOutcomeUnknown { - t.Fatalf("held fork: %v", e) - } - if _, ok, e := c.ReadVolume(ctx, "v2"); e != nil || !ok { - t.Fatalf("fixture lacks existing VOLUME: %v", e) - } - if _, ok, e := c.ReadHead(ctx, "v2"); e != nil || ok { - t.Fatalf("held fork already published: %v %v", ok, e) - } - *now = now.Add(DefaultOpDeadline + time.Second) - count, e := g.SweepCopies(ctx) - if e != nil || count != 1 { - t.Fatalf("fork sweep: %d %v", count, e) - } - head, ok, e := c.ReadHead(ctx, "v2") - if e != nil || !ok || head.State != storage.ChunkHeadAborted { - t.Fatalf("final HEAD not claimed: %+v %v", head, e) - } - if n := f.releaseDeferredCreates(); n != 0 { - t.Fatalf("late fork HEAD published over claim: %d", n) - } - if _, e := c.EnsureVolume(ctx, "v2", catGeo); CodeOf(e) != CodeForkIncomplete { - t.Fatalf("aborted target attached: %v", e) - } - if _, e := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "new"}); CodeOf(e) != CodeTargetExists { - t.Fatalf("volume id reused: %v", e) - } -} - -type retainCopyIntent struct{ Filer } - -func (f retainCopyIntent) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { - if path.Base(dir) == intentsDir { - return errors.New("cleanup response unavailable") - } - return f.Filer.DeleteEntry(ctx, dir, name, expected) -} - -func TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - c.SetClock(func() time.Time { return *now }) - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x51)}) - snapshotDir(t, f, "v1", "s1") - c.f = retainCopyIntent{f} - if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "published"}, h); e != nil { - t.Fatal(e) - } - c.f = f - oldPath := snapPath(t, f, "v1", "s1") - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: h.RemoteLSN}); e != nil { - t.Fatal(e) - } - *now = now.Add(DefaultOpDeadline + time.Second) - if count, e := g.SweepCopies(ctx); e != nil || count != 1 { - t.Fatalf("published copy claim: %d %v", count, e) - } - e, err := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)) - if err != nil || string(e.Extended[extSnapState]) != SnapActive { - t.Fatalf("published snapshot was overwritten: %v", err) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - // The name is gone, but its immutable attempt remains a root throughout grace. - if list, _, e := c.ListSnapshots(ctx, "v1", ListOptions{IncludeDeleting: true}); e != nil || len(list) != 0 { - t.Fatalf("name still listed: %+v %v", list, e) - } - for i := 0; i < 2; i++ { - if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { - t.Fatalf("unnamed deleting attempt lost grace: %+v %v", result, e) - } - *now = now.Add(time.Minute) - } - for _, ref := range h.Chunks { - if got, e := r.Get(ctx, ref.Key); e != nil || !bytes.Equal(got, chunkBytes(0x51)) { - t.Fatalf("snapshot bytes lost: %v", e) - } - } - *now = now.Add(2 * time.Hour) - if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { - t.Fatalf("first unrooted mark: %+v %v", result, e) - } - *now = now.Add(time.Hour + g.cfg.ClockSkew + time.Nanosecond) - if result, e := g.Run(ctx); e != nil || result.Reclaimed != 2 { - t.Fatalf("deleted attempt retained chunks forever: %+v %v", result, e) - } - if _, e := f.LookupEntry(ctx, path.Dir(oldPath), path.Base(oldPath)); e != nil { - t.Fatal("permanent attempt entry removed", e) - } -} - -func TestGC_CopyClaimUnknownRetainsIntent(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - c.SetClock(func() time.Time { return *now }) - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x61)}) - snapshotDir(t, f, "v1", "s1") - holdFirst(f, path.Join(catBase, "v1", snapsDir, "s1")+"/") - if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "dead"}, h); CodeOf(e) != CodeOutcomeUnknown { - t.Fatal(e) - } - *now = now.Add(DefaultOpDeadline + time.Second) - f.failCreate = func(string) error { return errors.New("claim outcome unknown") } - if n, e := g.SweepCopies(ctx); e == nil || n != 0 { - t.Fatalf("unknown claim accepted: %d %v", n, e) - } - if ins := intentsOf(t, f, "v1"); len(ins) != 1 { - t.Fatalf("unknown claim released root: %+v", ins) - } - f.failCreate = nil - if n, e := g.SweepCopies(ctx); e != nil || n != 1 { - t.Fatalf("claim recovery: %d %v", n, e) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go b/seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go deleted file mode 100644 index 0874adcddd..0000000000 --- a/seaweed-block/core/frontend/chunkstore/gc_delete_progress_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "path" - "strings" - "sync" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func TestGCPermanentDeleteDoesNotStarveLaterBindings(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - for _, key := range []string{"a_bad", "b_later", "rooted"} { - if err := r.Put(ctx, key, []byte(key)); err != nil { - t.Fatal(err) - } - } - if _, err := r.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "live", Keys: []string{"rooted"}}); err != nil { - t.Fatal(err) - } - entry, err := f.LookupEntry(ctx, path.Join(catBase, "v1", keysDir), "a_bad") - if err != nil { - t.Fatal(err) - } - badFID := string(entry.Extended[extFid]) - calls := map[string]int{} - var callsMu sync.Mutex - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - fid := strings.TrimPrefix(req.URL.Path, "/") - callsMu.Lock() - calls[fid]++ - callsMu.Unlock() - if fid == badFID { - http.Error(w, "cookie mismatch", http.StatusBadRequest) - return - } - if err := b.DeleteBlob(req.Context(), fid); err != nil { - t.Error(err) - } - w.WriteHeader(http.StatusAccepted) - })) - defer server.Close() - deleter := &SWFS{http: server.Client(), vidCache: map[string][]string{"3": {strings.TrimPrefix(server.URL, "http://")}}} - if _, err := c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true); err != nil { - t.Fatal(err) - } - *now = now.Add(2 * time.Hour) - out, err := c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true) - if out.Reclaimed != 1 { - t.Fatalf("permanent DELETE starved later binding: %+v err=%v", out, err) - } - if len(out.FailedDeletes) != 1 || out.FailedDeletes[0].FID != badFID || out.FailedDeletes[0].Key != "a_bad" || out.FailedDeletes[0].Volume != "v1" || !strings.Contains(out.FailedDeletes[0].Error, "http 400") { - t.Fatalf("object refusal missing from result: %+v", out) - } - if !errors.Is(err, ErrBlobDeleteRejected) || !out.MarkSaved { - t.Fatalf("partial deletion must retain complete mark coverage: %+v %v", out, err) - } - badEntry, err := f.LookupEntry(ctx, path.Join(catBase, "v1", keysDir), "a_bad") - if err != nil || string(badEntry.Extended[extGCDeleted]) != "1" { - t.Fatalf("failed DELETE declared done: %+v %v", badEntry, err) - } - if _, err := r.Get(ctx, "rooted"); err != nil { - t.Fatal("protected root lost", err) - } - // A repeatedly rejected older object must not erase a younger object's - // first mark, including when each pass is a new collector process. - if err := r.Put(ctx, "c_new", []byte("c_new")); err != nil { - t.Fatal(err) - } - for i := 0; i < 2; i++ { - *now = now.Add(2 * time.Hour) - out, err = c.ExecuteVolumeGC(ctx, "v1", deleter, g.cfg, true) - if (err != nil && !errors.Is(err, ErrBlobDeleteRejected)) || !out.MarkSaved || ((len(out.FailedDeletes) > 0) != errors.Is(err, ErrBlobDeleteRejected)) { - t.Fatalf("repeated rejection stalled coverage: %+v %v", out, err) - } - if i == 1 && out.Reclaimed != 1 { - t.Fatalf("younger binding lost coverage: %+v", out) - } - } - callsMu.Lock() - badCalls := calls[badFID] - callsMu.Unlock() - if badCalls < 2 { - t.Fatal("failed binding was silently abandoned") - } - if err := r.Put(ctx, "a_bad", []byte("rebind")); err == nil { - t.Fatal("failed deletion permitted rebinding") - } -} diff --git a/seaweed-block/core/frontend/chunkstore/gc_execution.go b/seaweed-block/core/frontend/chunkstore/gc_execution.go deleted file mode 100644 index 98188a765c..0000000000 --- a/seaweed-block/core/frontend/chunkstore/gc_execution.go +++ /dev/null @@ -1,221 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "io" - "path" - "strings" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -const gcMarkName = "_GC_MARK" -const gcMarkKind = "chunkgcmark" -const gcToken = "swb.gc.token" - -type savedGCCandidate struct { - SinceNs int64 `json:"since_ns"` - Digest string `json:"digest"` -} -type savedGCMark struct { - Scope string `json:"scope,omitempty"` - Format int `json:"format"` - Base string `json:"base"` - GraceNs int64 `json:"grace_ns"` - ClockSkewNs int64 `json:"clock_skew_ns"` - TTLNs int64 `json:"ttl_ns"` - OpDeadlineNs int64 `json:"op_deadline_ns"` - Ready bool `json:"ready"` - LastNs int64 `json:"last_ns"` - Candidates map[string]savedGCCandidate `json:"candidates"` -} - -type GCExecution struct { - // MarkSaved confirms this caller received the completed-write response; - // false does not prove that no completed mark exists remotely. - MarkOutcome string `json:"mark_outcome"` - UnknownOutcomes []string `json:"unknown_outcomes"` - DryRun bool `json:"dry_run"` - SettledCopies int `json:"settled_copy_intents"` - MarkSaved bool `json:"mark_saved"` - GCResult -} - -// ExecuteGC binds independent CLI calls to completed filer-side marks. -// Preview never writes even the watermark. Apply first invalidates stored -// coverage with a conditional empty/in-progress record before other effects. -// A write may commit despite a lost response: errors retain known effects -// and identify uncertain stages, rather than asserting remote absence. -// The catalog namespace is the scope; permanent tombstones are untouched. -func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool) (out GCExecution, err error) { - return c.executeGC(ctx, blobs, cfg, apply, "") -} - -// ExecuteVolumeGC reclaims only volumeID's objects while tracing every volume's -// roots. Its persisted two-mark coverage never aliases namespace-wide coverage. -func (c *Catalog) ExecuteVolumeGC(ctx context.Context, volumeID string, blobs BlobDeleter, cfg GCConfig, apply bool) (GCExecution, error) { - if err := CheckVolumeID(volumeID); err != nil { - return GCExecution{GCResult: GCResult{UnknownUnbound: true}}, err - } - return c.executeGC(ctx, blobs, cfg, apply, volumeID) -} - -func (c *Catalog) executeGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool, scope string) (out GCExecution, err error) { - // Pre-binding needles remain unenumerable even if admission/readback fails. - out.UnknownUnbound = true - out.DryRun = !apply - out.MarkOutcome = "not_attempted" - out.UnknownOutcomes = []string{} - g, err := NewCollector(c, blobs, cfg) - if err != nil { - return out, err - } - g.scope = scope - mark, previous, err := g.readMark(ctx) - if err != nil { - return out, err - } - if mark != nil && mark.Ready && mark.GraceNs == int64(cfg.Grace) && mark.TTLNs == int64(g.cfg.IntentTTL) && mark.ClockSkewNs == int64(g.cfg.ClockSkew) && mark.OpDeadlineNs == int64(c.deadline()) { - for p, candidate := range mark.Candidates { - raw, _ := hex.DecodeString(candidate.Digest) - var digest [32]byte - copy(digest[:], raw) - g.candidates[p] = gcCandidate{time.Unix(0, candidate.SinceNs), digest} - } - g.last = time.Unix(0, mark.LastNs) - } - if !apply { - out.GCResult, err = g.Preview(ctx) - return out, err - } - busy := g.mark(false) - token, err := g.writeMark(ctx, busy, previous) - if err != nil { - out.MarkOutcome = "unknown" - out.UnknownOutcomes = append(out.UnknownOutcomes, "in_progress_mark_write") - return out, err - } - out.MarkOutcome = "in_progress" - out.SettledCopies, err = g.SweepCopies(ctx) - if err != nil { - out.UnknownOutcomes = append(out.UnknownOutcomes, "copy_intent_settlement") - return out, err - } - out.GCResult, err = g.Run(ctx) - if err != nil { - out.UnknownOutcomes = append(out.UnknownOutcomes, "reclamation") - return out, err - } - _, err = g.writeMark(ctx, g.mark(true), token) - if err != nil { - out.MarkOutcome = "unknown" - out.UnknownOutcomes = append(out.UnknownOutcomes, "completed_mark_write") - return out, err - } - out.MarkOutcome = "complete" - out.MarkSaved = true - if len(out.FailedDeletes) != 0 { - // The mark completed and is reusable even though these tombstoned - // objects remain. Report partial failure after persisting coverage, - // so CLI/maintenance callers cannot mistake it for full reclamation. - return out, fmt.Errorf("%w: %d objects retained; complete GC mark saved", ErrBlobDeleteRejected, len(out.FailedDeletes)) - } - return out, nil -} - -func (g *Collector) mark(ready bool) savedGCMark { - m := savedGCMark{Format: 1, Scope: g.scope, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), ClockSkewNs: int64(g.cfg.ClockSkew), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}} - if ready { - m.LastNs = g.last.UnixNano() - for p, c := range g.candidates { - m.Candidates[p] = savedGCCandidate{c.since.UnixNano(), hex.EncodeToString(c.digest[:])} - } - } - return m -} - -func (g *Collector) markDir() string { - if g.scope != "" { - return path.Join(g.cat.base, g.scope) - } - return g.cat.base -} - -func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error) { - e, err := g.cat.f.LookupEntry(ctx, g.markDir(), gcMarkName) - if errors.Is(err, ErrNotFound) { - return nil, "", nil - } - if err != nil { - return nil, "", err - } - token := string(e.Extended[gcToken]) - if e.GetIsDirectory() || len(e.GetChunks()) != 0 || string(e.Extended[extKind]) != gcMarkKind || !storage.ValidChunkIntentID(token) || len(e.Content) > 64<<20 { - return nil, "", errors.New("chunkstore: invalid GC mark entry") - } - var m savedGCMark - d := json.NewDecoder(bytes.NewReader(e.Content)) - d.DisallowUnknownFields() - if err = d.Decode(&m); err != nil { - return nil, "", err - } - var trailing any - if err = d.Decode(&trailing); err != io.EOF { - return nil, "", errors.New("chunkstore: trailing GC mark content") - } - if m.Format != 1 || m.Scope != g.scope || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 || m.ClockSkewNs < 0 { - return nil, "", errors.New("chunkstore: incompatible GC mark") - } - if m.Ready { - now := g.cfg.Now().UnixNano() - if m.LastNs <= 0 { - return nil, "", errors.New("chunkstore: invalid GC mark time") - } - for p, c := range m.Candidates { - digest, err := hex.DecodeString(c.Digest) - if err != nil || len(digest) != 32 || c.SinceNs <= 0 || c.SinceNs > m.LastNs || path.Clean(p) != p || !strings.HasPrefix(p, g.markDir()+"/") || !strings.Contains(p, "/"+keysDir+"/") { - return nil, "", errors.New("chunkstore: invalid GC candidate state") - } - } - if m.LastNs > now { - // A valid mark from a faster clock cannot supply elapsed coverage. - // Keep its token for the conditional replacement, but start afresh. - m.Ready, m.LastNs, m.Candidates = false, 0, nil - } - } else if m.LastNs != 0 || len(m.Candidates) != 0 { - return nil, "", errors.New("chunkstore: incomplete GC mark carries coverage") - } - return &m, token, nil -} - -func (g *Collector) writeMark(ctx context.Context, m savedGCMark, expected string) (string, error) { - token, err := storage.NewChunkIntentID(0) - if err != nil { - return "", err - } - body, err := json.Marshal(m) - if err != nil { - return "", err - } - if len(body) > 64<<20 { - return "", errors.New("chunkstore: GC mark exceeds 64 MiB") - } - now := g.cfg.Now().Unix() - e := &filerpb.Entry{Name: gcMarkName, Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Crtime: now, Mtime: now, FileMode: 0600}, Content: body, Extended: map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(token)}} - if expected == "" { - err = g.cat.f.CreateEntry(ctx, g.markDir(), e, true) - } else { - err = g.cat.f.UpdateEntry(ctx, g.markDir(), e, map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(expected)}) - } - if err != nil { - return "", fmt.Errorf("chunkstore: GC watermark changed or unavailable: %w", err) - } - return token, nil -} diff --git a/seaweed-block/core/frontend/chunkstore/gc_execution_test.go b/seaweed-block/core/frontend/chunkstore/gc_execution_test.go deleted file mode 100644 index 84b089e9c9..0000000000 --- a/seaweed-block/core/frontend/chunkstore/gc_execution_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "path" - "testing" - "time" -) - -func TestGCExecution_PreviewAndIndependentApplyMarks(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if e := r.Put(ctx, "orphan", []byte("orphan")); e != nil { - t.Fatal(e) - } - preview, e := c.ExecuteGC(ctx, b, g.cfg, false) - if e != nil || !preview.DryRun || preview.MarkSaved || len(preview.WouldDelete) != 0 { - t.Fatalf("first preview: %+v %v", preview, e) - } - if _, e = f.LookupEntry(ctx, catBase, gcMarkName); !errors.Is(e, ErrNotFound) { - t.Fatalf("preview created state: %v", e) - } - first, e := c.ExecuteGC(ctx, b, g.cfg, true) - if e != nil || first.DryRun || !first.MarkSaved || first.Reclaimed != 0 { - t.Fatalf("first applied mark: %+v %v", first, e) - } - *now = now.Add(time.Hour - time.Second) - early, e := c.ExecuteGC(ctx, b, g.cfg, false) - if e != nil || len(early.WouldDelete) != 0 { - t.Fatalf("early independent preview: %+v %v", early, e) - } - *now = now.Add(2*time.Second + g.cfg.ClockSkew) - before, _ := f.LookupEntry(ctx, catBase, gcMarkName) - mature, e := c.ExecuteGC(ctx, b, g.cfg, false) - if e != nil || len(mature.WouldDelete) != 1 || mature.Reclaimed != 0 { - t.Fatalf("mature preview: %+v %v", mature, e) - } - after, _ := f.LookupEntry(ctx, catBase, gcMarkName) - if string(before.Content) != string(after.Content) || string(before.Extended[gcToken]) != string(after.Extended[gcToken]) { - t.Fatal("preview advanced persistent state") - } - if _, e = r.Get(ctx, "orphan"); e != nil { - t.Fatal("preview deleted a chunk", e) - } - applied, e := c.ExecuteGC(ctx, b, g.cfg, true) - if e != nil || applied.Reclaimed != 1 || !applied.MarkSaved { - t.Fatalf("independent second apply: %+v %v", applied, e) - } - if _, e = r.Get(ctx, "orphan"); e == nil { - t.Fatal("applied GC did not delete orphan") - } -} - -func TestGCExecution_FailedPassInvalidatesPersistedCoverage(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if e := r.Put(ctx, "orphan", []byte("orphan")); e != nil { - t.Fatal(e) - } - if _, e := c.ExecuteGC(ctx, b, g.cfg, true); e != nil { - t.Fatal(e) - } - *now = now.Add(2 * time.Hour) - wrapped := &failingGCListing{Filer: f, fail: true} - c.f = wrapped - if _, e := c.ExecuteGC(ctx, b, g.cfg, true); e == nil { - t.Fatal("failed scan reported success") - } - wrapped.fail = false - pass, e := c.ExecuteGC(ctx, b, g.cfg, true) - if e != nil || pass.Reclaimed != 0 { - t.Fatalf("failed/crashed pass retained old coverage: %+v %v", pass, e) - } -} - -func TestGCExecution_WatermarkConflictDispatchesNoReclaim(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if e := r.Put(ctx, "orphan", []byte("orphan")); e != nil { - t.Fatal(e) - } - if _, e := c.ExecuteGC(ctx, b, g.cfg, true); e != nil { - t.Fatal(e) - } - *now = now.Add(2 * time.Hour) - f.failUpdate = func(p string) error { - if p == path.Join(catBase, gcMarkName) { - return ErrPrecondition - } - return nil - } - if _, e := c.ExecuteGC(ctx, b, g.cfg, true); e == nil { - t.Fatal("watermark conflict reported success") - } - if _, e := r.Get(ctx, "orphan"); e != nil { - t.Fatal("conflicting pass deleted bytes", e) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/gc_test.go b/seaweed-block/core/frontend/chunkstore/gc_test.go deleted file mode 100644 index 70ff2d2eab..0000000000 --- a/seaweed-block/core/frontend/chunkstore/gc_test.go +++ /dev/null @@ -1,393 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "errors" - "net/http" - "net/http/httptest" - "path" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -type gcBlobs struct{ *fakeBlobs } - -func (b gcBlobs) DeleteBlob(_ context.Context, fid string) error { - b.mu.Lock() - defer b.mu.Unlock() - delete(b.data, fid) - return nil -} - -type heldGCRemote struct { - *ChunkRemote - entered chan struct{} - release chan struct{} -} - -func (r *heldGCRemote) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) { - close(r.entered) - select { - case <-r.release: - case <-ctx.Done(): - return 0, ctx.Err() - } - return r.ChunkRemote.CASHead(ctx, v, h) -} - -func gcFixture(t *testing.T) (*fakeFiler, gcBlobs, *Catalog, *Collector, *time.Time) { - t.Helper() - f, b := newFakeFiler(), gcBlobs{newFakeBlobs()} - c := newCat(t, f) - if e := f.CreateEntry(context.Background(), catBase, &filerpb.Entry{Name: "v1", IsDirectory: true}, true); e != nil { - t.Fatal(e) - } - if _, e := c.EnsureVolume(context.Background(), "v1", catGeo); e != nil { - t.Fatal(e) - } - now := time.Now().Add(24 * time.Hour) - g, e := NewCollector(c, b, GCConfig{Grace: time.Hour, IntentTTL: time.Hour, Now: func() time.Time { return now }, IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) - if e != nil { - t.Fatal(e) - } - return f, b, c, g, &now -} - -func TestGC_StalledCutRemainsReadableAfterTwoMarks(t *testing.T) { - f, b, _, g, now := gcFixture(t) - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - defer cancel() - remote, e := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if e != nil { - t.Fatal(e) - } - held := &heldGCRemote{remote, make(chan struct{}), make(chan struct{})} - p := filepath.Join(t.TempDir(), "volume") - s, e := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8}) - if e != nil { - t.Fatal(e) - } - defer s.Close() - if _, e = s.Recover(); e != nil { - t.Fatal(e) - } - layer, e := storage.AttachChunkLayer(s, held, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true}) // a new, empty store: its dirty set is known (empty) - if e != nil { - t.Fatal(e) - } - want := bytes.Repeat([]byte{0x71}, 4096) - if _, e = s.Write(0, want); e != nil { - t.Fatal(e) - } - done := make(chan error, 1) - go func() { _, e := layer.Capture(ctx); done <- e }() - select { - case <-held.entered: - case <-ctx.Done(): - t.Fatal("cut never reached post-upload CAS") - } - // Always release the owned cut before Close, including a failing assertion. - released := false - defer func() { - if !released { - close(held.release) - <-done - } - }() - for i := 0; i < 2; i++ { - result, e := g.Run(ctx) - if e != nil { - t.Fatal(e) - } - t.Logf("mark %d: %+v", i+1, result) - *now = now.Add(time.Hour + time.Second) - } - close(held.release) - released = true - if e := <-done; e != nil { - t.Fatal(e) - } - h, e := remote.GetHead(ctx) - if e != nil || h.Gen == 0 { - t.Fatalf("published HEAD: %+v %v", h, e) - } - for _, ref := range h.Chunks { - got, e := remote.Get(ctx, ref.Key) - if e != nil || !bytes.Equal(got[:min(len(got), 4096)], want) { - t.Fatalf("published HEAD references deleted or corrupt stalled-cut chunk: key=%q bytes=%d err=%v", ref.Key, len(got), e) - } - } -} - -func TestGC_UnreachableRequiresTwoMarksAndUploadAge(t *testing.T) { - f, b, _, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if e := r.Put(ctx, "orphan", []byte("exact orphan")); e != nil { - t.Fatal(e) - } - if _, e := g.Run(ctx); e != nil { - t.Fatal(e) - } - *now = now.Add(time.Hour - time.Second) - if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { - t.Fatalf("early second mark: %+v %v", result, e) - } - if _, e := r.Get(ctx, "orphan"); e != nil { - t.Fatal("orphan deleted before grace", e) - } - *now = now.Add(2*time.Second + g.cfg.ClockSkew) - result, e := g.Run(ctx) - if e != nil || result.Reclaimed != 1 { - t.Fatalf("old unreachable chunk was not reclaimed after grace-separated marks: %+v %v", result, e) - } - if _, e := r.Get(ctx, "orphan"); e == nil { - t.Fatal("reclaimed orphan remains readable") - } - fresh, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if e := fresh.Put(ctx, "orphan", []byte("reused")); !errors.Is(e, storage.ErrChunkKeyExists) { - t.Fatalf("immutable key reused after GC: %v", e) - } - // A freshly uploaded chunk cannot enter its first candidate mark yet. - *now = time.Now() - next, e := NewCollector(g.cat, b, g.cfg) - if e != nil { - t.Fatal(e) - } - if e := r.Put(ctx, "young", []byte("young")); e != nil { - t.Fatal(e) - } - if result, e := next.Run(ctx); e != nil || result.Candidates != 0 { - t.Fatalf("young upload admitted: %+v %v", result, e) - } -} - -func TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence(t *testing.T) { - for _, tc := range []struct { - name string - issued, head uint64 - age time.Duration - authorityErr bool - expire bool - }{ - {"current-holder-old-intent", 1, 1, 2 * time.Hour, false, false}, - {"higher-issued-but-no-takeover", 2, 1, 2 * time.Hour, false, false}, - {"takeover-but-no-authority", 1, 2, 2 * time.Hour, false, false}, - {"unknown-authority", 2, 2, 2 * time.Hour, true, false}, - {"TTL-not-exceeded", 2, 2, time.Hour, false, false}, - {"higher-issued-and-fenced", 2, 2, time.Hour + DefaultGCClockSkew + time.Nanosecond, false, true}, - } { - t.Run(tc.name, func(t *testing.T) { - f, b, _, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if e := r.Put(ctx, "inflight", []byte("protected")); e != nil { - t.Fatal(e) - } - id, e := r.PutIntent(ctx, storage.ChunkIntent{Gen: 0, Epoch: 1, Holder: "h1", Keys: []string{"inflight"}}) - if e != nil { - t.Fatal(e) - } - ins, e := r.ListIntents(ctx) - if e != nil || len(ins) != 1 { - t.Fatalf("intent: %+v %v", ins, e) - } - *now = time.Unix(0, ins[0].CreatedNs).Add(tc.age) - // A real remote HEAD fence. The publisher's original expected version - // can no longer install after epoch 2 was published. - cur, e := r.GetHead(ctx) - if e != nil { - t.Fatal(e) - } - old := storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch} - if _, e = r.CASHead(ctx, old, storage.ChunkHead{Epoch: tc.head, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); e != nil { - t.Fatal(e) - } - g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { - if tc.authorityErr { - return 0, errors.New("authority unavailable") - } - return tc.issued, nil - } - result, e := g.Run(ctx) - if e != nil { - t.Fatal(e) - } - ins, e = r.ListIntents(ctx) - if e != nil { - t.Fatal(e) - } - if (len(ins) == 0) != tc.expire { - t.Fatalf("intent %s expired=%v want=%v; %+v", id, len(ins) == 0, tc.expire, result) - } - if result.Reclaimed != 0 { - t.Fatal("one mark reclaimed bytes") - } - if tc.expire { - _, e = r.CASHead(ctx, old, storage.ChunkHead{Epoch: 1, Holder: "h1"}) - if !errors.Is(e, storage.ErrChunkHeadPrecondition) { - t.Fatalf("expired publisher can still CAS: %v", e) - } - } - }) - } -} - -type failingGCListing struct { - Filer - fail bool -} - -func (f *failingGCListing) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { - if f.fail { - return nil, errors.New("listing unavailable") - } - return f.Filer.ListEntries(ctx, dir, prefix, after, limit) -} -func TestGC_FailedMarkAndRestartNeverReuseCoverage(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if e := r.Put(ctx, "orphan", []byte("orphan")); e != nil { - t.Fatal(e) - } - wrapper := &failingGCListing{Filer: f} - c.f = wrapper - if _, e := g.Run(ctx); e != nil { - t.Fatal(e) - } - *now = now.Add(2 * time.Hour) - wrapper.fail = true - if _, e := g.Run(ctx); e == nil { - t.Fatal("failed listing accepted") - } - wrapper.fail = false - if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { - t.Fatalf("failed mark preserved coverage: %+v %v", result, e) - } - fresh, e := NewCollector(c, b, g.cfg) - if e != nil { - t.Fatal(e) - } - *now = now.Add(2 * time.Hour) - if result, e := fresh.Run(ctx); e != nil || result.Reclaimed != 0 { - t.Fatalf("restart inferred prior mark: %+v %v", result, e) - } -} - -func TestGC_SnapshotAndQualifiedForkAreRoots(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x21)}) - if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); e != nil { - t.Fatal(e) - } - if e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil { - t.Fatal(e) - } - if _, e := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); e != nil { - t.Fatal(e) - } - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}}); e != nil { - t.Fatal(e) - } - for i := 0; i < 2; i++ { - if result, e := g.Run(ctx); e != nil || result.Reclaimed != 0 { - t.Fatalf("rooted data reclaimed: %+v %v", result, e) - } - *now = now.Add(2 * time.Hour) - } - for _, ref := range h.Chunks { - if got, e := r.Get(ctx, ref.Key); e != nil || !bytes.Equal(got, chunkBytes(0x21)) { - t.Fatalf("shared bytes: %v", e) - } - } -} - -func TestGC_CopyIntentSurvivesTakeover(t *testing.T) { - f, b, _, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - for _, holder := range []string{"snapshot:v1/s1/req", "fork:v1/req"} { - if _, e := r.PutIntent(ctx, storage.ChunkIntent{Gen: 0, Epoch: 1, Holder: holder, Keys: []string{"k"}}); e != nil { - t.Fatal(e) - } - } - cur, e := r.GetHead(ctx) - if e != nil { - t.Fatal(e) - } - if _, e := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new"}); e != nil { - t.Fatal(e) - } - g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil } - *now = now.Add(24 * time.Hour) - if result, e := g.Run(ctx); e != nil || result.ExpiredIntents != 0 { - t.Fatalf("epochless copy publication lost its protection: %+v %v", result, e) - } - intents, e := r.ListIntents(ctx) - if e != nil || len(intents) != 2 { - t.Fatalf("copy intents: %+v %v", intents, e) - } -} - -func TestSWFS_DeleteBlobStatusesAndExactPath(t *testing.T) { - for _, status := range []int{200, 202, 204, 404, 400, 401, 500} { - t.Run(http.StatusText(status), func(t *testing.T) { - calls := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls++ - if r.Method != "DELETE" || r.URL.Path != "/7,01abcdef" { - t.Errorf("unexpected delete %s %s", r.Method, r.URL.Path) - } - w.WriteHeader(status) - })) - defer server.Close() - c := &SWFS{http: server.Client(), vidCache: map[string][]string{"7": {strings.TrimPrefix(server.URL, "http://")}}} - e := c.DeleteBlob(context.Background(), "7,01abcdef") - if (e == nil) != (status == 200 || status == 202 || status == 204 || status == 404) { - t.Fatalf("status %d: %v", status, e) - } - if errors.Is(e, ErrBlobDeleteRejected) != (status == 400) { - t.Fatalf("wrong per-object refusal classification: status=%d err=%v", status, e) - } - if calls != 1 { - t.Fatalf("calls %d", calls) - } - for _, bad := range []string{"7,../bad", "7,a?bad", "7,a%2fb", "", ",a"} { - if e := c.DeleteBlob(context.Background(), bad); e == nil { - t.Errorf("invalid fid accepted: %q", bad) - } - } - if calls != 1 { - t.Fatal("invalid fid dispatched HTTP") - } - }) - } -} - -func TestGC_UnboundNeedleRetainedAndCountUnknown(t *testing.T) { - _, b, _, g, now := gcFixture(t) - ctx := context.Background() - fid, e := b.Put(ctx, []byte("pre-binding orphan")) - if e != nil { - t.Fatal(e) - } - for i := 0; i < 3; i++ { - result, e := g.Run(ctx) - if e != nil || !result.UnknownUnbound || result.Reclaimed != 0 { - t.Fatalf("unbound inventory claim: %+v %v", result, e) - } - *now = now.Add(2 * time.Hour) - } - if got, e := b.Get(ctx, fid); e != nil || string(got) != "pre-binding orphan" { - t.Fatalf("unbound orphan deleted: %q %v", got, e) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go deleted file mode 100644 index ea5cfdc98f..0000000000 --- a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go +++ /dev/null @@ -1,251 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "path" - "reflect" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func TestVolumeGC_ForeignIntentRootsAndLocalCandidates(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { - t.Fatal(err) - } - v1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - v2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) - for _, key := range []string{"rooted-only-from-v2", "local-orphan"} { - if err := v1.Put(ctx, key, []byte(key)); err != nil { - t.Fatal(err) - } - } - if err := v2.Put(ctx, "foreign-orphan", []byte("foreign")); err != nil { - t.Fatal(err) - } - if _, err := v2.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "snapshot:v2/s1/req", Keys: []string{"@v1/rooted-only-from-v2"}}); err != nil { - t.Fatal(err) - } - for i := 0; i < 2; i++ { - if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil { - t.Fatal(err) - } - *now = now.Add(2 * time.Hour) - } - if _, err := v1.Get(ctx, "local-orphan"); err == nil { - t.Error("local orphan not reclaimed") - } - if _, err := v1.Get(ctx, "rooted-only-from-v2"); err != nil { - t.Errorf("foreign root lost: %v", err) - } - if _, err := v2.Get(ctx, "foreign-orphan"); err != nil { - t.Errorf("scoped pass reclaimed foreign candidate: %v", err) - } -} - -// Grace must cover the operation deadline, the clock skew and the CAS apply -// bound (default: the deadline), so a snapshot deleted while a fork of it is -// in flight stays rooted until that fork can no longer publish. -func TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound(t *testing.T) { - _, b, c, g, _ := gcFixture(t) - need := c.deadline() + DefaultGCClockSkew + c.deadline() - for _, grace := range []time.Duration{0, c.deadline(), c.deadline() + DefaultGCClockSkew, need - time.Nanosecond} { - cfg := g.cfg - cfg.Grace, cfg.ClockSkew, cfg.CASApplyBound = grace, 0, 0 - if _, err := NewCollector(c, b, cfg); err == nil { - t.Errorf("accepted grace %s < deadline + skew + apply bound %s", grace, need) - } - } - cfg := g.cfg - cfg.Grace, cfg.ClockSkew, cfg.CASApplyBound = need, 0, 0 - if _, err := NewCollector(c, b, cfg); err != nil { - t.Fatalf("grace = deadline + skew + apply bound: %v", err) - } - cfg.Grace, cfg.CASApplyBound = need, time.Second // an explicit, smaller bound - if _, err := NewCollector(c, b, cfg); err != nil { - t.Fatal(err) - } - cfg.CASApplyBound = -1 - if _, err := NewCollector(c, b, cfg); err == nil { - t.Fatal("accepted a negative CAS apply bound") - } -} - -func TestVolumeGC_DoesNotImportGlobalMark(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err := r.Put(ctx, "orphan", []byte("bytes")); err != nil { - t.Fatal(err) - } - if _, err := c.ExecuteGC(ctx, b, g.cfg, true); err != nil { - t.Fatal(err) - } - *now = now.Add(2 * time.Hour) - // A separate scope must take its own first mark, even with mature global coverage. - result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) - if err != nil || result.Reclaimed != 0 { - t.Fatalf("scope imported namespace coverage: %+v %v", result, err) - } - if _, err = f.LookupEntry(ctx, path.Join(catBase, "v1"), gcMarkName); errors.Is(err, ErrNotFound) { - t.Fatal("scoped watermark absent") - } -} - -func TestVolumeGC_IncompletePassAndConfigChangeDiscardCoverage(t *testing.T) { - for _, mode := range []string{"incomplete", "config"} { - t.Run(mode, func(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err := r.Put(ctx, "orphan", []byte("bytes")); err != nil { - t.Fatal(err) - } - if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil { - t.Fatal(err) - } - *now = now.Add(2 * time.Hour) - if mode == "incomplete" { - g.scope = "v1" - _, token, err := g.readMark(ctx) - if err != nil { - t.Fatal(err) - } - if _, err = g.writeMark(ctx, g.mark(false), token); err != nil { - t.Fatal(err) - } - } else { - g.cfg.IntentTTL += time.Second - } - result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) - if err != nil || result.Reclaimed != 0 { - t.Fatalf("stale coverage used: %+v %v", result, err) - } - *now = now.Add(2 * time.Hour) - result, err = c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) - if err != nil || result.Reclaimed != 1 { - t.Fatalf("fresh coverage did not progress: %+v %v", result, err) - } - }) - } -} - -func TestVolumeGC_ForeignForkHeadIsSoleRoot(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x22)}) - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); err != nil { - t.Fatal(err) - } - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { - t.Fatal(err) - } - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}}); err != nil { - t.Fatal(err) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - for i := 0; i < 2; i++ { - if out, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil || out.Reclaimed != 0 { - t.Fatalf("foreign-only fork root reclaimed: %+v %v", out, err) - } - *now = now.Add(2 * time.Hour) - } - for _, ref := range h.Chunks { - if _, err := r.Get(ctx, ref.Key); err != nil { - t.Fatal("fork bytes reclaimed", err) - } - } -} - -func TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { - t.Fatal(err) - } - remotes := map[string]*ChunkRemote{} - for _, vol := range []string{"v1", "v2"} { - remote, _ := NewChunkRemote(f, b, path.Join(catBase, vol)) - remotes[vol] = remote - if err := remote.Put(ctx, "capture", []byte("protected")); err != nil { - t.Fatal(err) - } - if _, err := remote.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "old", Keys: []string{"capture"}}); err != nil { - t.Fatal(err) - } - cur, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); err != nil { - t.Fatal(err) - } - } - g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil } - *now = time.Now().Add(3 * time.Hour) - foreign, _ := remotes["v2"].ListIntents(ctx) - result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) - local, _ := remotes["v1"].ListIntents(ctx) - after, _ := remotes["v2"].ListIntents(ctx) - if err != nil || result.ExpiredIntents != 1 || len(local) != 0 || !reflect.DeepEqual(foreign, after) { - t.Fatalf("capture scope mutated foreign intent: %+v %v before=%+v after=%+v", result, err, foreign, after) - } - if _, err := remotes["v2"].Get(ctx, "capture"); err != nil { - t.Fatal("foreign protection lost", err) - } - result, err = c.ExecuteVolumeGC(ctx, "v2", b, g.cfg, true) - if err != nil || result.ExpiredIntents != 1 { - t.Fatalf("foreign positive eligibility not witnessed: %+v %v", result, err) - } -} -func TestVolumeGC_ForeignEligibleCopyIsNotSettled(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - c.SetClock(func() time.Time { return *now }) - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil { - t.Fatal(err) - } - for _, vol := range []string{"v1", "v2"} { - h := publishSource(t, f, b.fakeBlobs, vol, map[uint64][]byte{0: chunkBytes(0x55)}) - snapshotDir(t, f, vol, "held") - holdFirst(f, path.Join(catBase, vol, snapsDir, "held")+"/") - if _, err := c.CreateSnapshot(ctx, vol, SnapshotRequest{Name: "held", RequestID: "dead"}, h); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("copy not held: %v", err) - } - } - before := intentsOf(t, f, "v2") - foreignPath := snapPath(t, f, "v2", "held") - *now = now.Add(DefaultOpDeadline + time.Second) - result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true) - after := intentsOf(t, f, "v2") - if err != nil || result.SettledCopies != 1 || len(intentsOf(t, f, "v1")) != 0 || !reflect.DeepEqual(before, after) { - t.Fatalf("copy scope changed foreign attempt: %+v %v", result, err) - } - if _, err := f.LookupEntry(ctx, path.Dir(foreignPath), path.Base(foreignPath)); !errors.Is(err, ErrNotFound) { - t.Fatalf("foreign pending copy claimed: %v", err) - } - result, err = c.ExecuteVolumeGC(ctx, "v2", b, g.cfg, true) - if err != nil || result.SettledCopies != 1 || len(intentsOf(t, f, "v2")) != 0 { - t.Fatalf("foreign positive settlement not witnessed: %+v %v", result, err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go b/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go deleted file mode 100644 index ed22ed0be0..0000000000 --- a/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "path" - "reflect" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -type rootCASFiler struct { - Filer - roots, children int - refuseChildren bool -} - -func (f *rootCASFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { - if name == headName { - f.roots++ - } else { - f.children++ - if f.refuseChildren { - return nil, errors.New("segment service unavailable") - } - } - return f.Filer.LookupEntry(ctx, dir, name) -} - -// A HEAD CAS validates root authority, not the availability of every immutable -// segment. Ordinary GetHead still resolves and verifies all segment contents. -func TestManifest_CASReadsOnlyRoot(t *testing.T) { - f, b, _, _, _ := gcFixture(t) - _, h := publishSegmented(t, f, b) - tracked := &rootCASFiler{Filer: f, refuseChildren: true} - r, err := NewChunkRemote(tracked, b, path.Join(catBase, "v1")) - if err != nil { - t.Fatal(err) - } - next := h - next.RemoteLSN++ - gen, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next) - if err != nil { - t.Fatalf("root-only CAS must not depend on segments: %v", err) - } - if gen != h.Gen+1 || tracked.roots != 1 || tracked.children != 0 { - t.Fatalf("CAS gen=%d root reads=%d child reads=%d", gen, tracked.roots, tracked.children) - } - root, err := r.GetHeadRoot(context.Background()) - if err != nil || root.Gen != gen || root.Epoch != h.Epoch || root.Holder != h.Holder || tracked.children != 0 { - t.Fatalf("confirmation resolved segments: root=%+v children=%d err=%v", root, tracked.children, err) - } - if _, err := r.GetHead(context.Background()); err == nil { - t.Fatal("GetHead skipped segment resolution") - } - tracked.refuseChildren = false - got, err := r.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - if got.Gen != gen || got.RemoteLSN != next.RemoteLSN || !reflect.DeepEqual(got.Chunks, h.Chunks) || !reflect.DeepEqual(got.Segments, h.Segments) { - t.Fatalf("CAS changed content or lost frontier: %+v", got) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/head_decode.go b/seaweed-block/core/frontend/chunkstore/head_decode.go deleted file mode 100644 index 699259088b..0000000000 --- a/seaweed-block/core/frontend/chunkstore/head_decode.go +++ /dev/null @@ -1,112 +0,0 @@ -package chunkstore - -import ( - "bytes" - "encoding/json" - "fmt" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Only identity/proof fields are shared between persisted representations. -// Format-specific structs deliberately have no field for the other format: -// DisallowUnknownFields rejects even encoding/json's Unicode-folded aliases. -type headIdentityDoc struct { - Format int `json:"format"` - Gen uint64 `json:"gen"` - Epoch uint64 `json:"epoch"` - Holder string `json:"holder"` - RemoteLSN uint64 `json:"remote_lsn"` - State string `json:"state,omitempty"` - DetachedBy *detachedByDoc `json:"detachedBy,omitempty"` -} -type flatHeadDoc struct { - headIdentityDoc - Chunks map[uint64]refDoc `json:"chunks"` -} -type segmentedHeadDoc struct { - headIdentityDoc - Segments map[uint64]legacySegmentRefDoc `json:"segments"` - ChunkBytes uint64 `json:"chunk_bytes"` - ChunkCount int `json:"chunk_count"` -} - -type legacySegmentRefDoc struct { - Key string `json:"key"` - SHA256 [32]byte `json:"sha256"` - Owner string `json:"owner"` - Count int `json:"count"` -} - -type segmentRefV3Doc struct { - legacySegmentRefDoc - MaxBirthLSN *uint64 `json:"max_birth_lsn"` - SegFormat int `json:"seg_format"` -} - -type levelHeadDoc struct { - headIdentityDoc - Levels int `json:"levels"` - Segments map[uint64]segmentRefV3Doc `json:"segments"` - ChunkBytes uint64 `json:"chunk_bytes"` - ChunkCount int `json:"chunk_count"` -} - -func (d headIdentityDoc) document() headDoc { - return headDoc{Format: d.Format, Gen: d.Gen, Epoch: d.Epoch, Holder: d.Holder, RemoteLSN: d.RemoteLSN, State: d.State, DetachedBy: d.DetachedBy} -} - -func decodeFormatHead(content []byte) (headDoc, error) { - var discriminator struct { - Format int `json:"format"` - } - // Preserve duplicate/nesting/byte/trailing-byte checks before selecting the - // schema. Unknown fields are allowed ONLY for this discriminator read. - if err := decodeManifestJSON(content, &discriminator); err != nil { - return headDoc{}, err - } - decoder := json.NewDecoder(bytes.NewReader(content)) - decoder.DisallowUnknownFields() - switch discriminator.Format { - case 1: - var flat flatHeadDoc - if err := decoder.Decode(&flat); err != nil { - return headDoc{}, err - } - doc := flat.headIdentityDoc.document() - doc.Chunks = flat.Chunks - return doc, nil - case 2: - var segmented segmentedHeadDoc - if err := decoder.Decode(&segmented); err != nil { - return headDoc{}, err - } - doc := segmented.headIdentityDoc.document() - doc.Segments = make(map[uint64]storage.ChunkSegment, len(segmented.Segments)) - for group, ref := range segmented.Segments { - doc.Segments[group] = storage.ChunkSegment{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count, SegFormat: 1, MaxBirthLSN: doc.RemoteLSN} - } - doc.ChunkBytes, doc.ChunkCount = segmented.ChunkBytes, segmented.ChunkCount - return doc, nil - case 3: - var root levelHeadDoc - if err := decoder.Decode(&root); err != nil { - return headDoc{}, err - } - if root.Levels != 1 { - return headDoc{}, fmt.Errorf("chunkstore: unsupported levels %d", root.Levels) - } - doc := root.headIdentityDoc.document() - doc.Levels, doc.ChunkBytes, doc.ChunkCount = root.Levels, root.ChunkBytes, root.ChunkCount - doc.Segments = make(map[uint64]storage.ChunkSegment, len(root.Segments)) - for group, ref := range root.Segments { - if ref.MaxBirthLSN == nil || (ref.SegFormat != 1 && ref.SegFormat != 2) || *ref.MaxBirthLSN > root.RemoteLSN { - return headDoc{}, fmt.Errorf("chunkstore: invalid segment version/birth maximum") - } - doc.Segments[group] = storage.ChunkSegment{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count, SegFormat: ref.SegFormat, MaxBirthLSN: *ref.MaxBirthLSN} - } - return doc, nil - default: - return headDoc{}, fmt.Errorf("chunkstore: unsupported HEAD format %d", discriminator.Format) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index fc409a72f7..89a39e53e7 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -14,6 +14,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -23,46 +24,44 @@ import ( // pins it. "GAP" marks a reader that takes an absent HEAD for an empty // one; a change that treats an absent HEAD as unknown flips those probes. var headReaders = map[string]string{ - // chunkstore: the two raw reads every other reader goes through - "core/frontend/chunkstore/catalog.go ReadHead -> LookupEntry": "ok=false, no error (probe ReadHead)", - "core/frontend/chunkstore/chunk_remote.go getHeadRoot -> LookupEntry": "zero HEAD, no error (probe GetHead)", - "core/frontend/chunkstore/catalog.go headExists -> LookupEntry": "false (probe EnsureVolume)", - "core/frontend/chunkstore/chunk_remote.go GetHead -> getHeadRoot": "zero HEAD, no error (probe GetHead)", - "core/frontend/chunkstore/chunk_remote.go GetHeadRoot -> getHeadRoot": "zero HEAD, no error (probe GetHeadRoot)", - "core/frontend/chunkstore/chunk_remote.go CASHead -> getHeadRoot": "GAP: expected gen 0 creates a HEAD over existing keys (probe CASHead)", - "core/frontend/chunkstore/catalog.go ensureInitialHead -> headExists": "GAP: creates an empty gen-1 HEAD over existing keys (probe EnsureVolume)", - "core/frontend/chunkstore/catalog.go EnsureVolume -> ReadHead": "GAP: attaches the recreated empty HEAD (probe EnsureVolume)", - "core/frontend/chunkstore/catalog.go fork -> ReadHead": "replay falls through and publishes the fork-time HEAD (probe ForkReplay)", - "core/frontend/chunkstore/catalog.go AbortFork -> ReadHead": "GAP: exclusive-creates an aborted HEAD (probe AbortFork)", - "core/frontend/chunkstore/gc.go run -> GetHead": "GAP: zero HEAD roots nothing; the volume's keys become candidates (probe GCMark)", - "core/frontend/chunkstore/gc_copy.go SweepCopies -> ReadHead": "after AbortFork: settles from the HEAD it created (probe AbortFork)", - "core/frontend/chunkstore/restore.go MarkIndependent -> ReadHead": "refuses (not a restore / no HEAD) (probe MarkIndependent)", - "core/frontend/chunkstore/share_guard.go beginShare -> ReadHead": "refuses outcome_unknown: the HEAD to share is no longer current", - "core/frontend/chunkstore/usage.go Usage -> ReadHead": "GAP: reports an empty image, no error (probe Usage)", - "core/frontend/chunkstore/verify.go readHead -> LookupEntry": "finding ROOT_INVALID (probe Verify)", - "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: a target without HEAD (never created, or a restore that died between its VOLUME and its HEAD) gets a deleted HEAD written exclusively before the release (probe LayoutOperatorRelease)", - "core/frontend/chunkstore/layout/start.go Start -> ReadHead": "refuses ErrHeadAbsent and creates nothing (probe LayoutStart)", - "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and writes nothing to the objects (probe LayoutRemoval)", - "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", - "core/frontend/chunkstore/verify.go run -> LookupEntry": "finding ROOT_INVALID (probe Verify)", - "core/frontend/chunkstore/volume_delete.go DeleteVolume -> ReadHead": "operator delete writes a deleting HEAD from nothing and completes (probe DeleteVolume)", - "core/frontend/chunkstore/volume_delete.go markHeadDeleting -> ReadHead": "zero HEAD: creates the deleting HEAD (probe DeleteVolume)", - "core/frontend/chunkstore/volume_delete.go commitHeadPurging -> ReadHead": "reads the HEAD markHeadDeleting wrote (probe DeleteVolume)", - "core/frontend/chunkstore/volume_delete.go finishHeadDeleted -> ReadHead": "reads the HEAD markHeadDeleting wrote (probe DeleteVolume)", - "core/frontend/chunkstore/volume_delete.go revertHeadDeleting -> ReadHead": "reads the HEAD markHeadDeleting wrote (probe DeleteVolume)", - "core/frontend/chunkstore/volume_delete.go volumeGone -> ReadHead": "absent HEAD = not gone (probe DeleteVolume)", - // above the chunk store: they read through storage.ChunkRemote GetHead / - // GetHeadRoot, so an absent HEAD reaches them as the zero HEAD (probe GetHead) - "cmd/sw-block/chunk.go chunkShow -> ReadHead": "ok=false: reports no HEAD (probe ReadHead)", - "core/frontend/durable/provider_chunk.go GetHead -> GetHead": "zero HEAD (probe GetHead)", - "core/frontend/durable/provider_chunk.go GetHeadRoot -> GetHead": "zero HEAD (probe GetHead)", - "core/frontend/durable/provider_chunk.go GetHeadRoot -> GetHeadRoot": "zero HEAD (probe GetHeadRoot)", - "core/frontend/durable/provider_chunk.go newChunkLayer -> GetHead": "zero HEAD: a fresh lineage (probe GetHead)", - "core/storage/chunk_head_belt.go confirmChunkHead -> GetHead": "gen mismatch: fenced, HEAD publication displaced (reads the zero HEAD, probe GetHead)", - "core/storage/chunk_head_belt.go confirmChunkHead -> GetHeadRoot": "gen mismatch: fenced, HEAD publication displaced (probe GetHeadRoot)", - "core/storage/chunk_head_belt.go readChunkHead -> GetHead": "zero HEAD (probe GetHead)", - "core/storage/chunk_layer.go attachChunkLayerImpl -> GetHead": "zero HEAD: attaches as a new lineage (probe GetHead)", - "core/storage/chunk_restore.go ClaimChunkHead -> GetHead": "GAP: the zero HEAD passes the fence check (gen 0), the claim then CASes from gen 0 (probe CASHead)", + "core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)", + "core/frontend/durable/provider_layout.go settleLayoutStop -> ReadHead": "absent refuses unknown stop outcome, never resumes (probe TestLayoutStopAbortMustConfirmItsOutcome)", + "core/frontend/durable/provider_layout.go startLayoutRoot -> ReadHead": "the diagnostic re-read after Start refusal cannot turn an absent HEAD into a claim; Start already refused it (probe TestLayoutStoreMissingHEADRefusesStart)", + "cmd/blockvolume/workspace_lease.go workspaceLayoutDetachedGeneration -> ReadHead": "absent refuses ACK (probe TestWorkspaceLayoutDetachedProof)", + "cmd/blockvolume/chunk_remote.go chunkAttachCheck -> ReadHead": "absent refuses attach without creating VOLUME or HEAD (TestChunkAttachCheckAppliesVolumeRules)", + "core/frontend/chunkstore/layout_store.go ReadHead -> DecodeLayoutHeadEntry": "shared canonical entry decoder; no missing HEAD is invented (TestLayoutStoreMissingHEADRefusesStart)", + "core/host/master/workspace_layout_head.go NewLayoutWorkspaceHEADReader -> DecodeLayoutHeadEntry": "any missing/failed metadata refuses; identity comes from master intent (TestWorkspaceLayoutHEADRefusalsAndStates)", + "cmd/blockmaster/layout_create.go layoutHeadReader -> ReadHead": "absent refuses restore before target persistence (TestMasterLayoutHeadReaderRefusesAbsentHead)", + "core/host/volume/chunk_control.go ListSnapshots -> ReadHead": "refuses ErrHeadAbsent without creating HEAD (TestChunkControlUsesTheBoundLayoutIdentity)", + "core/frontend/chunkstore/layout_store.go ReadHead -> LookupEntry": "found=false; Start refuses without writing (probe TestLayoutStoreMissingHEADRefusesStart)", + "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: a target without HEAD (never created, or a restore that died between its VOLUME and its HEAD) gets a deleted HEAD written exclusively before the release (probe LayoutOperatorRelease)", + "core/frontend/chunkstore/layout/start.go Start -> ReadHead": "refuses ErrHeadAbsent and creates nothing (probe LayoutStart)", + "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and writes nothing to the objects (probe LayoutRemoval)", + "core/frontend/chunkstore/layout/snapshots.go RunAddDependent -> ReadHead": "refuses ErrHeadAbsent before reading any root and writes nothing (probe LayoutAddDependent)", + "core/frontend/chunkstore/catalog_b.go DeleteVolume -> ReadHead": "refuses ErrHeadAbsent before any write (probe BCatalog)", + "core/frontend/chunkstore/catalog_b.go ReadHead -> ReadHead": "found=false to the caller, which reports no HEAD (probe BCatalog)", + "core/frontend/chunkstore/retain_b.go Retain -> ReadHead": "refuses ErrHeadAbsent, deletes nothing (probe BCatalog)", + "core/frontend/chunkstore/retain_b.go SetRetention -> ReadHead": "refuses ErrHeadAbsent, writes no policy (probe BCatalog)", + "core/frontend/chunkstore/catalog_b.go Usage -> ReadHead": "refuses ErrHeadAbsent (probe BCatalog)", + "core/frontend/chunkstore/layout_remote.go AbortOpenSession -> ReadHead": "refuses ErrHeadAbsent, aborts nothing (probe LayoutRemote)", + "core/frontend/chunkstore/layout_remote.go CommitPendingSnapshot -> ReadHead": "refuses ErrHeadAbsent, commits nothing (probe LayoutRemote)", + "core/frontend/durable/provider_layout_snapshot.go SnapshotVolume -> ReadHead": "the layout remote's HEAD read: refuses ErrHeadAbsent, names nothing (probe LayoutRemote)", + "core/frontend/chunkstore/layout_remote.go CASHead -> ReadHead": "refuses ErrHeadAbsent, writes nothing (probe LayoutRemote)", + "core/frontend/chunkstore/layout_remote.go ReadHead -> ReadHead": "refuses ErrHeadAbsent (probe LayoutRemote)", + "core/frontend/chunkstore/layout_remote.go rollBackLocked -> ReadHead": "refuses ErrHeadAbsent before any Begin or upload (probe LayoutRemote)", + "core/frontend/chunkstore/layout/create.go createVolume -> ReadHead": "reads HEAD only after its exclusive create found one; absent then refuses ErrIdentity, writes nothing more (probe LayoutCreate)", + "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", + // above the chunk store: they read through the layout remote's GetHead, so an + // absent HEAD reaches them as ErrHeadAbsent, never as a zero HEAD (probe LayoutRemote) + "cmd/sw-block/chunk_b.go chunkShow -> ReadHead": "found=false: prints a null head (probe TestOpsChunk_AbsentVolume)", + "cmd/sw-block/chunk_b.go chunkSnapshots -> ReadHead": "refuses volume_not_found (probe TestOpsChunk_AbsentVolume)", + "core/frontend/durable/provider_chunk.go GetHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", + "core/frontend/durable/provider_chunk.go GetHeadRoot -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", + "core/frontend/durable/provider_chunk.go GetHeadRoot -> GetHeadRoot": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", + "core/storage/chunk_head_belt.go confirmChunkHead -> GetHead": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)", + "core/storage/chunk_head_belt.go confirmChunkHead -> GetHeadRoot": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)", + "core/storage/chunk_head_belt.go readChunkHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", + "core/storage/chunk_layer.go attachChunkLayerImpl -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", } // TestHeadReaders_Enumeration lists every HEAD reader in core/ and cmd/ from @@ -103,12 +102,15 @@ func TestHeadReaders_Enumeration(t *testing.T) { case *ast.Ident: name = x.Name } - hit := name == "ReadHead" || name == "GetHead" || name == "GetHeadRoot" || name == "getHeadRoot" || name == "headExists" + hit := name == "ReadHead" || name == "GetHead" || name == "GetHeadRoot" || name == "getHeadRoot" || name == "headExists" || name == "DecodeLayoutHeadEntry" if name == "LookupEntry" { for _, a := range call.Args { if id, ok := a.(*ast.Ident); ok && id.Name == "headName" { hit = true } + if sel, ok := a.(*ast.SelectorExpr); ok && sel.Sel.Name == "HeadName" { + hit = true // layout.HeadName + } } } if hit { @@ -141,123 +143,10 @@ func TestHeadReaders_Enumeration(t *testing.T) { } } -// absentHeadFixture: volume v1 is live (VOLUME), holds a bound key, and its -// HEAD entry was removed (pruned by a stock tool, or by hand). -func absentHeadFixture(t *testing.T) (*fakeFiler, gcBlobs, *Catalog, *Collector, *time.Time, *ChunkRemote) { - t.Helper() - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, err := NewChunkRemote(f, b, catBase+"/v1") - if err != nil { - t.Fatal(err) - } - if err := r.Put(ctx, "chunks/e1/c0/k", []byte("published data")); err != nil { - t.Fatal(err) - } - if err := f.DeleteEntry(ctx, catBase+"/v1", headName, nil); err != nil { - t.Fatal(err) - } - return f, b, c, g, now, r -} - -// headReaderForkFixture: v1 holds a snapshot s1; v2 is a directory a fork -// can target. -func headReaderForkFixture(t *testing.T) (*fakeFiler, *fakeBlobs) { - t.Helper() - f, b, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h); err != nil { - t.Fatal(err) - } - return f, b -} - // TestHeadReaders_AbsentHeadProbes pins, per reader, what today's code does // when HEAD is absent (see headReaders). func TestHeadReaders_AbsentHeadProbes(t *testing.T) { ctx := context.Background() - t.Run("ReadHead", func(t *testing.T) { - _, _, c, _, _, _ := absentHeadFixture(t) - if h, ok, err := c.ReadHead(ctx, "v1"); err != nil || ok || h.Gen != 0 { - t.Fatalf("ReadHead: %+v %t %v; want absent, no error", h, ok, err) - } - }) - t.Run("GetHead", func(t *testing.T) { - _, _, _, _, _, r := absentHeadFixture(t) - if h, err := r.GetHead(ctx); err != nil || h.Gen != 0 { - t.Fatalf("GetHead: %+v %v; want the zero HEAD", h, err) - } - }) - t.Run("GetHeadRoot", func(t *testing.T) { - _, _, _, _, _, r := absentHeadFixture(t) - if h, err := r.GetHeadRoot(ctx); err != nil || h.Gen != 0 { - t.Fatalf("GetHeadRoot: %+v %v; want the zero HEAD", h, err) - } - }) - t.Run("CASHead", func(t *testing.T) { // GAP - _, _, _, _, _, r := absentHeadFixture(t) - gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "h", Chunks: map[uint64]storage.ChunkRef{}}) - if err != nil || gen != 1 { - t.Fatalf("CASHead from gen 0 over keys: %d %v; today it creates gen 1", gen, err) - } - }) - t.Run("EnsureVolume", func(t *testing.T) { // GAP - _, _, c, _, _, _ := absentHeadFixture(t) - if _, err := c.EnsureVolume(ctx, "v1", catGeo); err != nil { - t.Fatalf("attach over keys without HEAD: %v; today it attaches", err) - } - if h, ok, _ := c.ReadHead(ctx, "v1"); !ok || h.Gen != 1 || len(h.Chunks) != 0 { - t.Fatalf("HEAD after attach: %+v %t; today an empty gen-1 HEAD", h, ok) - } - }) - t.Run("Usage", func(t *testing.T) { // GAP - _, _, c, _, _, _ := absentHeadFixture(t) - u, err := c.Usage(ctx, "v1") - if err != nil || u.LiveChunks != 0 { - t.Fatalf("Usage: %+v %v; today an empty image", u, err) - } - }) - t.Run("GCMark", func(t *testing.T) { // GAP - _, _, _, g, now, _ := absentHeadFixture(t) - if _, err := g.Run(ctx); err != nil { - t.Fatal(err) - } - *now = now.Add(2*time.Hour + g.cfg.ClockSkew) - res, err := g.Run(ctx) - if err != nil || res.Candidates == 0 { - t.Fatalf("GC over an absent HEAD: %+v %v; today the volume's keys are candidates", res, err) - } - }) - t.Run("Verify", func(t *testing.T) { - _, _, c, _, _, _ := absentHeadFixture(t) - res, err := c.Verify(ctx, "v1", VerifyOptions{}) - if err != nil || res.FindingsByClass[FindingRootInvalid] == 0 { - t.Fatalf("Verify: %+v %v; want a ROOT_INVALID finding", res, err) - } - }) - t.Run("MarkIndependent", func(t *testing.T) { - _, _, c, _, _, _ := absentHeadFixture(t) - if _, err := c.MarkIndependent(ctx, "v1"); err == nil { - t.Fatal("MarkIndependent of a volume without HEAD succeeded") - } - }) - t.Run("DeleteVolume", func(t *testing.T) { - _, _, c, _, _, _ := absentHeadFixture(t) - res, err := c.DeleteVolume(ctx, "v1", nil) - if err != nil || !res.Completed { - t.Fatalf("operator delete over an absent HEAD: %+v %v; today it completes", res, err) - } - if h, ok, _ := c.ReadHead(ctx, "v1"); !ok || h.State != storage.ChunkHeadDeleted { - t.Fatalf("HEAD after the delete: %+v %t; want deleted", h, ok) - } - }) - t.Run("AbortFork", func(t *testing.T) { // GAP - _, _, c, _, _, _ := absentHeadFixture(t) - claimed, err := c.AbortFork(ctx, "v1") - if err != nil || !claimed { - t.Fatalf("AbortFork over an absent HEAD: %t %v; today it creates an aborted HEAD", claimed, err) - } - }) t.Run("LayoutTransition", func(t *testing.T) { st := &absentLayoutHead{} if _, err := layout.RunBegin(ctx, st, layout.HolderID{Epoch: 1, Holder: "h"}, "s"); !errors.Is(err, layout.ErrHeadAbsent) { @@ -267,6 +156,72 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { t.Fatalf("layout transition over an absent HEAD wrote %d times", st.updates) } }) + t.Run("LayoutAddDependent", func(t *testing.T) { + r, err := layout.NewReader("/swblock/chunks", "v1", func(context.Context, string) ([]byte, bool, error) { return nil, false, nil }) + if err != nil { + t.Fatal(err) + } + st := &absentLayoutHead{} + if _, err := layout.RunAddDependent(ctx, st, r, "daily", layout.Dependent{Target: "t", TargetID: layout.VolumeID{1}}); !errors.Is(err, layout.ErrHeadAbsent) || st.updates != 0 { + t.Fatalf("add dependent over an absent HEAD: %v (%d writes); want ErrHeadAbsent and none", err, st.updates) + } + }) + t.Run("BCatalog", func(t *testing.T) { + f := newFakeFiler() + c, err := NewBCatalog(f, newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + v := VolumeRef{Name: "v", ID: layout.VolumeID{1}} + if _, found, err := c.ReadHead(ctx, v); found || err != nil { + t.Fatalf("catalog read of an absent HEAD: found %t, %v", found, err) + } + if _, err := c.Usage(ctx, v); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("usage of an absent HEAD: %v; want ErrHeadAbsent", err) + } + if _, err := c.Retain(ctx, v, time.Now(), false); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("retain of an absent HEAD: %v; want ErrHeadAbsent", err) + } + if err := c.SetRetention(ctx, v, retain.DefaultPolicy()); !errors.Is(err, layout.ErrHeadAbsent) || len(f.written) != 0 { + t.Fatalf("policy of an absent HEAD: %v (%d writes); want ErrHeadAbsent and none", err, len(f.written)) + } + if err := c.DeleteVolume(ctx, v, okDeleteAuthority{}); !errors.Is(err, layout.ErrHeadAbsent) || len(f.written) != 0 { + t.Fatalf("delete of an absent HEAD: %v (%d writes); want ErrHeadAbsent and none", err, len(f.written)) + } + }) + t.Run("LayoutRemote", func(t *testing.T) { + f := newFakeFiler() + c, err := NewBCatalog(f, newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + r, err := NewLayoutRemote(c, VolumeRef{Name: "v", ID: layout.VolumeID{1}}, layout.HolderID{Epoch: 1, Holder: "a", ClaimID: "k"}) + if err != nil { + t.Fatal(err) + } + r.SetSnapshot("x", layout.SnapshotMeta{}) + if err := r.CommitPendingSnapshot(ctx); !errors.Is(err, layout.ErrHeadAbsent) || len(f.written) != 0 { + t.Fatalf("naming over an absent HEAD: %v (%d writes); want ErrHeadAbsent and none", err, len(f.written)) + } + if _, err := r.AbortOpenSession(ctx); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("settling a stop over an absent HEAD: %v; want ErrHeadAbsent", err) + } + if _, err := r.ReadHead(ctx); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("kernel HEAD read of an absent HEAD: %v; want ErrHeadAbsent", err) + } + if _, err := r.GetHead(ctx); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("engine HEAD read of an absent HEAD: %v; want ErrHeadAbsent", err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 0, Epoch: 1}, storage.ChunkHead{Epoch: 1}); !errors.Is(err, layout.ErrHeadAbsent) || len(f.written) != 0 { + t.Fatalf("engine commit over an absent HEAD: %v (%d writes); want ErrHeadAbsent and none", err, len(f.written)) + } + }) + t.Run("LayoutCreate", func(t *testing.T) { + st := &existsButAbsent{} + if _, err := layout.CreateVolume(ctx, st, layout.Volume{ID: layout.VolumeID{1}, Name: "v", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("create whose HEAD create found one that then reads absent: %v; want ErrIdentity", err) + } + }) t.Run("LayoutRemoval", func(t *testing.T) { r, err := layout.NewReader("/swblock/chunks", "v1", func(context.Context, string) ([]byte, bool, error) { return nil, false, nil }) if err != nil { @@ -285,7 +240,7 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { if err != nil { t.Fatal(err) } - vb, err := layout.Volume{ID: tid, Name: "t", Format: layout.VolumeFormat}.Encode() + vb, err := layout.Volume{ID: tid, Name: "t", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}.Encode() if err != nil { t.Fatal(err) } @@ -311,30 +266,10 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { }) t.Run("LayoutStart", func(t *testing.T) { st := &absentLayoutHead{} - if _, err := layout.Start(ctx, st, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "h"}, layout.LocalRoot{ClaimID: "k", Fresh: true}); !errors.Is(err, layout.ErrHeadAbsent) || st.updates != 0 { + if _, err := layout.Start(ctx, st, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "h"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); !errors.Is(err, layout.ErrHeadAbsent) || st.updates != 0 { t.Fatalf("start over an absent HEAD: %v, %d writes; want ErrHeadAbsent and none", err, st.updates) } }) - t.Run("ForkReplay", func(t *testing.T) { - f, b := headReaderForkFixture(t) - c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) - if err != nil { - t.Fatal(err) - } - req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f1"} - if _, err := c.Fork(ctx, req); err != nil { - t.Fatal(err) - } - if err := f.DeleteEntry(ctx, catBase+"/v2", headName, nil); err != nil { - t.Fatal(err) - } - if _, err := c.Fork(ctx, req); err != nil { - t.Fatalf("fork replay over an absent target HEAD: %v; today it republishes", err) - } - if h, ok, _ := c.ReadHead(ctx, "v2"); !ok || h.Gen != 1 { - t.Fatalf("target HEAD after the replay: %+v %t; today the fork-time HEAD again", h, ok) - } - }) } // absentLayoutHead is a layout HEAD store whose HEAD is absent; it records @@ -397,3 +332,20 @@ func (p *presentLayoutHead) UpdateHead(context.Context, uint64, layout.Head) err type okClaimLease struct{} func (okClaimLease) OldLeaseEnded(context.Context, uint64) error { return nil } + +// existsButAbsent: VOLUME is created; the HEAD create reports one exists, +// yet HEAD then reads absent (removed in between). +type existsButAbsent struct{} + +func (existsButAbsent) ReadHead(context.Context) (layout.Head, bool, error) { + return layout.Head{}, false, nil +} +func (existsButAbsent) CreateHead(context.Context, layout.Head) error { return layout.ErrExists } +func (existsButAbsent) CreateVolumeRecord(context.Context, layout.Volume) error { return nil } +func (existsButAbsent) ReadVolumeRecord(context.Context) (layout.Volume, bool, error) { + return layout.Volume{}, false, nil +} + +func (s *absentLayoutHead) ReadVolumeRecord(context.Context) (layout.Volume, bool, error) { + return layout.Volume{}, false, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/interrupt_every_step_test.go b/seaweed-block/core/frontend/chunkstore/interrupt_every_step_test.go deleted file mode 100644 index 3dc70647bd..0000000000 --- a/seaweed-block/core/frontend/chunkstore/interrupt_every_step_test.go +++ /dev/null @@ -1,268 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "fmt" - "path" - "sync" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// writeTrace records every filer write (create, update, delete) a command -// makes, in order: the command's step boundaries. -type writeTrace struct { - manifestFilerBlobs - mu sync.Mutex - writes []string -} - -func (w *writeTrace) note(op, p string) { - w.mu.Lock() - defer w.mu.Unlock() - w.writes = append(w.writes, op+" "+p) -} - -func (w *writeTrace) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, o bool) error { - w.note("create", path.Join(dir, e.GetName())) - return w.manifestFilerBlobs.CreateEntry(ctx, dir, e, o) -} - -func (w *writeTrace) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, x map[string][]byte) error { - w.note("update", path.Join(dir, e.GetName())) - return w.manifestFilerBlobs.UpdateEntry(ctx, dir, e, x) -} - -func (w *writeTrace) DeleteEntry(ctx context.Context, dir, name string, x map[string][]byte) error { - w.note("delete", path.Join(dir, name)) - return w.manifestFilerBlobs.DeleteEntry(ctx, dir, name, x) -} - -// nthWrite matches the n-th filer write (1-based) of any kind. -func nthWrite(n int) func(op, p string) bool { - seen := 0 - return func(op, _ string) bool { - if op != "create" && op != "update" && op != "delete" { - return false - } - seen++ - return seen == n - } -} - -// interruptCase is one multi-step operator command: a fresh store, the -// command (with a fixed request id), and the end state it must reach. -type interruptCase struct { - name string - setup func(t *testing.T) (*fakeFiler, *fakeBlobs) - run func(ctx context.Context, c *Catalog) error - check func(t *testing.T, c *Catalog, f *fakeFiler, b *fakeBlobs) -} - -// interruptAtEveryStep runs tc once to enumerate its filer writes, then for -// every write kills the command at it (before it reaches the filer, and -// after it applied with its reply lost), restarts the catalog, re-runs the -// command with the same request id, and checks the end state. A step added -// to the command is covered without editing the test. -func interruptAtEveryStep(t *testing.T, tc interruptCase) { - t.Helper() - ctx := context.Background() - f, b := tc.setup(t) - trace := &writeTrace{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}} - c, err := NewCatalog(trace, catBase) - if err != nil { - t.Fatal(err) - } - if err := tc.run(ctx, c); err != nil { - t.Fatalf("%s, uninterrupted: %v", tc.name, err) - } - tc.check(t, c, f, b) - steps := append([]string(nil), trace.writes...) - if len(steps) == 0 { - t.Fatalf("%s made no filer write", tc.name) - } - t.Logf("%s: %d step boundaries: %v", tc.name, len(steps), steps) - for k := range steps { - for _, after := range []bool{false, true} { - name := fmt.Sprintf("%s/step%d %s/%s", tc.name, k+1, steps[k], map[bool]string{false: "before", true: "applied-reply-lost"}[after]) - t.Run(name, func(t *testing.T) { - f, b := tc.setup(t) - crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: after, match: nthWrite(k + 1)} - dying, err := NewCatalog(crashed, catBase) - if err != nil { - t.Fatal(err) - } - _ = tc.run(ctx, dying) - crashed.mu.Lock() - died := crashed.dead - crashed.mu.Unlock() - if !died { - t.Fatalf("the command never reached step %d", k+1) - } - c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) // the restarted process - if err != nil { - t.Fatal(err) - } - if err := tc.run(ctx, c); err != nil { - t.Fatalf("re-run after a kill at step %d: %v", k+1, err) - } - tc.check(t, c, f, b) - if err := tc.run(ctx, c); err != nil { // and a further re-run replays - t.Fatalf("second re-run: %v", err) - } - tc.check(t, c, f, b) - }) - } - } -} - -// forkSourceFixture: v1 holds chunks 0 and 3 and a snapshot s1 of them. -func forkSourceFixture(t *testing.T) (*fakeFiler, *fakeBlobs) { - t.Helper() - f, b, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h); err != nil { - t.Fatal(err) - } - for _, v := range []string{"v1", "v2", "v3"} { // the volume directories GC lists - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: v, IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - } - return f, b -} - -// requireImage checks vol's HEAD names exactly chunks 0 and 3 of the -// fixture and each reads back its bytes. -func requireImage(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) { - t.Helper() - ctx := context.Background() - r, err := NewChunkRemote(f, b, path.Join(catBase, vol)) - if err != nil { - t.Fatal(err) - } - h, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - want := map[uint64][]byte{0: chunkBytes(0x10), 3: chunkBytes(0x13)} - if len(h.Chunks) != len(want) { - t.Fatalf("%s HEAD names %d chunks; want %d", vol, len(h.Chunks), len(want)) - } - for idx, data := range want { - ref, ok := h.Chunks[idx] - if !ok { - t.Fatalf("%s HEAD lacks chunk %d", vol, idx) - } - got, err := r.Get(ctx, ref.Key) - if err != nil || !bytes.Equal(got, data) { - t.Fatalf("%s chunk %d: %d bytes, %v", vol, idx, len(got), err) - } - } -} - -// requireCopyIntentsSettle: a killed attempt's copy intent may outlive the -// replay (the replaying attempt cannot know the dead one's create will not -// still land); every intent left is this request's copy intent, and GC's -// copy sweep past the deadline settles all of them from the HEAD it reads, -// the image intact. -func requireCopyIntentsSettle(t *testing.T, c *Catalog, f *fakeFiler, b *fakeBlobs, vol, holder string) { - t.Helper() - ctx := context.Background() - r, err := NewChunkRemote(f, b, path.Join(catBase, vol)) - if err != nil { - t.Fatal(err) - } - left, err := r.ListIntents(ctx) - if err != nil { - t.Fatal(err) - } - for _, in := range left { - if in.Holder != holder { - t.Fatalf("%s intent %s held by %q; want only %q", vol, in.ID, in.Holder, holder) - } - } - later := time.Now().Add(DefaultOpDeadline + time.Hour) - g, err := NewCollector(c, gcBlobs{b}, GCConfig{Grace: time.Hour, IntentTTL: time.Hour, Now: func() time.Time { return later }, IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) - if err != nil { - t.Fatal(err) - } - if _, err := g.SweepCopies(ctx); err != nil { - t.Fatalf("copy sweep: %v", err) - } - if in, err := r.ListIntents(ctx); err != nil || len(in) != 0 { - t.Fatalf("%s intents after the copy sweep: %d %v; want none", vol, len(in), err) - } - requireImage(t, f, b, vol) -} - -// r2.149 (3): volume delete, fork and restore, each killed at every step -// boundary and re-run with the same request id, reach their end state with -// their data. -func TestInterruptAtEveryStep_VolumeDelete(t *testing.T) { - var rsv *fakeReservation - interruptAtEveryStep(t, interruptCase{ - name: "volume-delete", - setup: func(t *testing.T) (*fakeFiler, *fakeBlobs) { - f, b, _, _ := deleteFixture(t) - detachHead(t, f, b, "v1") - rsv = &fakeReservation{} - return f, b - }, - run: func(ctx context.Context, c *Catalog) error { - res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) - if err == nil && !res.Completed { - return fmt.Errorf("not completed: %+v", res) - } - return err - }, - check: func(t *testing.T, c *Catalog, _ *fakeFiler, _ *fakeBlobs) { - requireVolumeDeleted(t, c, rsv, "v1") - }, - }) -} - -func TestInterruptAtEveryStep_Fork(t *testing.T) { - interruptAtEveryStep(t, interruptCase{ - name: "fork", - setup: forkSourceFixture, - run: func(ctx context.Context, c *Catalog) error { - _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f1"}) - return err - }, - check: func(t *testing.T, c *Catalog, f *fakeFiler, b *fakeBlobs) { - v, ok, err := c.ReadVolume(context.Background(), "v2") - if err != nil || !ok || v.Origin != OriginFork { - t.Fatalf("fork VOLUME: %+v %t %v", v, ok, err) - } - if h, ok, err := c.ReadHead(context.Background(), "v2"); err != nil || !ok || h.State != storage.ChunkHeadActive { - t.Fatalf("fork HEAD: %+v %t %v", h, ok, err) - } - requireImage(t, f, b, "v2") - requireCopyIntentsSettle(t, c, f, b, "v2", "fork:v2/f1") - }, - }) -} - -func TestInterruptAtEveryStep_Restore(t *testing.T) { - interruptAtEveryStep(t, interruptCase{ - name: "restore", - setup: forkSourceFixture, - run: func(ctx context.Context, c *Catalog) error { - _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "r1"}) - return err - }, - check: func(t *testing.T, c *Catalog, f *fakeFiler, b *fakeBlobs) { - v, ok, err := c.ReadVolume(context.Background(), "v3") - if err != nil || !ok || v.Origin != OriginRestore { - t.Fatalf("restore VOLUME: %+v %t %v", v, ok, err) - } - requireImage(t, f, b, "v3") - requireCopyIntentsSettle(t, c, f, b, "v3", "fork:v3/r1") - }, - }) -} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go index ca432b9d97..797adbc682 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -15,6 +15,10 @@ var ( // ErrStaleBase: the previous manifest given is not HEAD's current // root, so what is new cannot be told. ErrStaleBase = errors.New("layout: previous manifest is not HEAD's current root") + // ErrPositionBehind: a commit's position is below HEAD's. HEAD's position + // only rises (an equal one names an unchanged image); a lower commit + // has no legitimate source, so it is fenced, never retried. + ErrPositionBehind = errors.New("layout: commit position below HEAD's") // ErrSnapshotExists: the snapshot name is taken by another root. ErrSnapshotExists = errors.New("layout: snapshot name taken") // ErrTooManySnapshots: HEAD already holds MaxSnapshots. @@ -33,8 +37,9 @@ type CommitRequest struct { Prev map[uint64]Ref Next map[uint64]Ref Position uint64 - Snapshot string // "" = no named snapshot - State string // StateLive, or StateDetached for the final synced image + Snapshot string // "" = no named snapshot + Meta SnapshotMeta // the new snapshot's retention facts + State string // StateLive, or StateDetached for the final synced image } // rootOf names the root of a manifest. @@ -67,7 +72,7 @@ func newOwn(vol string, prev, next map[uint64]Ref) map[uint64]Ref { // A live HEAD that already shows this commit // applied (idle, current = root, position, the snapshot) is a replay: // unchanged, changed=false. -func (h Head) Commit(me HolderID, session string, root RootName, position uint64, snapshot, state string) (next Head, changed bool, err error) { +func (h Head) Commit(me HolderID, session string, root RootName, position uint64, snapshot string, meta SnapshotMeta, state string) (next Head, changed bool, err error) { if session == "" { return Head{}, false, errors.New("layout: Commit needs a session id") } @@ -78,27 +83,43 @@ func (h Head) Commit(me HolderID, session string, root RootName, position uint64 return Head{}, false, fmt.Errorf("%w: invalid commit state %q", ErrMalformed, state) } if h.State == state && h.Activity.Kind == ActIdle && h.Current != nil && *h.Current == root && h.Position == position { - if s, ok := h.Snapshots[snapshot]; snapshot == "" || ok && s.Root == root { + if s, ok := h.Snapshots[snapshot]; snapshot == "" || ok && s.Root == root && s.Position == position { return h, false, nil } } if h.Activity != (Activity{Kind: ActSnap, Session: session}) { return Head{}, false, fmt.Errorf("%w: HEAD has %s(%s), not snap(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, session) } + // The position is produced here: never one with no room for a next + // LSN (a HEAD already there keeps it, e.g. to stop). + if position == ^uint64(0) && position != h.Position { + return Head{}, false, fmt.Errorf("%w: commit at %d", ErrNoNextPosition, position) + } + if position < h.Position { + return Head{}, false, fmt.Errorf("%w: commit at %d, HEAD at %d", ErrPositionBehind, position, h.Position) + } next = h.clone() if snapshot != "" { if s, ok := next.Snapshots[snapshot]; ok { - if s.Root != root { + // the same name at another root or another position is another + // commit's snapshot, never this one's replay + if s.Root != root || s.Position != position { return Head{}, false, fmt.Errorf("%w: %q", ErrSnapshotExists, snapshot) } } else { if len(next.Snapshots) >= MaxSnapshots { - return Head{}, false, fmt.Errorf("%w: %d", ErrTooManySnapshots, MaxSnapshots) + return Head{}, false, fmt.Errorf("%w: at most %d per volume; delete a snapshot, or let retention prune", ErrTooManySnapshots, MaxSnapshots) } if next.Snapshots == nil { next.Snapshots = map[string]Snapshot{} } - next.Snapshots[snapshot] = Snapshot{Root: root} + if len(snapshot) > MaxSnapshotNameBytes { + return Head{}, false, fmt.Errorf("%w: snapshot name %q is %d bytes, at most %d", ErrMalformed, snapshot, len(snapshot), MaxSnapshotNameBytes) + } + if err := meta.check(snapshot); err != nil { + return Head{}, false, err + } + next.Snapshots[snapshot] = Snapshot{Root: root, Position: position, Meta: meta.clone()} } } rn := root @@ -124,7 +145,7 @@ func RunCommit(ctx context.Context, st HeadStore, os ObjectStore, vol string, me return Head{}, err } return runTransition(ctx, st, func(h Head) (Head, bool, error) { - if next, changed, err := h.Commit(me, req.Session, root, req.Position, req.Snapshot, req.State); err != nil || !changed { + if next, changed, err := h.Commit(me, req.Session, root, req.Position, req.Snapshot, req.Meta, req.State); err != nil || !changed { return next, changed, err // refused, or already applied: no lookups } // The base is HEAD's current root. Before any commit there is none @@ -172,6 +193,17 @@ func RunCommit(ctx context.Context, st HeadStore, os ObjectStore, vol string, me return Head{}, false, fmt.Errorf("%w: %s (absent, written by another session, or marked)", ErrNotPrepared, rel) } } - return h.Commit(me, req.Session, root, req.Position, req.Snapshot, req.State) + return h.Commit(me, req.Session, root, req.Position, req.Snapshot, req.Meta, req.State) }) } + +func (m SnapshotMeta) clone() SnapshotMeta { + if m.Labels != nil { + l := make(map[string]string, len(m.Labels)) + for k, v := range m.Labels { + l[k] = v + } + m.Labels = l + } + return m +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit_monotonic_test.go b/seaweed-block/core/frontend/chunkstore/layout/commit_monotonic_test.go new file mode 100644 index 0000000000..3d29cee175 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/commit_monotonic_test.go @@ -0,0 +1,37 @@ +package layout + +import ( + "errors" + "testing" +) + +// HEAD's position only rises: a commit at 10, then a commit at 9 is +// refused (ErrPositionBehind) and HEAD is unchanged; a commit at 10 again +// (an unchanged image) is legal. A HEAD naming a snapshot past its own +// position is malformed. +func TestCommit_PositionIsMonotonic(t *testing.T) { + rn := RootName{Hash: Sum([]byte("new"))} + base := snapHead("s1").Position // positions below are relative to the fixture's + at10, _, err := snapHead("s1").Commit(me, "s1", rn, base+10, "", SnapshotMeta{}, StateLive) + if err != nil || at10.Position != base+10 { + t.Fatalf("commit at 10: %+v %v", at10, err) + } + reopened := at10.clone() + reopened.Activity = Activity{Kind: ActSnap, Session: "s2"} + other := RootName{Hash: Sum([]byte("older"))} + if got, _, err := reopened.Commit(me, "s2", other, base+9, "", SnapshotMeta{}, StateLive); !errors.Is(err, ErrPositionBehind) { + t.Fatalf("commit at 9 over HEAD at 10: %+v %v; want ErrPositionBehind", got, err) + } + if reopened.Position != base+10 || *reopened.Current != rn { + t.Fatalf("HEAD changed by the refused commit: %+v", reopened) + } + if got, changed, err := reopened.Commit(me, "s2", rn, base+10, "same", SnapshotMeta{}, StateLive); err != nil || !changed || got.Snapshots["same"].Position != base+10 { + t.Fatalf("a named snapshot of the unchanged image at 10: %+v %t %v", got, changed, err) + } + + bad := at10.clone() + bad.Snapshots["future"] = Snapshot{Root: rn, Position: base + 11} + if _, err := bad.Encode(); !errors.Is(err, ErrMalformed) { + t.Fatalf("HEAD at 10 naming a snapshot at 11: %v; want ErrMalformed", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit_snapshot_position_test.go b/seaweed-block/core/frontend/chunkstore/layout/commit_snapshot_position_test.go new file mode 100644 index 0000000000..afdba9380e --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/commit_snapshot_position_test.go @@ -0,0 +1,28 @@ +package layout + +import ( + "errors" + "testing" +) + +// A snapshot is named by one commit: its root and its position. A commit +// repeating the name at the same root but another position is not that +// commit's replay; it is refused, and HEAD keeps the recorded position. +func TestCommit_SnapshotNameAtAnotherPositionIsAnotherCommit(t *testing.T) { + rn := RootName{Hash: Sum([]byte("new"))} + next, _, err := snapHead("s1").Commit(me, "s1", rn, 50, "hourly", SnapshotMeta{}, StateLive) + if err != nil || next.Snapshots["hourly"].Position != 50 { + t.Fatalf("Commit: %+v %v", next.Snapshots["hourly"], err) + } + if _, changed, err := next.Commit(me, "s1", rn, 50, "hourly", SnapshotMeta{}, StateLive); err != nil || changed { + t.Fatalf("same name, root and position: %t %v; want a replay", changed, err) + } + reopened := next.clone() + reopened.Activity = Activity{Kind: ActSnap, Session: "s2"} + if _, _, err := reopened.Commit(me, "s2", rn, 60, "hourly", SnapshotMeta{}, StateLive); !errors.Is(err, ErrSnapshotExists) { + t.Fatalf("same name and root at position 60: %v; want ErrSnapshotExists", err) + } + if _, changed, err := next.Commit(me, "s1", rn, 50, "hourly", SnapshotMeta{}, StateLive); err != nil || changed { + t.Fatalf("after the refusal: %t %v", changed, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go index fdea6af3b6..875f97dede 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go @@ -46,7 +46,7 @@ func manifest(entries ...Ref) map[uint64]Ref { func TestCommit_Closure(t *testing.T) { rn := RootName{Hash: Sum([]byte("new"))} h := snapHead("s1") - next, changed, err := h.Commit(me, "s1", rn, 50, "hourly", StateLive) + next, changed, err := h.Commit(me, "s1", rn, 50, "hourly", SnapshotMeta{}, StateLive) if err != nil || !changed || next.Activity.Kind != ActIdle || *next.Current != rn || next.Position != 50 || next.Snapshots["hourly"].Root != rn { t.Fatalf("Commit: %+v %t %v", next, changed, err) } @@ -56,10 +56,10 @@ func TestCommit_Closure(t *testing.T) { if h.Activity.Kind != ActSnap || h.Snapshots["hourly"].Root == rn { t.Fatal("Commit changed its receiver") } - if again, changed, err := next.Commit(me, "s1", rn, 50, "hourly", StateLive); err != nil || changed || again.Gen != next.Gen { + if again, changed, err := next.Commit(me, "s1", rn, 50, "hourly", SnapshotMeta{}, StateLive); err != nil || changed || again.Gen != next.Gen { t.Fatalf("Commit over its applied HEAD: %+v %t %v; want a replay", again, changed, err) } - if n2, changed, err := h.Commit(me, "s1", rn, 50, "", StateLive); err != nil || !changed || len(n2.Snapshots) != 1 { + if n2, changed, err := h.Commit(me, "s1", rn, 50, "", SnapshotMeta{}, StateLive); err != nil || !changed || len(n2.Snapshots) != 1 { t.Fatalf("Commit without a snapshot name: %+v %t %v", n2, changed, err) } full := snapHead("s1") @@ -80,7 +80,7 @@ func TestCommit_Closure(t *testing.T) { "name taken": {h, me, "daily", ErrSnapshotExists}, "snapshot limit": {full, me, "one-more", ErrTooManySnapshots}, } { - if _, _, err := tc.h.Commit(tc.me, "s1", rn, 50, tc.snapshot, StateLive); !errors.Is(err, tc.want) { + if _, _, err := tc.h.Commit(tc.me, "s1", rn, 50, tc.snapshot, SnapshotMeta{}, StateLive); !errors.Is(err, tc.want) { t.Errorf("%s: %v; want %v", name, err, tc.want) } } diff --git a/seaweed-block/core/frontend/chunkstore/layout/create.go b/seaweed-block/core/frontend/chunkstore/layout/create.go new file mode 100644 index 0000000000..8a225e7f7f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/create.go @@ -0,0 +1,123 @@ +package layout + +import ( + "context" + "errors" + "fmt" +) + +// NewVolumeStore is a new volume's never-reused directory as its creator +// sees it: exclusive creates of the VOLUME record and of the first HEAD +// (ErrExists if the entry is already there), and their reads. +type NewVolumeStore interface { + ReadHead(ctx context.Context) (h Head, found bool, err error) + CreateHead(ctx context.Context, h Head) error + ReadVolumeRecord(ctx context.Context) (v Volume, found bool, err error) + CreateVolumeRecord(ctx context.Context, v Volume) error +} + +// Unclaimed is the first HEAD of a volume: its id, epoch 0, no holder, no +// claim id, idle, live, position 0, and current (nil for a new volume, the +// copied root for a restore target). The first Start claims it from a +// fresh root. +func Unclaimed(id VolumeID, current *RootName) Head { + return Head{VolumeID: id, Activity: Activity{Kind: ActIdle}, Current: current} +} + +// CreateVolume creates a volume in its directory: the VOLUME record, then +// the unclaimed HEAD, each exclusively. A re-run after a crash between them +// finds VOLUME of the same id and writes the HEAD; an existing HEAD of the +// same id means it is done. Another id in either entry is ErrIdentity. +func CreateVolume(ctx context.Context, st NewVolumeStore, v Volume) (Head, error) { + return createVolume(ctx, st, v, nil) +} + +// CreateTarget creates a restore target from the source's named snapshot, +// in this order: the target is recorded as a dependent of that snapshot +// (RunAddDependent, which refuses a snapshot naming another volume's +// chunks), the snapshot's segments and root are written into the target's +// directory (copy), then the target's VOLUME, then its unclaimed HEAD with +// current = that root. Its HEAD is never written before the dependent: an +// operator's release of a target without HEAD writes the deleted HEAD +// first, and the target's HEAD create then fails. +func CreateTarget(ctx context.Context, src StartStore, srcReader *Reader, snapshot string, st NewVolumeStore, v Volume, copy func(ctx context.Context, root RootName) error) (Head, error) { + if copy == nil { + return Head{}, errors.New("layout: CreateTarget needs a copy of the snapshot's root") + } + source, found, err := src.ReadVolumeRecord(ctx) + if err != nil { + return Head{}, err + } + if !found { + return Head{}, ErrMissing + } + if err := source.Geometry.Check(); err != nil { + return Head{}, err + } + if v.Geometry != source.Geometry { + return Head{}, ErrGeometryMismatch + } + sh, err := RunAddDependent(ctx, src, srcReader, snapshot, Dependent{Target: v.Name, TargetID: v.ID}) + if err != nil { + return Head{}, err + } + root := sh.Snapshots[snapshot].Root + if err := copy(ctx, root); err != nil { + return Head{}, fmt.Errorf("layout: copy %s: %w", root, err) + } + return createVolume(ctx, st, v, &root) +} + +func createVolume(ctx context.Context, st NewVolumeStore, v Volume, current *RootName) (Head, error) { + if st == nil { + return Head{}, errors.New("layout: create needs the volume's store") + } + if _, err := v.Encode(); err != nil { + return Head{}, err + } + if err := st.CreateVolumeRecord(ctx, v); err != nil { + if !errors.Is(err, ErrExists) { + return Head{}, err + } + got, found, rerr := st.ReadVolumeRecord(ctx) + if rerr != nil { + return Head{}, rerr + } + if !found || got.ID != v.ID { + return Head{}, fmt.Errorf("%w: VOLUME holds %s, not %s", ErrIdentity, got.ID, v.ID) + } + if got.Geometry != v.Geometry { + return Head{}, ErrGeometryMismatch + } + + } + h := Unclaimed(v.ID, current) + if err := h.check(); err != nil { + return Head{}, err + } + if err := st.CreateHead(ctx, h); err != nil { + if !errors.Is(err, ErrExists) { + return Head{}, err + } + got, found, rerr := st.ReadHead(ctx) + if rerr != nil { + return Head{}, rerr + } + if !found || got.VolumeID != v.ID { + return Head{}, fmt.Errorf("%w: HEAD of %s, not %s", ErrIdentity, got.VolumeID, v.ID) + } + if got.State == StateDeleting || got.State == StateDeleted { + // the volume is being deleted, or the operator released this + // target and tombstoned it first; a detached HEAD (a clean stop + // before a move) is the volume's, for Start to claim + return Head{}, fmt.Errorf("%w: HEAD of %s is %s", ErrVolumeDeleting, v.ID, got.State) + } + if current != nil && (got.Current == nil || *got.Current != *current) { + // another create (an empty volume) got there first, or the + // target has moved on since: refuse rather than report a restore + return Head{}, fmt.Errorf("%w: %s was created without the restored image", ErrExists, v.ID) + } + return got, nil + } + return h, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/create_target_interrupt_test.go b/seaweed-block/core/frontend/chunkstore/layout/create_target_interrupt_test.go new file mode 100644 index 0000000000..6d4134d8e0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/create_target_interrupt_test.go @@ -0,0 +1,97 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "reflect" + "testing" +) + +// CreateTarget killed at every step, before the step applies and after it +// applied with its reply lost: the source's AddDependent, the root and +// segment copy, the target's VOLUME and its HEAD. Until the HEAD exists +// the target is not startable (no HEAD: Start refuses); a re-run converges +// to the same target as an uninterrupted create, with the dependent +// recorded once and the same root copied. +func TestCreateTarget_InterruptAtEveryStep(t *testing.T) { + ctx := context.Background() + v := Volume{ID: idFor("t"), Name: "t", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat} + setup := func(t *testing.T) (*memHead, *Reader, *memNewVolume) { + o, h, _, _ := removeFixture(t) + r, err := NewReader(removeBase, "v1", o.fetch) + if err != nil { + t.Fatal(err) + } + h.Activity = Activity{Kind: ActIdle} + return &memHead{h: h}, r, newMemNewVolume() + } + + // The uninterrupted create every re-run must reach. + src, r, st := setup(t) + var want RootName + ref, err := CreateTarget(ctx, src, r, "daily", st, v, func(_ context.Context, rn RootName) error { want = rn; return nil }) + if err != nil { + t.Fatal(err) + } + wantDeps := src.h.Snapshots["daily"].Dependents + + for _, step := range []string{"AddDependent", "copy", "VOLUME", "HEAD"} { + for _, after := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/after=%t", step, after), func(t *testing.T) { + src, r, st := setup(t) + var copies []RootName + killCopy := step == "copy" + copyRoot := func(_ context.Context, rn RootName) error { + if killCopy { + killCopy = false + if after { + copies = append(copies, rn) // copied, the reply lost + } + return errKilled + } + copies = append(copies, rn) + return nil + } + switch step { + case "AddDependent": + src.killAt, src.after = 1, after + case "VOLUME": + st.killAt, st.after = 1, after + case "HEAD": + st.killAt, st.after = 2, after + } + if _, err := CreateTarget(ctx, src, r, "daily", st, v, copyRoot); !errors.Is(err, errKilled) { + t.Fatalf("killed run: %v; want the kill", err) + } + if st.memHead.h != nil && !(step == "HEAD" && after) { + t.Fatalf("killed at %s: the target has a HEAD (startable) before the create finished: %+v", step, st.memHead.h) + } + // restart the process + src.dead, src.killAt, src.after = false, 0, false + st.restart() + got, err := CreateTarget(ctx, src, r, "daily", st, v, copyRoot) + if err != nil { + t.Fatalf("re-run: %v", err) + } + // Gen is the store's: a replayed create reads it back (1 here), + // a first create returns the HEAD it wrote without one. + got.Gen, ref.Gen = 0, 0 + if !reflect.DeepEqual(got, ref) { + t.Fatalf("re-run HEAD %+v; the uninterrupted create gives %+v", got, ref) + } + if d := src.h.Snapshots["daily"].Dependents; !reflect.DeepEqual(d, wantDeps) { + t.Fatalf("source dependents %+v; want %+v (recorded once)", d, wantDeps) + } + if st.vol == nil || st.vol.ID != v.ID { + t.Fatalf("target VOLUME %+v", st.vol) + } + for _, rn := range copies { + if rn != want { + t.Fatalf("copied %s; the snapshot's root is %s", rn, want) + } + } + }) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/create_test.go b/seaweed-block/core/frontend/chunkstore/layout/create_test.go new file mode 100644 index 0000000000..312104da0b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/create_test.go @@ -0,0 +1,243 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "reflect" + "testing" +) + +// memNewVolume is a volume directory: VOLUME and HEAD, each created +// exclusively; killAt kills the process at its n-th create, before the +// write applies or (after) once it applied with its reply lost. +type memNewVolume struct { + *memHead + vol *Volume + creates int + killAt int + after, killed bool +} + +func newMemNewVolume() *memNewVolume { return &memNewVolume{memHead: &memHead{}} } + +func (m *memNewVolume) kill() (bool, error) { + if m.killed { + return false, errKilled + } + m.creates++ + if m.creates == m.killAt { + m.killed = true + return m.after, errKilled + } + return true, nil +} + +func (m *memNewVolume) ReadVolumeRecord(context.Context) (Volume, bool, error) { + if m.killed { + return Volume{}, false, errKilled + } + if m.vol == nil { + return Volume{}, false, nil + } + return *m.vol, true, nil +} + +func (m *memNewVolume) CreateVolumeRecord(_ context.Context, v Volume) error { + if m.vol != nil && !m.killed { + return ErrExists + } + apply, err := m.kill() + if apply { + vv := v + m.vol = &vv + } + return err +} + +func (m *memNewVolume) ReadHead(ctx context.Context) (Head, bool, error) { + if m.killed { + return Head{}, false, errKilled + } + return m.memHead.ReadHead(ctx) +} + +func (m *memNewVolume) CreateHead(_ context.Context, h Head) error { + if m.memHead.h != nil && !m.killed { + return ErrExists + } + apply, err := m.kill() + if apply { + if _, eerr := h.Encode(); eerr != nil { + return eerr + } + n := h.clone() + n.Gen = 1 + m.memHead.h = &n + } + return err +} + +func (m *memNewVolume) restart() { m.killed, m.killAt = false, 0 } + +func TestUnclaimedHead_Shape(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + for name, h := range map[string]Head{ + "new volume": Unclaimed(idFor("v"), nil), + "restore target": Unclaimed(idFor("v"), &rn), + "tombstone": {VolumeID: idFor("v"), Activity: Activity{Kind: ActIdle}, State: StateDeleted}, + } { + if _, err := h.Encode(); err != nil { + t.Errorf("%s: %v", name, err) + } + } + for name, h := range map[string]Head{ + "epoch without holder": {VolumeID: idFor("v"), Epoch: 1, Activity: Activity{Kind: ActIdle}}, + "claim id without holder": {VolumeID: idFor("v"), ClaimID: "k", Activity: Activity{Kind: ActIdle}}, + "activity without holder": {VolumeID: idFor("v"), Activity: Activity{Kind: ActSnap, Session: "s"}}, + "holder without epoch": {VolumeID: idFor("v"), Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}}, + "holder without claim id": {VolumeID: idFor("v"), Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}}, + } { + if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { + t.Errorf("%s: %v; want ErrMalformed", name, err) + } + } + // No holder step applies to an unclaimed HEAD, not even for an empty caller. + h := Unclaimed(idFor("v"), nil) + for _, me := range []HolderID{{}, {Epoch: 1, Holder: "a", ClaimID: "k"}} { + if _, _, err := h.Begin(me, "s"); !errors.Is(err, ErrNotHolder) { + t.Errorf("Begin by %+v on an unclaimed HEAD: %v; want ErrNotHolder", me, err) + } + } +} + +// The first Start claims an unclaimed HEAD only from a fresh root. +func TestStart_ClaimsAnUnclaimedHeadFromAFreshRoot(t *testing.T) { + ctx := context.Background() + line := HolderID{Epoch: 1, Holder: "s1/r1"} + h := Unclaimed(idFor("v1"), nil) + h.Gen = 1 + st := &memHead{h: &h} + if _, err := Start(ctx, st, &fakeLease{ended: true}, line, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k1"}); !errors.Is(err, ErrStaleLocalRoot) || st.updates != 0 { + t.Fatalf("non-fresh root on an unclaimed HEAD: %v (%d writes); want ErrStaleLocalRoot", err, st.updates) + } + got, err := Start(ctx, st, &fakeLease{ended: true}, line, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k1", Fresh: true, CanStartFrom: anyStart}) + if err != nil || got.Epoch != 1 || got.Holder != "s1/r1" || got.ClaimID != "k1" { + t.Fatalf("fresh root on an unclaimed HEAD: %+v %v", got, err) + } +} + +func TestCreateVolume(t *testing.T) { + ctx := context.Background() + v := Volume{ID: idFor("v1"), Name: "v1", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat} + st := newMemNewVolume() + h, err := CreateVolume(ctx, st, v) + if err != nil || h.VolumeID != v.ID || h.Holder != "" || h.Epoch != 0 || h.Current != nil || st.vol == nil { + t.Fatalf("CreateVolume: %+v %v", h, err) + } + if again, err := CreateVolume(ctx, st, v); err != nil || again.VolumeID != v.ID || st.creates != 2 { + t.Fatalf("CreateVolume again: %v, %d creates; want a replay", err, st.creates) + } + other := newMemNewVolume() + other.vol = &Volume{ID: idFor("x"), Name: "v1", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat} + if _, err := CreateVolume(ctx, other, v); !errors.Is(err, ErrIdentity) || other.memHead.h != nil { + t.Fatalf("CreateVolume over another id's VOLUME: %v; want ErrIdentity, no HEAD", err) + } +} + +// Creating a volume whose HEAD exists returns that HEAD unchanged while it is +// live or detached (a clean stop before a move: the target's attach check +// creates, then Start claims), and refuses it while deleting or deleted. +func TestCreateVolume_OverAnExistingHeadByState(t *testing.T) { + ctx := context.Background() + v := Volume{ID: idFor("v1"), Name: "v1", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat} + for _, state := range []string{StateLive, StateDetached, StateDeleting, StateDeleted} { + st := newMemNewVolume() + h, err := CreateVolume(ctx, st, v) + if err != nil { + t.Fatal(err) + } + held := h.clone() + // a real detached HEAD names its committed image + img := RootName{Hash: Sum([]byte("image"))} + held.Epoch, held.Holder, held.ClaimID, held.State, held.Current = 2, "a/r1", "k", state, &img + st.memHead.h = &held + got, err := CreateVolume(ctx, st, v) + switch state { + case StateLive, StateDetached: + if err != nil || got.State != state || got.ClaimID != "k" || got.Epoch != 2 { + t.Fatalf("create over a %s HEAD: %+v %v; want that HEAD unchanged", state, got, err) + } + default: + if !errors.Is(err, ErrVolumeDeleting) { + t.Fatalf("create over a %s HEAD: %v; want ErrVolumeDeleting", state, err) + } + } + if !reflect.DeepEqual(*st.memHead.h, held) { + t.Fatalf("create over a %s HEAD wrote it: %+v", state, *st.memHead.h) + } + } +} + +// Killed at each create, before it applies and after with the reply lost, +// a re-run completes with VOLUME and the unclaimed HEAD. +func TestCreateVolume_InterruptAtEveryStep(t *testing.T) { + ctx := context.Background() + v := Volume{ID: idFor("v1"), Name: "v1", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat} + for k := 1; k <= 2; k++ { + for _, after := range []bool{false, true} { + t.Run(fmt.Sprintf("create%d/after=%t", k, after), func(t *testing.T) { + st := newMemNewVolume() + st.killAt, st.after = k, after + if _, err := CreateVolume(ctx, st, v); !errors.Is(err, errKilled) { + t.Fatalf("killed run: %v", err) + } + st.restart() + h, err := CreateVolume(ctx, st, v) + if err != nil || h.VolumeID != v.ID || st.vol == nil || st.vol.ID != v.ID { + t.Fatalf("re-run: %+v %v", h, err) + } + }) + } + } +} + +// CreateTarget records the dependent before it writes anything of the +// target, and its HEAD names the copied root; once the operator has +// tombstoned the target, the create refuses. +func TestCreateTarget(t *testing.T) { + ctx := context.Background() + o, h, _, _ := removeFixture(t) + r, err := NewReader(removeBase, "v1", o.fetch) + if err != nil { + t.Fatal(err) + } + h.Activity = Activity{Kind: ActIdle} + src := &memHead{h: h} + v := Volume{ID: idFor("t"), Name: "t", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat} + st := newMemNewVolume() + var copied *RootName + copyRoot := func(_ context.Context, rn RootName) error { + if d := src.h.Snapshots["daily"].Dependents; len(d) != 1 || d[0].TargetID != v.ID { + t.Fatalf("copy before the dependent is recorded: %+v", d) + } + copied = &rn + return nil + } + got, err := CreateTarget(ctx, src, r, "daily", st, v, copyRoot) + if err != nil || copied == nil || got.Current == nil || *got.Current != *copied || *copied != src.h.Snapshots["daily"].Root { + t.Fatalf("CreateTarget: %+v %v", got, err) + } + empty := newMemNewVolume() + if _, err := CreateVolume(ctx, empty, v); err != nil { + t.Fatal(err) + } + if _, err := CreateTarget(ctx, src, r, "daily", empty, v, func(context.Context, RootName) error { return nil }); !errors.Is(err, ErrExists) { + t.Fatalf("CreateTarget over an empty volume created first: %v; want ErrExists", err) + } + tomb := newMemNewVolume() + tomb.memHead.h = &Head{VolumeID: v.ID, Activity: Activity{Kind: ActIdle}, State: StateDeleted, Gen: 1} + if _, err := CreateTarget(ctx, src, r, "daily", tomb, v, func(context.Context, RootName) error { return nil }); !errors.Is(err, ErrVolumeDeleting) { + t.Fatalf("CreateTarget over the operator's tombstone: %v; want ErrVolumeDeleting", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete.go b/seaweed-block/core/frontend/chunkstore/layout/delete.go index 81639ee02e..a5d66b1e8e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete.go @@ -25,6 +25,8 @@ var ( ErrHasDependents = errors.New("layout: a snapshot has dependents") // ErrHolderActive: a transaction is open on the volume. ErrHolderActive = errors.New("layout: a holder is acting on the volume") + // ErrNotDeleting: MarkDeleted on a HEAD whose delete never began. + ErrNotDeleting = errors.New("layout: the volume's delete has not begun") // ErrTargetLive: the operator asked to release a dependent whose // target still exists and may still name the source's chunks. ErrTargetLive = errors.New("layout: the dependent's target is live") @@ -80,7 +82,7 @@ func (h Head) MarkDeleted() (next Head, changed bool, err error) { case StateDeleted: return h, false, nil case StateLive, StateDetached: - return Head{}, false, fmt.Errorf("layout: HEAD is %q; a delete marks it deleting first", h.State) + return Head{}, false, fmt.Errorf("%w: HEAD is %q; a delete marks it deleting first", ErrNotDeleting, h.State) } next = h.clone() next.State = StateDeleted @@ -159,14 +161,14 @@ func RunReleaseDependent(ctx context.Context, source HeadStore, target VolumeID) // removes the object of a volume created again under the name), then HEAD // deleted. A source left out keeps an extra dependent, which over-protects // and is released by the operator's command. -func DeleteVolume(ctx context.Context, st HeadStore, auth DeleteAuthority, id VolumeID, sources []HeadStore, os ObjectStore, objects []string) error { - if auth == nil || os == nil { - return errors.New("layout: delete needs the master's delete authority and an object store") - } - for _, rel := range objects { - if !isObjectPath(rel) { - return fmt.Errorf("%w: %q is not a pool, segment or root object; HEAD, VOLUME and the directory stay", ErrMalformed, rel) - } +// +// The objects are listed (list) only after HEAD is deleting, so nothing a +// holder uploaded before the reservation escapes the listing. A re-run on +// a deleted HEAD lists and deletes again: the operator's sweep for a late +// object of a dead holder. +func DeleteVolume(ctx context.Context, st HeadStore, auth DeleteAuthority, id VolumeID, sources []HeadStore, os ObjectStore, list func(context.Context) ([]string, error)) error { + if auth == nil || os == nil || list == nil { + return errors.New("layout: delete needs the master's delete authority, an object store and a lister") } if err := auth.Reserve(ctx); err != nil { return fmt.Errorf("layout: delete reservation: %w", err) @@ -179,6 +181,15 @@ func DeleteVolume(ctx context.Context, st HeadStore, auth DeleteAuthority, id Vo return err } } + objects, err := list(ctx) + if err != nil { + return fmt.Errorf("layout: list the volume's objects: %w", err) + } + for _, rel := range objects { + if !isObjectPath(rel) { + return fmt.Errorf("%w: %q is not a pool, segment or root object; HEAD, VOLUME and the directory stay", ErrMalformed, rel) + } + } for _, rel := range objects { if err := os.DeleteOfVolume(ctx, rel, id); err != nil { if errors.Is(err, ErrPrecondition) { @@ -187,7 +198,7 @@ func DeleteVolume(ctx context.Context, st HeadStore, auth DeleteAuthority, id Vo return fmt.Errorf("layout: delete %s: %w", rel, err) } } - _, err := RunMarkDeleted(ctx, st) + _, err = RunMarkDeleted(ctx, st) return err } @@ -252,28 +263,10 @@ func OperatorReleaseDependent(ctx context.Context, source HeadStore, target Targ // Every shard of every root is read; an unreadable one is an error, never // "names nothing". func namesVolume(ctx context.Context, r *Reader, h Head, owner VolumeID) (bool, error) { - roots := map[RootName]bool{} - if h.Current != nil { - roots[*h.Current] = true - } - for _, s := range h.Snapshots { - roots[s.Root] = true - } - for rn := range roots { - img, err := r.Open(ctx, rn) - if err != nil { - return false, err - } - for shard := range img.root.Segments { - seg, _, err := img.Segment(ctx, shard) - if err != nil { - return false, err - } - for _, ref := range seg.Chunks { - if ref.OwnerID == owner { - return true, nil - } - } + found := false + for _, rn := range HeadRoots(h) { + if err := r.EachRef(ctx, rn, AllShards, func(_ uint64, ref Ref) bool { found = ref.OwnerID == owner; return !found }); err != nil || found { + return found, err } } return false, nil diff --git a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go index 62a77b54cc..456edff35e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/delete_test.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" "path" + "sort" + "strings" "testing" ) @@ -82,7 +84,7 @@ func TestDeleting_RefusesEveryHolderStep(t *testing.T) { for name, step := range map[string]func() error{ "Begin": func() error { _, _, err := h.Begin(me, "s"); return err }, "Abort": func() error { _, _, err := h.Abort(me, "s"); return err }, - "Commit": func() error { _, _, err := h.Commit(me, "s", rn, 1, "", StateLive); return err }, + "Commit": func() error { _, _, err := h.Commit(me, "s", rn, 1, "", SnapshotMeta{}, StateLive); return err }, "BeginClean": func() error { _, _, err := h.BeginClean(me, "c"); return err }, "EndClean": func() error { _, _, err := h.EndClean(me, "c"); return err }, "Claim": func() error { _, _, err := h.Claim(newer); return err }, @@ -208,7 +210,7 @@ func TestDeleteVolume_ALateDeleteSparesTheNameReused(t *testing.T) { ctx := context.Background() w := newDeleteWorld() o := w.objects() - if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, fixed(w.rels)); err != nil { t.Fatal(err) } o.volume = idFor("t again") // the name holds a new volume, which writes the same content name @@ -230,19 +232,19 @@ func TestDeleteVolume(t *testing.T) { ctx := context.Background() w := newDeleteWorld() o := w.objects() - if err := DeleteVolume(ctx, w.t, &fakeMaster{leases: 1}, idFor("t"), []HeadStore{w.src}, o, w.rels); !errors.Is(err, ErrHolderActive) || w.t.updates != 0 { + if err := DeleteVolume(ctx, w.t, &fakeMaster{leases: 1}, idFor("t"), []HeadStore{w.src}, o, fixed(w.rels)); !errors.Is(err, ErrHolderActive) || w.t.updates != 0 { t.Fatalf("delete while held: %v (%d HEAD writes)", err, w.t.updates) } - if err := DeleteVolume(ctx, w.src, &fakeMaster{}, idFor("src"), nil, o, nil); !errors.Is(err, ErrHasDependents) { + if err := DeleteVolume(ctx, w.src, &fakeMaster{}, idFor("src"), nil, o, fixed(nil)); !errors.Is(err, ErrHasDependents) { t.Fatalf("delete of a volume with a dependent: %v; want ErrHasDependents", err) } - if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, fixed(w.rels)); err != nil { t.Fatal(err) } if w.t.h.State != StateDeleted || len(o.objs) != 0 || len(w.src.h.Snapshots["daily"].Dependents) != 0 { t.Fatalf("after the delete: state %q, %d objects, source dependents %+v", w.t.h.State, len(o.objs), w.src.h.Snapshots["daily"].Dependents) } - if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, fixed(w.rels)); err != nil { t.Fatalf("a further re-run: %v", err) } } @@ -275,7 +277,7 @@ func TestDeleteVolume_InterruptAtEveryStep(t *testing.T) { case "object": o.killAt, o.after = nth, after } - if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); !errors.Is(err, errKilled) { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, fixed(w.rels)); !errors.Is(err, errKilled) { t.Fatalf("killed run: %v", err) } if len(o.objs) < len(w.rels) && (w.t.h.State == StateLive || len(w.src.h.Snapshots["daily"].Dependents) != 0) { @@ -287,7 +289,7 @@ func TestDeleteVolume_InterruptAtEveryStep(t *testing.T) { w.t.restart() w.src.restart() o.dead, o.killAt = false, 0 - if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, fixed(w.rels)); err != nil { t.Fatalf("re-run: %v", err) } if w.t.h.State != StateDeleted || len(o.objs) != 0 || len(w.src.h.Snapshots["daily"].Dependents) != 0 { @@ -307,7 +309,7 @@ func operatorCase(t *testing.T, tgtHead *Head, tgtVolume *VolumeID, namesSource objs := map[string][]byte{} put := func(rel string, b []byte) { objs[path.Join(removeBase, "t", rel)] = b } if tgtVolume != nil { - b, err := Volume{ID: *tgtVolume, Name: "t", Format: VolumeFormat}.Encode() + b, err := Volume{ID: *tgtVolume, Name: "t", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat}.Encode() if err != nil { t.Fatal(err) } @@ -417,14 +419,15 @@ func (r *raceTarget) CreateDeletedHead(ctx context.Context, h Head) error { return r.memHead.CreateDeletedHead(ctx, h) } -// A volume delete removes only content-named objects: HEAD (which stays, -// deleted), VOLUME and the directory are refused before any write. +// A volume delete removes only content-named objects: a listing that +// names HEAD (which stays, deleted), VOLUME or the directory is refused +// before any object is deleted. func TestDeleteVolume_RemovesOnlyObjects(t *testing.T) { for _, bad := range []string{HeadName, VolumeName, "", "pool/", "pool/../HEAD", "other/x"} { w := newDeleteWorld() o := w.objects() - if err := DeleteVolume(context.Background(), w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, append(append([]string(nil), w.rels...), bad)); !errors.Is(err, ErrMalformed) || w.t.updates != 0 || len(o.writes) != 0 { - t.Errorf("delete listing %q: %v (%d HEAD writes, %d object writes); want ErrMalformed and nothing written", bad, err, w.t.updates, len(o.writes)) + if err := DeleteVolume(context.Background(), w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, fixed(append(append([]string(nil), w.rels...), bad))); !errors.Is(err, ErrMalformed) || len(o.writes) != 0 { + t.Errorf("delete listing %q: %v (%d object writes); want ErrMalformed and no object deleted", bad, err, len(o.writes)) } } } @@ -445,7 +448,7 @@ func TestDeleteVolume_AGrantRaceNeverDeletesALiveVolume(t *testing.T) { t.Fatal(err) } claim(w.t) - if err := DeleteVolume(ctx, w.t, m, idFor("t"), []HeadStore{w.src}, o, w.rels); !errors.Is(err, ErrHolderActive) || len(o.writes) != 0 || w.t.h.State != StateLive { + if err := DeleteVolume(ctx, w.t, m, idFor("t"), []HeadStore{w.src}, o, fixed(w.rels)); !errors.Is(err, ErrHolderActive) || len(o.writes) != 0 || w.t.h.State != StateLive { t.Fatalf("delete of a volume with a granted line: %v, %d object writes, HEAD %s; want ErrHolderActive, nothing deleted", err, len(o.writes), w.t.h.State) } }) @@ -459,7 +462,7 @@ func TestDeleteVolume_AGrantRaceNeverDeletesALiveVolume(t *testing.T) { claim(w.t) } } - if err := DeleteVolume(ctx, w.t, m, idFor("t"), []HeadStore{w.src}, o, w.rels); err != nil { + if err := DeleteVolume(ctx, w.t, m, idFor("t"), []HeadStore{w.src}, o, fixed(w.rels)); err != nil { t.Fatalf("delete: %v", err) } if grantErr == nil { @@ -470,8 +473,51 @@ func TestDeleteVolume_AGrantRaceNeverDeletesALiveVolume(t *testing.T) { w := newDeleteWorld() o := w.objects() w.t.afterRead = func() { claim(w.t) } - if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, w.rels); err == nil || len(o.writes) != 0 || w.t.h.State != StateLive { + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, fixed(w.rels)); err == nil || len(o.writes) != 0 || w.t.h.State != StateLive { t.Fatalf("delete with a claim after its HEAD read: %v, %d object writes, HEAD %s; want the update refused, nothing deleted", err, len(o.writes), w.t.h.State) } }) } + +// fixed is a lister of a fixed set of objects. +func fixed(rels []string) func(context.Context) ([]string, error) { + return func(context.Context) ([]string, error) { return rels, nil } +} + +// dirLister lists every object of the store, at the time it is called. +func dirLister(o *memObjects) func(context.Context) ([]string, error) { + return func(context.Context) ([]string, error) { + var out []string + for p := range o.objs { + out = append(out, strings.TrimPrefix(p, o.root+"/")) + } + sort.Strings(out) + return out, nil + } +} + +// The objects are listed after HEAD is deleting: one a holder uploaded +// between an early listing point and the reservation is deleted too; a +// re-run on the deleted HEAD sweeps one that landed after the delete. +func TestDeleteVolume_ListsAfterTheMark(t *testing.T) { + ctx := context.Background() + w := newDeleteWorld() + o := w.objects() + late := NameChunk(9, []byte("late")).Path() + m := &fakeMaster{onReserve: func() { + o.objs[path.Join(o.root, late)] = &memObject{data: []byte("late"), meta: ObjectMeta{Session: "s9", Volume: o.volume}} + }} + if err := DeleteVolume(ctx, w.t, m, idFor("t"), []HeadStore{w.src}, o, dirLister(o)); err != nil { + t.Fatal(err) + } + if len(o.objs) != 0 { + t.Fatalf("objects left after the delete: %d; want none (also the one uploaded before the reservation)", len(o.objs)) + } + o.objs[path.Join(o.root, late)] = &memObject{data: []byte("late"), meta: ObjectMeta{Session: "s9", Volume: o.volume}} + if err := DeleteVolume(ctx, w.t, &fakeMaster{}, idFor("t"), []HeadStore{w.src}, o, dirLister(o)); err != nil || len(o.objs) != 0 { + t.Fatalf("sweep re-run on the deleted HEAD: %v, %d objects left", err, len(o.objs)) + } + if w.t.h.State != StateDeleted { + t.Fatalf("HEAD after the sweep: %s", w.t.h.State) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/detached_test.go b/seaweed-block/core/frontend/chunkstore/layout/detached_test.go index b918a119f3..cb74eaf612 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/detached_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/detached_test.go @@ -28,7 +28,7 @@ func TestCommitDetached_ProofAndLostReply(t *testing.T) { if proof.State != StateDetached || proof.Position != req.Position || proof.Activity.Kind != ActIdle { t.Fatal("HEAD lacks the final synced image proof", proof) } - if _, err := Start(context.Background(), st, &fakeLease{}, me, LocalRoot{ClaimID: me.ClaimID, Position: req.Position}); !errors.Is(err, ErrDetached) || !strings.Contains(err.Error(), "new grant") { + if _, err := Start(context.Background(), st, &fakeLease{}, me, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: me.ClaimID, Position: req.Position}); !errors.Is(err, ErrDetached) || !strings.Contains(err.Error(), "new grant") { t.Fatal("same-epoch start did not refuse with the cure", err) } } else if proof.State != StateLive || proof.Position != h.Position { @@ -48,7 +48,7 @@ func TestDetachedHEAD_RefusesEveryHolderTransition(t *testing.T) { steps := map[string]func() error{ "Begin": func() error { _, _, e := h.Begin(me, "s"); return e }, "Abort": func() error { _, _, e := h.Abort(me, "s"); return e }, - "Commit": func() error { _, _, e := h.Commit(me, "s", rn, h.Position, "", StateLive); return e }, + "Commit": func() error { _, _, e := h.Commit(me, "s", rn, h.Position, "", SnapshotMeta{}, StateLive); return e }, "BeginClean": func() error { _, _, e := h.BeginClean(me, "c"); return e }, "EndClean": func() error { _, _, e := h.EndClean(me, "c"); return e }, "Claim": func() error { _, _, e := h.Claim(me); return e }, @@ -95,7 +95,7 @@ func TestDetachedHEAD_NewGrantStillWaitsForTheOldLease(t *testing.T) { line := me line.Epoch++ lease := &fakeLease{} - local := LocalRoot{ClaimID: me.ClaimID, Position: h.Position} + local := LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: me.ClaimID, Position: h.Position} if _, err := Start(context.Background(), st, lease, line, local); err == nil || st.updates != 0 || len(lease.calls) != 1 { t.Fatal("higher epoch bypassed old lease", err, st.updates, lease.calls) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/each_ref_test.go b/seaweed-block/core/frontend/chunkstore/layout/each_ref_test.go new file mode 100644 index 0000000000..968a3ee346 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/each_ref_test.go @@ -0,0 +1,61 @@ +package layout + +import ( + "context" + "errors" + "path" + "testing" +) + +// EachRef visits every reference of the selected shards and stops when fn +// says so; an unreadable segment is an error, never a partial walk. +// HeadRoots names each root HEAD holds once. +func TestEachRefAndHeadRoots(t *testing.T) { + ctx := context.Background() + m := &memStore{obj: map[string][]byte{}} + rn := putImage(t, m, "v", map[uint64]string{0: "a", 1: "b", ShardSize + 2: "c"}, nil) + r, err := NewReader(vbase, "v", m.fetch) + if err != nil { + t.Fatal(err) + } + visit := func(shard uint64, stop int) (map[uint64]bool, error) { + got := map[uint64]bool{} + err := r.EachRef(ctx, rn, shard, func(i uint64, _ Ref) bool { got[i] = true; return len(got) != stop }) + return got, err + } + if got, err := visit(AllShards, -1); err != nil || len(got) != 3 || !got[ShardSize+2] { + t.Fatalf("all shards: %v %v; want 0, 1 and %d", got, err, ShardSize+2) + } + if got, err := visit(1, -1); err != nil || len(got) != 1 || !got[ShardSize+2] { + t.Fatalf("shard 1: %v %v; want only %d", got, err, ShardSize+2) + } + if got, err := visit(7, -1); err != nil || len(got) != 0 { + t.Fatalf("a shard the root does not name: %v %v; want none", got, err) + } + if got, err := visit(AllShards, 1); err != nil || len(got) != 1 { + t.Fatalf("stop after one: %v %v", got, err) + } + img, err := r.Open(ctx, rn) + if err != nil { + t.Fatal(err) + } + seg := img.root.Segments[0] + m.readErr = path.Join(vbase, "v", seg.Path()) + if _, err := visit(AllShards, -1); err == nil || errors.Is(err, ErrMissing) { + t.Fatalf("unreadable segment: %v; want the read error", err) + } + m.readErr = "" + delete(m.obj, path.Join(vbase, "v", seg.Path())) + if _, err := visit(AllShards, -1); !errors.Is(err, ErrMissing) { + t.Fatalf("missing segment: %v; want ErrMissing", err) + } + + s := RootName{Hash: Sum([]byte("s"))} + h := Head{Current: &rn, Snapshots: map[string]Snapshot{"a": {Root: rn}, "b": {Root: s}}} + if roots := HeadRoots(h); len(roots) != 2 || roots[0] != rn { + t.Fatalf("HEAD roots %v; want the current root once, then the snapshot's", roots) + } + if roots := HeadRoots(Head{}); len(roots) != 0 { + t.Fatalf("an empty HEAD names %v", roots) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 2c3d028485..c71e0be859 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -191,6 +191,14 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) bad = append(bad, fn+" uses CreateDeletedHead: only the operator's release writes a tombstone, for a target never created") } } + // HEAD creates are exactly three: a new volume's and a restore target's + // unclaimed HEAD (createVolume, for CreateVolume and CreateTarget) and + // the operator's tombstone (above). + for _, fn := range owners(code["CreateHead"]) { + if fn != "createVolume" { + bad = append(bad, fn+" uses CreateHead: only createVolume creates a HEAD (unclaimed), besides the operator's tombstone") + } + } for _, fn := range owners(code["RunReleaseDependent"]) { if fn != "DeleteVolume" && fn != "OperatorReleaseDependent" { bad = append(bad, fn+" uses RunReleaseDependent: only DeleteVolume (target deleting) and OperatorReleaseDependent (target checked) release") @@ -200,6 +208,9 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) bad = append(bad, "OperatorReleaseDependent does not read the target's HEAD before releasing") } for name, by := range code { + if name == "DeleteSnapshot" { + continue // a HEAD transition (a snapshot's name leaves HEAD), not a store remover + } if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") { for _, fn := range owners(by) { if fn != "RemoveUnreachable" && fn != "DeleteVolume" { @@ -480,6 +491,7 @@ func w(ctx context.Context, x g) error { return x.NoLiveLease(ctx) }`, want: "on "one mark, two deletes": {file: "remove.go", src: removeVariant(t, "second"), want: "without a mark gate immediately before it"}, "unlisted removal method": {file: "remove.go", src: removeVariant(t, "other"), want: "without a mark gate immediately before it"}, "claim outside Start": {src: `func w(ctx context.Context, st HeadStore, l LeaseWait, me HolderID) { _, _ = RunClaim(ctx, st, l, me) }`, want: "a claim is made only by Start"}, + "a fourth HEAD create": {src: `func w(ctx context.Context, st NewVolumeStore, h Head) { _ = st.CreateHead(ctx, h) }`, want: "only createVolume creates a HEAD"}, "tombstone outside the operator's release": {src: `func w(ctx context.Context, t TargetStore, h Head) { _ = t.CreateDeletedHead(ctx, h) }`, want: "only the operator's release writes a tombstone"}, "remover method value": {src: `type p interface{ RemoveName(string) } func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable (mark-gated) and DeleteVolume"}, diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index 5b392ff3d2..c5a299ec0c 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -22,7 +22,7 @@ const ( ) // MaxSnapshots bounds the named snapshots one HEAD holds. -const MaxSnapshots = 100 +const MaxSnapshots = 10 // Activity is HEAD's open transaction. Session names it; a session id is // never reused. @@ -41,13 +41,100 @@ type Dependent struct { Root RootName } -// Snapshot is one named snapshot: its root and the restore targets that +// Snapshot is one named snapshot: its root, the position of the commit +// that named it (the cut LSN of its image), and the restore targets that // still name its chunks, ordered by target id. type Snapshot struct { Root RootName + Position uint64 + Meta SnapshotMeta Dependents []Dependent } +// The retention classes of a snapshot. +const ( + ClassSemantic = "semantic" + ClassPinned = "pinned" + ClassScheduled = "scheduled" +) + +// The bounds that keep HEAD inline at its snapshot cap: a snapshot's +// name, its labels, and its dependents. +const ( + MaxSnapshotNameBytes = 64 + MaxSnapshotLabels = 4 + MaxLabelKeyBytes = 24 + MaxLabelValueBytes = 32 + MaxDependents = 4 + // MaxDependentsPerHead bounds the dependents of all snapshots together. + MaxDependentsPerHead = 16 + // MaxHeadBytes is the inline limit: Encode refuses a larger HEAD, so a + // bound missed elsewhere fails the write, never stores it. + MaxHeadBytes = 64 << 10 +) + +// ErrHeadTooLarge: an encoded HEAD above MaxHeadBytes. +var ErrHeadTooLarge = errors.New("layout: HEAD above its inline limit") + +// SnapshotMeta is what retention decides from: written once by the commit +// that creates the name. The times are wall clock and decide policy only; +// reachability, dependents and removal never read them. +type SnapshotMeta struct { + CreatedNs int64 + Class string // "", ClassSemantic, ClassPinned or ClassScheduled + ExpiresNs int64 // pinned until then, when set + Labels map[string]string +} + +// PinnedAt reports whether the snapshot is an explicit keep at nowNs: class +// pinned, or an expiry not yet passed. An automatic delete refuses it. +func (m SnapshotMeta) PinnedAt(nowNs int64) bool { + return m.Class == ClassPinned || m.ExpiresNs > 0 && nowNs < m.ExpiresNs +} + +// CheckSnapshot refuses a snapshot name or facts the commit would refuse +// (ErrMalformed): the name's bounds and encoding, the class, the times and +// the labels. Callers check before the commit, so a refusal there is never +// confused with a malformed manifest. +func CheckSnapshot(name string, meta SnapshotMeta) error { + if name == "" { + return fmt.Errorf("%w: unnamed snapshot", ErrMalformed) + } + if err := validName("snapshot", name); err != nil { + return err + } + if len(name) > MaxSnapshotNameBytes { + return fmt.Errorf("%w: snapshot name %q is %d bytes, at most %d", ErrMalformed, name, len(name), MaxSnapshotNameBytes) + } + return meta.check(name) +} + +func (m SnapshotMeta) check(name string) error { + switch m.Class { + case "", ClassSemantic, ClassPinned, ClassScheduled: + default: + return fmt.Errorf("%w: snapshot %q class %q", ErrMalformed, name, m.Class) + } + if m.CreatedNs < 0 || m.ExpiresNs < 0 { + return fmt.Errorf("%w: snapshot %q has a negative time", ErrMalformed, name) + } + if len(m.Labels) > MaxSnapshotLabels { + return fmt.Errorf("%w: snapshot %q has %d labels, at most %d", ErrMalformed, name, len(m.Labels), MaxSnapshotLabels) + } + for k, v := range m.Labels { + if k == "" || len(k) > MaxLabelKeyBytes || len(v) > MaxLabelValueBytes { + return fmt.Errorf("%w: snapshot %q label %q: keys 1-%d bytes, values at most %d", ErrMalformed, name, k, MaxLabelKeyBytes, MaxLabelValueBytes) + } + if err := validName("label", k); err != nil { + return err + } + if err := validName("label", v); err != nil { + return err + } + } + return nil +} + // Head is the decoded HEAD. Gen is the generation the store holds it at; // it is not part of the encoding. VolumeID is the volume's id (its VOLUME // record's); ClaimID is the id the current holder's claim wrote, which @@ -79,8 +166,13 @@ type headDoc struct { } type snapDoc struct { - Root string `json:"root"` - Dependents []depDoc `json:"dependents,omitempty"` + Root string `json:"root"` + Position uint64 `json:"position,omitempty"` + CreatedNs int64 `json:"created_ns,omitempty"` + Class string `json:"class,omitempty"` + ExpiresNs int64 `json:"expires_ns,omitempty"` + Labels map[string]string `json:"labels,omitempty"` + Dependents []depDoc `json:"dependents,omitempty"` } type depDoc struct { @@ -99,6 +191,12 @@ func validName(field, v string) error { return nil } +// ErrNoNextPosition: a HEAD position with no room for a next LSN. No +// commit produces it (Commit refuses); a HEAD that already carries one (an +// older or broken writer) is still read, written by every other +// transition (so it can be deleted), and Start refuses to seed from it. +var ErrNoNextPosition = fmt.Errorf("%w: HEAD position leaves no room for a next LSN", ErrMalformed) + func (h Head) check() error { if h.VolumeID.IsZero() { return fmt.Errorf("%w: HEAD without a volume id", ErrMalformed) @@ -128,12 +226,16 @@ func (h Head) check() error { if h.State == StateDetached && (h.Activity.Kind != ActIdle || h.Current == nil) { return fmt.Errorf("%w: detached HEAD needs an idle, committed image", ErrMalformed) } - // A deleted HEAD written as a tombstone for a restore target never - // created has no holder; every other HEAD has an epoch, a holder and - // the claim id of its claim. - if h.State != StateDeleted || h.Holder != "" { - if h.Epoch == 0 || h.Holder == "" { - return fmt.Errorf("%w: HEAD without epoch or holder", ErrMalformed) + // A HEAD no one has claimed yet (a new volume or restore target, or a + // tombstone) has epoch 0, no holder, no claim id and no activity; a + // claimed HEAD has an epoch, a holder and the claim id of its claim. + if h.Holder == "" { + if h.Epoch != 0 || h.ClaimID != "" || h.Activity.Kind != ActIdle { + return fmt.Errorf("%w: HEAD without a holder has epoch %d, claim id %q, activity %s", ErrMalformed, h.Epoch, h.ClaimID, h.Activity.Kind) + } + } else { + if h.Epoch == 0 { + return fmt.Errorf("%w: HEAD holder %q without an epoch", ErrMalformed, h.Holder) } if h.ClaimID == "" { return fmt.Errorf("%w: HEAD holder %q without a claim id", ErrMalformed, h.Holder) @@ -142,6 +244,9 @@ func (h Head) check() error { if len(h.Snapshots) > MaxSnapshots { return fmt.Errorf("%w: %d snapshots, at most %d", ErrMalformed, len(h.Snapshots), MaxSnapshots) } + if n := h.dependents(); n > MaxDependentsPerHead { + return fmt.Errorf("%w: %d dependents in HEAD, at most %d", ErrMalformed, n, MaxDependentsPerHead) + } for n, s := range h.Snapshots { if n == "" { return fmt.Errorf("%w: unnamed snapshot", ErrMalformed) @@ -149,6 +254,20 @@ func (h Head) check() error { if err := validName("snapshot", n); err != nil { return err } + if len(n) > MaxSnapshotNameBytes { + return fmt.Errorf("%w: snapshot name %q is %d bytes, at most %d", ErrMalformed, n, len(n), MaxSnapshotNameBytes) + } + if len(s.Dependents) > MaxDependents { + return fmt.Errorf("%w: snapshot %q has %d dependents, at most %d", ErrMalformed, n, len(s.Dependents), MaxDependents) + } + if err := s.Meta.check(n); err != nil { + return err + } + if s.Position > h.Position { + // a snapshot is a past moment of this volume; HEAD's position + // only rises (Commit) + return fmt.Errorf("%w: snapshot %q at position %d, past HEAD's %d", ErrMalformed, n, s.Position, h.Position) + } for i, d := range s.Dependents { if err := validName("dependent", d.Target); err != nil { return err @@ -182,14 +301,21 @@ func (h Head) Encode() ([]byte, error) { if len(h.Snapshots) > 0 { d.Snapshots = map[string]snapDoc{} for n, s := range h.Snapshots { - sd := snapDoc{Root: s.Root.String()} + sd := snapDoc{Root: s.Root.String(), Position: s.Position, CreatedNs: s.Meta.CreatedNs, Class: s.Meta.Class, ExpiresNs: s.Meta.ExpiresNs} + if len(s.Meta.Labels) > 0 { + sd.Labels = s.Meta.Labels + } for _, dep := range s.Dependents { sd.Dependents = append(sd.Dependents, depDoc{Target: dep.Target, TargetID: dep.TargetID.String(), Root: dep.Root.String()}) } d.Snapshots[n] = sd } } - return json.Marshal(d) + b, err := json.Marshal(d) + if err == nil && len(b) > MaxHeadBytes { + return nil, fmt.Errorf("%w: %d bytes, at most %d", ErrHeadTooLarge, len(b), MaxHeadBytes) + } + return b, err } // DecodeHead parses canonical HEAD bytes for the volume whose VOLUME @@ -226,7 +352,7 @@ func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) { if err != nil { return Head{}, err } - snap := Snapshot{Root: rn} + snap := Snapshot{Root: rn, Position: s.Position, Meta: SnapshotMeta{CreatedNs: s.CreatedNs, Class: s.Class, ExpiresNs: s.ExpiresNs, Labels: s.Labels}} for _, dep := range s.Dependents { tid, err := ParseVolumeID(dep.TargetID) if err != nil { @@ -274,7 +400,14 @@ type HolderID struct { } func (h Head) heldBy(me HolderID) bool { - return h.Epoch == me.Epoch && h.Holder == me.Holder && h.ClaimID == me.ClaimID + return h.Holder != "" && h.Epoch == me.Epoch && h.Holder == me.Holder && h.ClaimID == me.ClaimID +} + +// DetachedBy is the one detached proof: HEAD h is a committed, idle detach +// of exactly me (this epoch, holder and claim id). Missing or foreign +// evidence never proves a detach. A predicate, not a holder transition. +func DetachedBy(h Head, me HolderID) bool { + return h.Gen != 0 && h.State == StateDetached && h.Activity.Kind == ActIdle && h.heldBy(me) } // holderErr is the refusal of a holder transition: the volume is being @@ -323,7 +456,7 @@ func (h Head) clone() Head { if h.Snapshots != nil { c.Snapshots = make(map[string]Snapshot, len(h.Snapshots)) for n, s := range h.Snapshots { - c.Snapshots[n] = Snapshot{Root: s.Root, Dependents: append([]Dependent(nil), s.Dependents...)} + c.Snapshots[n] = Snapshot{Root: s.Root, Position: s.Position, Meta: s.Meta.clone(), Dependents: append([]Dependent(nil), s.Dependents...)} } } return c @@ -404,3 +537,12 @@ func runTransition(ctx context.Context, st HeadStore, t func(Head) (Head, bool, next.Gen = h.Gen + 1 return next, nil } + +// dependents counts the dependents of every snapshot. +func (h Head) dependents() int { + n := 0 + for _, s := range h.Snapshots { + n += len(s.Dependents) + } + return n +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_test.go index 8c53eba933..7f23c7545c 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_test.go @@ -460,3 +460,10 @@ func TestHead_HolderNeedsAClaimID(t *testing.T) { t.Fatalf("HEAD with a holder and no claim id: %v; want ErrMalformed", err) } } + +func (m *memHead) ReadVolumeRecord(context.Context) (Volume, bool, error) { + if m.h == nil { + return Volume{}, false, nil + } + return Volume{ID: m.h.VolumeID, Name: "v1", Format: VolumeFormat, Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}}, true, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go b/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go new file mode 100644 index 0000000000..f0c9ac3159 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/kernel_table_test.go @@ -0,0 +1,418 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "go/ast" + "go/parser" + "go/token" + "os" + "strings" + "testing" +) + +// The kernel's state x entry-point table (spec section 0, made +// executable): every entry point called, as this volume's holder, on HEAD +// in every state, with its result. A new HEAD state or a new entry point +// fails TestKernelTable_Covers until its row or column is filled. +// +// Results: "write" (HEAD changed or was created), "noop" (no write, no +// error: a replay or nothing to do), or the kernel refusal's name. + +// kernelStates are HEAD's states: absent, unclaimed, live with each +// activity, detached, deleting, deleted. +var kernelStates = []string{"absent", "unclaimed", "idle", "snap", "clean", "detached", "deleting", "deleted"} + +// kernelEntries are the kernel's entry points (DeleteVolume is their +// composition: Reserve, MarkDeleting, release, objects, MarkDeleted). +var kernelEntries = []string{ + "CreateVolume", "CreateTarget", "StartHigher", "StartHigherCannotStart", "StartOwn", "StartOwnOtherFresh", "StartOwnOtherFreshCannotStart", "StartOwnOtherOld", + "Claim", "Begin", "Commit", "CommitNew", "CommitLower", "Abort", "BeginClean", "EndClean", + "RemoveUnreachable", "DeleteSnapshot", "RetireSnapshot", "AddDependent", "ReleaseDependent", + "MarkDeleting", "MarkDeleted", "DeletedHeadCreate", +} + +var kernelRefusals = []struct { + name string + err error +}{ + // the local-root refusals wrap ErrNotHolder: name them first + {"StaleLocalRoot", ErrStaleLocalRoot}, {"MissingLocalRoot", ErrMissingLocalRoot}, {"CannotStartFrom", ErrCannotStartFrom}, + {"HeadAbsent", ErrHeadAbsent}, {"NotHolder", ErrNotHolder}, {"Busy", ErrBusy}, {"NoSession", ErrNoSession}, + {"VolumeDeleting", ErrVolumeDeleting}, {"Detached", ErrDetached}, {"StaleEpoch", ErrStaleEpoch}, + {"Exists", ErrExists}, {"HasDependents", ErrHasDependents}, {"TargetLive", ErrTargetLive}, + {"NotPrepared", ErrNotPrepared}, + {"Identity", ErrIdentity}, {"NoSnapshot", ErrNoSnapshot}, {"Malformed", ErrMalformed}, + {"HolderActive", ErrHolderActive}, {"NotDeleting", ErrNotDeleting}, {"PositionBehind", ErrPositionBehind}, +} + +// cannotStart is a local root whose post-claim step fails on any HEAD. +func cannotStart(Head) error { return errors.New("the local root cannot start from this HEAD") } + +func resultOf(err error, wrote bool) string { + if err == nil { + if wrote { + return "write" + } + return "noop" + } + for _, k := range kernelRefusals { + if errors.Is(err, k.err) { + return k.name + } + } + return "other: " + err.Error() +} + +var tableGeometry = Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096} + +// kernelCell sets HEAD in state and runs entry once. +func kernelCell(t *testing.T, state, entry string) string { + t.Helper() + ctx := context.Background() + o, h, _, orphans := removeFixture(t) + h.Position = 10 // a volume with commits behind it (CommitLower commits below it) + switch state { + case "unclaimed": + // a restore target never started: its current root names the + // source's chunks (here the fixture's own image) + u := Unclaimed(h.VolumeID, h.Current) + u.Gen = 1 + h = &u + case "idle": + h.Activity = Activity{Kind: ActIdle} + case "snap": + h.Activity = Activity{Kind: ActSnap, Session: "s1"} + case "clean": + h.Activity = Activity{Kind: ActClean, Session: "c1"} + case "detached": + h.Activity, h.State = Activity{Kind: ActIdle}, StateDetached + case "deleting": + h.Activity, h.State = Activity{Kind: ActIdle}, StateDeleting + case "deleted": + h.Activity, h.State = Activity{Kind: ActIdle}, StateDeleted + case "maxposition": // an older writer left HEAD at the last position + h.Activity, h.Position = Activity{Kind: ActIdle}, ^uint64(0) + case "maxposition-deleting": + h.Activity, h.State, h.Position = Activity{Kind: ActIdle}, StateDeleting, ^uint64(0) + } + if entry == "ReleaseDependent" && h.Snapshots != nil { + d := h.Snapshots["daily"] + d.Dependents = []Dependent{{Target: "t", TargetID: idFor("t"), Root: d.Root}} + h.Snapshots["daily"] = d + } + nv := newMemNewVolume() + vol := Volume{ID: idFor("v1"), Name: "v1", Geometry: tableGeometry, Format: VolumeFormat} + if state != "absent" { + nv.memHead.h = h + nv.vol = &vol + } + before, objectWrites := 0, len(o.writes) + if nv.memHead.h != nil { + before = int(nv.memHead.h.Gen) + } + r, err := NewReader(removeBase, "v1", o.fetch) + if err != nil { + t.Fatal(err) + } + // An idle source volume with a snapshot "daily" naming only its own + // chunks, for the entry points that read or write a source. + _, sh, _, _ := removeFixture(t) + sh.Activity = Activity{Kind: ActIdle} + src := newMemNewVolume() + src.memHead.h, src.vol = sh, &vol + + switch entry { + case "CreateVolume": + _, err = CreateVolume(ctx, nv, vol) + case "CreateTarget": + _, err = CreateTarget(ctx, src, r, "daily", nv, Volume{ID: idFor("v1"), Name: "v1", Geometry: tableGeometry, Format: VolumeFormat}, func(context.Context, RootName) error { return nil }) + case "StartHigher": // a higher granted epoch, a fresh root + _, err = Start(ctx, nv, &fakeLease{ended: true}, HolderID{Epoch: 4, Holder: "srv-a"}, LocalRoot{Geometry: tableGeometry, ClaimID: "k-new", Fresh: true, CanStartFrom: anyStart}) + case "StartOwn": // HEAD's epoch and server, the root carrying HEAD's claim id + _, err = Start(ctx, nv, &fakeLease{ended: true}, HolderID{Epoch: me.Epoch, Holder: me.Holder}, LocalRoot{Geometry: tableGeometry, ClaimID: me.ClaimID, Position: h.Position}) + case "StartOwnOtherFresh": // HEAD's epoch and server, a fresh root of another claim + _, err = Start(ctx, nv, &fakeLease{ended: true}, HolderID{Epoch: me.Epoch, Holder: me.Holder}, LocalRoot{Geometry: tableGeometry, ClaimID: "k-other", Fresh: true, CanStartFrom: anyStart}) + case "StartHigherCannotStart": // a higher granted epoch, a fresh root whose store cannot seed HEAD's position + _, err = Start(ctx, nv, &fakeLease{ended: true}, HolderID{Epoch: 4, Holder: "srv-a"}, LocalRoot{Geometry: tableGeometry, ClaimID: "k-new", Fresh: true, CanStartFrom: cannotStart}) + case "StartOwnOtherFreshCannotStart": + _, err = Start(ctx, nv, &fakeLease{ended: true}, HolderID{Epoch: me.Epoch, Holder: me.Holder}, LocalRoot{Geometry: tableGeometry, ClaimID: "k-other", Fresh: true, CanStartFrom: cannotStart}) + case "StartOwnOtherOld": // HEAD's epoch and server, an older root of another claim + _, err = Start(ctx, nv, &fakeLease{ended: true}, HolderID{Epoch: me.Epoch, Holder: me.Holder}, LocalRoot{Geometry: tableGeometry, ClaimID: "k-other", Position: h.Position}) + case "Claim": + _, err = RunClaim(ctx, nv, &fakeLease{ended: true}, HolderID{Epoch: 4, Holder: "srv-b", ClaimID: "k-b"}) + case "Begin": + _, err = RunBegin(ctx, nv, me, "s2") + case "Commit": + var cur map[uint64]Ref + if h.Current != nil { + img, oerr := r.Open(ctx, *h.Current) + if oerr != nil { + t.Fatal(oerr) + } + cur = map[uint64]Ref{} + for _, sh := range img.Shards() { + seg, _, _ := img.Segment(ctx, sh) + for i, ref := range seg.Chunks { + cur[i] = ref + } + } + } + prepared(t, o, cur, "s1") + objectWrites = len(o.writes) + _, err = RunCommit(ctx, nv, o, "v1", me, CommitRequest{Session: "s1", Prev: cur, Next: cur, Position: h.Position, State: StateLive}) + case "CommitLower": // HEAD's image at a position below HEAD's + var cur map[uint64]Ref + if h.Current != nil { + img, oerr := r.Open(ctx, *h.Current) + if oerr != nil { + t.Fatal(oerr) + } + cur = map[uint64]Ref{} + for _, sh := range img.Shards() { + seg, _, _ := img.Segment(ctx, sh) + for i, ref := range seg.Chunks { + cur[i] = ref + } + } + } + lower := h.Position + if lower > 0 { + lower-- // (a HEAD at 0, absent or never committed, has no lower position) + } + prepared(t, o, cur, "s1") + objectWrites = len(o.writes) + _, err = RunCommit(ctx, nv, o, "v1", me, CommitRequest{Session: "s1", Prev: cur, Next: cur, Position: lower, State: StateLive}) + case "CommitNew": // a new image (not a replay of an applied commit) + var cur map[uint64]Ref + if h.Current != nil { + img, oerr := r.Open(ctx, *h.Current) + if oerr != nil { + t.Fatal(oerr) + } + cur = map[uint64]Ref{} + for _, sh := range img.Shards() { + seg, _, _ := img.Segment(ctx, sh) + for i, ref := range seg.Chunks { + cur[i] = ref + } + } + } + next := map[uint64]Ref{} + for i, ref := range cur { + next[i] = ref + } + next[9] = ref("v1", 9, "new") + prepared(t, o, next, "s1") + objectWrites = len(o.writes) + _, err = RunCommit(ctx, nv, o, "v1", me, CommitRequest{Session: "s1", Prev: cur, Next: next, Position: h.Position + 1, State: StateLive}) + case "Abort": + _, err = RunAbort(ctx, nv, me, "s1") + case "BeginClean": + _, err = RunBeginClean(ctx, nv, me, "c2") + case "EndClean": + _, err = RunEndClean(ctx, nv, me, "c1") + case "RemoveUnreachable": + _, err = RemoveUnreachable(ctx, nv, r, o, me, "c1", 0, orphans) + case "DeleteSnapshot": + _, err = RunDeleteSnapshot(ctx, nv, "daily") + case "RetireSnapshot": + _, err = RunRetireSnapshot(ctx, nv, "daily", 1) + case "AddDependent": + _, err = RunAddDependent(ctx, nv, r, "daily", Dependent{Target: "t", TargetID: idFor("t")}) + case "ReleaseDependent": + _, err = RunReleaseDependent(ctx, nv, idFor("t")) + case "MarkDeleting": + _, err = RunMarkDeleting(ctx, nv, &fakeMaster{}) + case "MarkDeleted": + _, err = RunMarkDeleted(ctx, nv) + case "DeletedHeadCreate": + _, err = OperatorReleaseDependent(ctx, src, nv.memHead, r, idFor("v1")) + default: + t.Fatalf("no call for entry %q", entry) + } + after := 0 + if nv.memHead.h != nil { + after = int(nv.memHead.h.Gen) + } + return resultOf(err, after != before || len(o.writes) != objectWrites) +} + +// kernelExpected is the table, reviewed cell by cell against the spec +// (section 0's state x event table): every entry point refuses a deleting +// or deleted HEAD except the delete's own steps; a detached HEAD (a clean +// stop) refuses the holder's transaction steps until a new claim, and +// takes the operator's snapshot management (delete, retire, restore +// source) and a claim; an unclaimed HEAD takes only the first claim and +// the creates' replays. +var kernelExpected = map[string]map[string]string{ + "CreateVolume": {"absent": "write", "unclaimed": "noop", "idle": "noop", "snap": "noop", "clean": "noop", "detached": "noop", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "CreateTarget": {"absent": "write", "unclaimed": "Exists", "idle": "Exists", "snap": "Exists", "clean": "Exists", "detached": "Exists", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "StartHigher": {"absent": "HeadAbsent", "unclaimed": "write", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "StartHigherCannotStart": {"absent": "HeadAbsent", "unclaimed": "CannotStartFrom", "idle": "CannotStartFrom", "snap": "CannotStartFrom", "clean": "CannotStartFrom", "detached": "CannotStartFrom", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "StartOwnOtherFreshCannotStart": {"absent": "HeadAbsent", "unclaimed": "CannotStartFrom", "idle": "MissingLocalRoot", "snap": "MissingLocalRoot", "clean": "MissingLocalRoot", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "StartOwn": {"absent": "HeadAbsent", "unclaimed": "StaleLocalRoot", "idle": "noop", "snap": "write", "clean": "write", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "StartOwnOtherFresh": {"absent": "HeadAbsent", "unclaimed": "write", "idle": "MissingLocalRoot", "snap": "MissingLocalRoot", "clean": "MissingLocalRoot", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "StartOwnOtherOld": {"absent": "HeadAbsent", "unclaimed": "StaleLocalRoot", "idle": "StaleLocalRoot", "snap": "StaleLocalRoot", "clean": "StaleLocalRoot", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "Claim": {"absent": "HeadAbsent", "unclaimed": "write", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "Begin": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "write", "snap": "Busy", "clean": "Busy", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "Commit": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "noop", "snap": "write", "clean": "NoSession", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "CommitLower": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "NoSession", "snap": "PositionBehind", "clean": "NoSession", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "CommitNew": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "NoSession", "snap": "write", "clean": "NoSession", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "Abort": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "noop", "snap": "write", "clean": "NoSession", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "BeginClean": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "write", "snap": "Busy", "clean": "Busy", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "EndClean": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "noop", "snap": "NoSession", "clean": "write", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "RemoveUnreachable": {"absent": "HeadAbsent", "unclaimed": "NotHolder", "idle": "NoSession", "snap": "NoSession", "clean": "write", "detached": "Detached", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "DeleteSnapshot": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "RetireSnapshot": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "AddDependent": {"absent": "HeadAbsent", "unclaimed": "NoSnapshot", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "VolumeDeleting", "deleted": "VolumeDeleting"}, + "ReleaseDependent": {"absent": "HeadAbsent", "unclaimed": "noop", "idle": "write", "snap": "write", "clean": "write", "detached": "write", "deleting": "unreachable", "deleted": "unreachable"}, + "MarkDeleting": {"absent": "HeadAbsent", "unclaimed": "write", "idle": "write", "snap": "HolderActive", "clean": "HolderActive", "detached": "write", "deleting": "noop", "deleted": "noop"}, + "MarkDeleted": {"absent": "HeadAbsent", "unclaimed": "NotDeleting", "idle": "NotDeleting", "snap": "NotDeleting", "clean": "NotDeleting", "detached": "NotDeleting", "deleting": "write", "deleted": "noop"}, + "DeletedHeadCreate": {"absent": "write", "unclaimed": "TargetLive", "idle": "TargetLive", "snap": "TargetLive", "clean": "TargetLive", "detached": "TargetLive", "deleting": "noop", "deleted": "noop"}, +} + +// kernelUnreachable are cells no reachable HEAD gives (a deleting source +// has no dependents: MarkDeleting refuses one that has, TestDeleteVolume). +var kernelUnreachable = map[string]map[string]bool{"ReleaseDependent": {"deleting": true, "deleted": true}} + +func TestKernelTable(t *testing.T) { + for _, e := range kernelEntries { + for _, s := range kernelStates { + want, ok := kernelExpected[e][s] + if !ok { + t.Errorf("no expected result for %s on %s HEAD", e, s) + continue + } + if kernelUnreachable[e][s] { + if want != "unreachable" { + t.Errorf("%s on %s HEAD is unreachable; the table says %s", e, s, want) + } + continue + } + if got := kernelCell(t, s, e); got != want { + t.Errorf("%s on %s HEAD: %s; want %s", e, s, got, want) + } + } + } +} + +// kernelEntryFuncs maps each table row to the exported function it calls; +// kernelComposed are exported entry points that only compose the rows. +var kernelEntryFuncs = map[string]string{ + "CreateVolume": "CreateVolume", "CreateTarget": "CreateTarget", "StartHigher": "Start", "StartOwn": "Start", + "StartOwnOtherFresh": "Start", "StartOwnOtherOld": "Start", "StartHigherCannotStart": "Start", "StartOwnOtherFreshCannotStart": "Start", "Claim": "RunClaim", + "Begin": "RunBegin", "Commit": "RunCommit", "CommitNew": "RunCommit", "CommitLower": "RunCommit", "Abort": "RunAbort", "BeginClean": "RunBeginClean", "EndClean": "RunEndClean", + "RemoveUnreachable": "RemoveUnreachable", "DeleteSnapshot": "RunDeleteSnapshot", "RetireSnapshot": "RunRetireSnapshot", + "AddDependent": "RunAddDependent", "ReleaseDependent": "RunReleaseDependent", "MarkDeleting": "RunMarkDeleting", + "MarkDeleted": "RunMarkDeleted", "DeletedHeadCreate": "OperatorReleaseDependent", +} + +var kernelComposed = map[string]string{"DeleteVolume": "Reserve, MarkDeleting, ReleaseDependent per source, the objects, MarkDeleted"} + +// kernelStateConsts maps every State*/Act* constant to the table's +// columns it gives. +var kernelStateConsts = map[string][]string{ + "StateLive": {"unclaimed", "idle", "snap", "clean"}, "StateDetached": {"detached"}, "StateDeleting": {"deleting"}, "StateDeleted": {"deleted"}, + "ActIdle": {"unclaimed", "idle", "detached", "deleting", "deleted"}, "ActSnap": {"snap"}, "ActClean": {"clean"}, +} + +// TestKernelTable_Covers fails when a new entry point (an exported Run*, +// Create*, Start, Remove* or Operator* function) or a new HEAD state or +// activity constant appears without its row or column in the table. +func TestKernelTable_Covers(t *testing.T) { + funcs, consts := map[string]bool{}, map[string]bool{} + for fname, src := range packageSources(t, false) { + file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + switch x := d.(type) { + case *ast.FuncDecl: + n := x.Name.Name + if x.Recv == nil && (strings.HasPrefix(n, "Run") || strings.HasPrefix(n, "Create") || n == "Start" || strings.HasPrefix(n, "Remove") || strings.HasPrefix(n, "Operator") || n == "DeleteVolume") { + funcs[n] = true + } + case *ast.GenDecl: + for _, sp := range x.Specs { + vs, ok := sp.(*ast.ValueSpec) + if !ok { + continue + } + for _, id := range vs.Names { + n := id.Name + if (strings.HasPrefix(n, "State") && len(n) > 5) || (strings.HasPrefix(n, "Act") && len(n) > 3) { + consts[n] = true + } + } + } + } + } + } + rows := map[string]bool{} + for _, f := range kernelEntryFuncs { + rows[f] = true + } + for f := range funcs { + if !rows[f] && kernelComposed[f] == "" { + t.Errorf("entry point %s has no row in the kernel table", f) + } + } + for _, e := range kernelEntries { + if !funcs[kernelEntryFuncs[e]] { + t.Errorf("table row %s calls %s, which is not an entry point any more", e, kernelEntryFuncs[e]) + } + } + cols := map[string]bool{} + for _, s := range kernelStates { + cols[s] = true + } + for c := range consts { + cs, ok := kernelStateConsts[c] + if !ok { + t.Errorf("HEAD state or activity %s has no column in the kernel table", c) + } + for _, s := range cs { + if !cols[s] { + t.Errorf("%s gives column %s, which the table lacks", c, s) + } + } + } +} + +// TestKernelTable_Observe prints the observed table (go test -run +// Observe -v), the source the expected table was reviewed from. +func TestKernelTable_Observe(t *testing.T) { + if os.Getenv("KERNEL_TABLE_OBSERVE") == "" { + t.Skip("set KERNEL_TABLE_OBSERVE=1 to print the observed table") + } + var b strings.Builder + for _, e := range kernelEntries { + fmt.Fprintf(&b, "%q: {", e) + for i, s := range kernelStates { + if i > 0 { + b.WriteString(", ") + } + fmt.Fprintf(&b, "%q: %q", s, kernelCell(t, s, e)) + } + b.WriteString("},\n") + } + t.Log("\n" + b.String()) +} + +// A HEAD an older or broken writer left at position MaxUint64 can still be +// deleted: the guard against that position sits where a position is +// produced (Commit), not on every transition, so the operator is never +// stuck with a HEAD nothing can remove. +func TestKernelTable_HeadAtMaxPosition(t *testing.T) { + for _, c := range []struct{ state, entry, want string }{ + {"maxposition", "MarkDeleting", "write"}, + {"maxposition-deleting", "MarkDeleted", "write"}, + } { + if got := kernelCell(t, c.state, c.entry); got != c.want { + t.Errorf("%s on a HEAD at position MaxUint64 (%s): %s; want %s", c.entry, c.state, got, c.want) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/objects.go b/seaweed-block/core/frontend/chunkstore/layout/objects.go index 31e0b243b3..abc69f49a5 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/objects.go +++ b/seaweed-block/core/frontend/chunkstore/layout/objects.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sort" ) // ObjectMeta is what an object entry (chunk, segment, root) carries besides @@ -83,6 +84,33 @@ func EnsureObject(ctx context.Context, os ObjectStore, rel string, data []byte, return fmt.Errorf("layout: %s kept moving under %d attempts", rel, maxEnsureRounds) } +// PrepareRoot writes root for session: every segment it names (segs holds +// their bytes, by name) in shard order, then the root itself, each by +// EnsureObject, so the root is written only after all it names. It returns +// the root's name. A segment the root names that segs lacks is an error. +func PrepareRoot(ctx context.Context, os ObjectStore, root Root, segs map[SegName][]byte, session string) (RootName, error) { + shards := make([]uint64, 0, len(root.Segments)) + for sh := range root.Segments { + shards = append(shards, sh) + } + sort.Slice(shards, func(a, b int) bool { return shards[a] < shards[b] }) + for _, sh := range shards { + n := root.Segments[sh] + b, ok := segs[n] + if !ok { + return RootName{}, fmt.Errorf("layout: root names segment %s, its bytes are not given", n.Path()) + } + if err := EnsureObject(ctx, os, n.Path(), b, session); err != nil { + return RootName{}, err + } + } + rn, rb, err := NameRoot(root) + if err != nil { + return RootName{}, err + } + return rn, EnsureObject(ctx, os, rn.Path(), rb, session) +} + // ownedBySession reports whether rel exists, carries session as its writer // and is unmarked: an object a commit of that session may name. func ownedBySession(ctx context.Context, os ObjectStore, rel, session string) (bool, error) { diff --git a/seaweed-block/core/frontend/chunkstore/layout/prepare_root_test.go b/seaweed-block/core/frontend/chunkstore/layout/prepare_root_test.go new file mode 100644 index 0000000000..19ee5bb25d --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/prepare_root_test.go @@ -0,0 +1,58 @@ +package layout + +import ( + "context" + "strings" + "testing" +) + +// PrepareRoot writes every segment the root names, in shard order, and the +// root last, all under the session; a segment whose bytes are not given is +// refused before anything is written. +func TestPrepareRootWritesSegmentsThenRoot(t *testing.T) { + ctx := context.Background() + m := newMemObjects("/v") + manifest := map[uint64]Ref{} + for _, idx := range []uint64{2*ShardSize + 1, 3, ShardSize + 4} { + manifest[idx] = Ref{Owner: "v", OwnerID: VolumeID{1}, Chunk: NameChunk(idx, []byte{byte(idx)})} + } + root, segs, err := Build(manifest) + if err != nil { + t.Fatal(err) + } + rn, err := PrepareRoot(ctx, m, root, segs, "s1") + if err != nil { + t.Fatal(err) + } + want, _, _ := NameRoot(root) + if rn != want { + t.Fatalf("root name %v; want %v", rn, want) + } + if len(m.writes) != 4 { + t.Fatalf("writes %v; want three segments and the root", m.writes) + } + for i, sh := range []uint64{0, 1, 2} { + if !strings.HasSuffix(m.writes[i], root.Segments[sh].Path()) { + t.Fatalf("write %d is %q; want shard %d's segment (shard order)", i, m.writes[i], sh) + } + } + if !strings.HasSuffix(m.writes[3], rn.Path()) { + t.Fatalf("last write %q; want the root", m.writes[3]) + } + for _, p := range append([]string{rn.Path()}, root.Segments[0].Path(), root.Segments[1].Path(), root.Segments[2].Path()) { + if o := m.objs[m.full(p)]; o == nil || o.meta.Session != "s1" { + t.Fatalf("%s: %+v; want written by s1", p, o) + } + } + + m2 := newMemObjects("/v") + delete(segs, root.Segments[1]) + if _, err := PrepareRoot(ctx, m2, root, segs, "s2"); err == nil || len(m2.writes) > 1 { + t.Fatalf("a missing segment: %v after %v; want refused before the root", err, m2.writes) + } + for _, w := range m2.writes { + if strings.HasSuffix(w, rn.Path()) { + t.Fatalf("the root was written without all its segments: %v", m2.writes) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/read.go b/seaweed-block/core/frontend/chunkstore/layout/read.go index b05cfd6c84..a6a2cece3e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/read.go +++ b/seaweed-block/core/frontend/chunkstore/layout/read.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "path" + "sort" ) // ErrMissing reports an object a root reaches that is not in the store: a @@ -87,6 +88,64 @@ type Image struct { root Root } +// ReadRef reads the chunk ref names from the pool of its owner's +// directory (VolumeDir of its owner name and id), after checking that +// directory's VOLUME id is the reference's (ErrIdentity otherwise); the +// bytes are checked against the name. A missing chunk is ErrMissing. +func (r *Reader) ReadRef(ctx context.Context, ref Ref) ([]byte, error) { + if err := checkOwner(ref.Owner); err != nil { + return nil, err + } + dir := VolumeDir(ref.Owner, ref.OwnerID) + id, err := r.VolumeID(ctx, dir) + if err != nil { + return nil, err + } + if id != ref.OwnerID { + return nil, fmt.Errorf("%w: %s names id %s, VOLUME has %s", ErrIdentity, ref.Owner, ref.OwnerID, id) + } + return r.get(ctx, dir, ref.Chunk.Path(), ref.Chunk.Hash) +} + +// Shards returns the shards the image's root names, in order. +func (img *Image) Shards() []uint64 { + out := make([]uint64, 0, len(img.root.Segments)) + for sh := range img.root.Segments { + out = append(out, sh) + } + sort.Slice(out, func(a, b int) bool { return out[a] < out[b] }) + return out +} + +// AllShards selects every shard in EachRef. +const AllShards = ^uint64(0) + +// EachRef calls fn for every chunk reference root rn names in shard (or in +// every shard, AllShards), until fn returns false. A root or segment that +// cannot be read is an error, never a partial walk. +func (r *Reader) EachRef(ctx context.Context, rn RootName, shard uint64, fn func(index uint64, ref Ref) bool) error { + img, err := r.Open(ctx, rn) + if err != nil { + return err + } + shards := img.Shards() + if shard != AllShards { + shards = []uint64{shard} + } + for _, sh := range shards { + seg, _, err := img.Segment(ctx, sh) + if err != nil { + return err + } + for idx, ref := range seg.Chunks { + if !fn(idx, ref) { + return nil + } + } + } + return nil +} + // Open reads and checks the root rn. func (r *Reader) Open(ctx context.Context, rn RootName) (*Image, error) { b, err := r.get(ctx, r.vol, rn.Path(), rn.Hash) @@ -159,17 +218,9 @@ func (img *Image) Chunk(ctx context.Context, index uint64) (Chunk, error) { if zero { return Chunk{Zero: true}, nil } - dir := VolumeDir(ref.Owner, ref.OwnerID) - id, err := img.r.VolumeID(ctx, dir) + b, err := img.r.ReadRef(ctx, ref) if err != nil { - return Chunk{}, err - } - if id != ref.OwnerID { - return Chunk{}, fmt.Errorf("%w: chunk %d names %s id %s, VOLUME has %s", ErrIdentity, index, ref.Owner, ref.OwnerID, id) - } - b, err := img.r.get(ctx, dir, ref.Chunk.Path(), ref.Chunk.Hash) - if err != nil { - return Chunk{}, err + return Chunk{}, fmt.Errorf("chunk %d: %w", index, err) } return Chunk{Ref: ref, Data: b}, nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout/read_test.go b/seaweed-block/core/frontend/chunkstore/layout/read_test.go index be87aa5bb8..c2fcac8d0d 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/read_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/read_test.go @@ -255,7 +255,7 @@ func TestNewReader_RefusesBadInput(t *testing.T) { // putVolume writes vol's VOLUME record with its test id. func putVolume(t *testing.T, put func(dir, rel string, b []byte), name, dir string) { t.Helper() - b, err := Volume{ID: idFor(name), Name: name, Format: VolumeFormat}.Encode() + b, err := Volume{ID: idFor(name), Name: name, Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat}.Encode() if err != nil { t.Fatal(err) } @@ -269,7 +269,7 @@ func putVolume(t *testing.T, put func(dir, rel string, b []byte), name, dir stri func TestRead_ForeignChunkNeedsTheOwnersVolumeID(t *testing.T) { ctx := context.Background() s, rn, m := readFixture(t) - b, err := Volume{ID: idFor("src again"), Name: "src", Format: VolumeFormat}.Encode() + b, err := Volume{ID: idFor("src again"), Name: "src", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat}.Encode() if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index 46f67dd852..7636cf7706 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -93,34 +93,19 @@ func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectSt // names. A root or segment that cannot be read is an error: nothing is // removed on a partial view. func reachable(ctx context.Context, r *Reader, h Head, shard uint64) (map[ChunkName]bool, error) { - roots := map[RootName]bool{} - if h.Current != nil { - roots[*h.Current] = true - } - for _, s := range h.Snapshots { - roots[s.Root] = true - } own, err := r.VolumeID(ctx, r.vol) if err != nil { return nil, err } live := map[ChunkName]bool{} - for rn := range roots { - img, err := r.Open(ctx, rn) - if err != nil { - return nil, err - } - seg, ok, err := img.Segment(ctx, shard) - if err != nil { - return nil, err - } - if !ok { - continue - } - for _, ref := range seg.Chunks { + for _, rn := range HeadRoots(h) { + if err := r.EachRef(ctx, rn, shard, func(_ uint64, ref Ref) bool { if ref.OwnerID == own { live[ref.Chunk] = true } + return true + }); err != nil { + return nil, err } } return live, nil diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go index 75814f07c3..7d18cc8777 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go @@ -28,7 +28,7 @@ func removeFixture(t *testing.T) (*memObjects, *Head, []ChunkName, []ChunkName) data[path.Join(volRoot, c.Path())] = []byte(d) orphans = append(orphans, c) } - vb, err := Volume{ID: idFor("v1"), Name: "v1", Format: VolumeFormat}.Encode() + vb, err := Volume{ID: idFor("v1"), Name: "v1", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat}.Encode() if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/snapshots.go b/seaweed-block/core/frontend/chunkstore/layout/snapshots.go new file mode 100644 index 0000000000..6f0f22df2b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/snapshots.go @@ -0,0 +1,137 @@ +package layout + +import ( + "bytes" + "context" + "errors" + "fmt" + "sort" +) + +var ( + // ErrNoSnapshot: the named snapshot is not in HEAD. + ErrNoSnapshot = errors.New("layout: no such snapshot") + // ErrForeignSource: the snapshot names chunks of another volume, so it + // cannot be a restore source (dependency depth stays one). + ErrForeignSource = errors.New("layout: snapshot names another volume's chunks") + // ErrTooManyDependents: a restore from a snapshot that already has + // MaxDependents targets. + ErrTooManyDependents = errors.New("layout: snapshot has the most restore targets") +) + +// DeleteSnapshot is transition 9: the named snapshot is removed, refused +// while it has dependents (ErrHasDependents) or while the volume is being +// deleted. A detached volume (stopped cleanly) takes it: the snapshot table +// is not part of the stop's proof. A missing name is a replay. +func (h Head) DeleteSnapshot(name string) (next Head, changed bool, err error) { + if h.State != StateLive && h.State != StateDetached { + return Head{}, false, fmt.Errorf("%w: HEAD is %s", ErrVolumeDeleting, h.State) + } + s, ok := h.Snapshots[name] + if !ok { + return h, false, nil + } + if len(s.Dependents) > 0 { + return Head{}, false, fmt.Errorf("%w: snapshot %q has %d", ErrHasDependents, name, len(s.Dependents)) + } + next = h.clone() + delete(next.Snapshots, name) + return next, true, nil +} + +// AddDependent is transition 10 on the source's HEAD: target (its name and +// volume id) is recorded as a dependent of the named snapshot, with that +// snapshot's root, which must be root (the one checked to name no foreign +// chunk). A dependent already recorded is a replay. A detached volume +// (stopped cleanly) is a restore source like a live one. +func (h Head) AddDependent(name string, target Dependent, root RootName) (next Head, changed bool, err error) { + if h.State != StateLive && h.State != StateDetached { + return Head{}, false, fmt.Errorf("%w: HEAD is %s", ErrVolumeDeleting, h.State) + } + if target.TargetID.IsZero() { + return Head{}, false, errors.New("layout: AddDependent needs the target's volume id") + } + s, ok := h.Snapshots[name] + if !ok { + return Head{}, false, fmt.Errorf("%w: %q", ErrNoSnapshot, name) + } + if s.Root != root { + return Head{}, false, fmt.Errorf("%w: snapshot %q now has root %s, not the checked %s", ErrNoSnapshot, name, s.Root, root) + } + for _, d := range s.Dependents { + if d.TargetID == target.TargetID { + return h, false, nil + } + } + if len(s.Dependents) >= MaxDependents { + return Head{}, false, fmt.Errorf("%w: snapshot %q has %d; delete a restore target, or make it independent (release it), first", ErrTooManyDependents, name, len(s.Dependents)) + } + if h.dependents() >= MaxDependentsPerHead { + return Head{}, false, fmt.Errorf("%w: the volume's snapshots have %d; delete a restore target, or make it independent (release it), first", ErrTooManyDependents, h.dependents()) + } + next = h.clone() + s = next.Snapshots[name] + s.Dependents = append(s.Dependents, Dependent{Target: target.Target, TargetID: target.TargetID, Root: root}) + sort.Slice(s.Dependents, func(a, b int) bool { + return bytes.Compare(s.Dependents[a].TargetID[:], s.Dependents[b].TargetID[:]) < 0 + }) + next.Snapshots[name] = s + return next, true, nil +} + +// RunDeleteSnapshot applies DeleteSnapshot by one conditional update. +func RunDeleteSnapshot(ctx context.Context, st HeadStore, name string) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.DeleteSnapshot(name) }) +} + +// RunAddDependent checks that the named snapshot's root names no chunk of +// another volume (read through r, the source's reader), then records the +// dependent by one conditional update conditional on that root. +func RunAddDependent(ctx context.Context, st HeadStore, r *Reader, name string, target Dependent) (Head, error) { + h, found, err := st.ReadHead(ctx) + if err != nil { + return Head{}, err + } + if !found { + return Head{}, ErrHeadAbsent + } + s, ok := h.Snapshots[name] + if !ok { + return Head{}, fmt.Errorf("%w: %q", ErrNoSnapshot, name) + } + foreign, err := namesOtherThan(ctx, r, s.Root, h.VolumeID) + if err != nil { + return Head{}, err + } + if foreign { + return Head{}, fmt.Errorf("%w: %q", ErrForeignSource, name) + } + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.AddDependent(name, target, s.Root) }) +} + +// namesOtherThan reports whether root names a chunk owned by a volume +// other than own; an unreadable segment is an error. +func namesOtherThan(ctx context.Context, r *Reader, rn RootName, own VolumeID) (bool, error) { + other := false + err := r.EachRef(ctx, rn, AllShards, func(_ uint64, ref Ref) bool { other = ref.OwnerID != own; return !other }) + return other, err +} + +// ErrPinned: an automatic delete of a snapshot pinned at its time. +var ErrPinned = errors.New("layout: snapshot is pinned") + +// RetireSnapshot is transition 9 for the automatic caller (retention): as +// DeleteSnapshot, and also refused for a snapshot pinned at nowNs (class +// pinned, or an expiry not yet passed), checked on the HEAD the update +// replaces. +func (h Head) RetireSnapshot(name string, nowNs int64) (next Head, changed bool, err error) { + if s, ok := h.Snapshots[name]; ok && s.Meta.PinnedAt(nowNs) { + return Head{}, false, fmt.Errorf("%w: %q", ErrPinned, name) + } + return h.DeleteSnapshot(name) +} + +// RunRetireSnapshot applies RetireSnapshot by one conditional update. +func RunRetireSnapshot(ctx context.Context, st HeadStore, name string, nowNs int64) (Head, error) { + return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h.RetireSnapshot(name, nowNs) }) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/snapshots_test.go b/seaweed-block/core/frontend/chunkstore/layout/snapshots_test.go new file mode 100644 index 0000000000..23689e7b88 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/snapshots_test.go @@ -0,0 +1,328 @@ +package layout + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "sort" + "strings" + "testing" +) + +func TestDeleteSnapshot_Closure(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + h := idleHead() + h.Snapshots = map[string]Snapshot{"daily": {Root: rn}, "pinned": {Root: rn, Dependents: deps(rn, "t1")}} + next, changed, err := h.DeleteSnapshot("daily") + if err != nil || !changed || len(next.Snapshots) != 1 { + t.Fatalf("DeleteSnapshot: %+v %t %v", next.Snapshots, changed, err) + } + if _, ok := h.Snapshots["daily"]; !ok { + t.Fatal("DeleteSnapshot changed its receiver") + } + if _, changed, err := next.DeleteSnapshot("daily"); err != nil || changed { + t.Fatalf("DeleteSnapshot of a missing name: %t %v; want a replay", changed, err) + } + if _, _, err := h.DeleteSnapshot("pinned"); !errors.Is(err, ErrHasDependents) { + t.Fatalf("DeleteSnapshot with a dependent: %v; want ErrHasDependents", err) + } + d := deletingHead() + d.Snapshots = map[string]Snapshot{"daily": {Root: rn}} + if _, _, err := d.DeleteSnapshot("daily"); !errors.Is(err, ErrVolumeDeleting) { + t.Fatalf("DeleteSnapshot on a deleting volume: %v", err) + } +} + +func TestRunDeleteSnapshot_InterruptAtEveryStep(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + h := idleHead() + h.Snapshots = map[string]Snapshot{"daily": {Root: rn}} + interruptHead(t, h, func(st HeadStore) error { _, err := RunDeleteSnapshot(context.Background(), st, "daily"); return err }, + func(t *testing.T, h Head) { + if _, ok := h.Snapshots["daily"]; ok { + t.Fatal("snapshot still in HEAD") + } + }) +} + +func TestAddDependent_Closure(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + h := idleHead() + h.Snapshots = map[string]Snapshot{"daily": {Root: rn}} + t1 := Dependent{Target: "t1", TargetID: idFor("t1")} + next, changed, err := h.AddDependent("daily", t1, rn) + if err != nil || !changed { + t.Fatalf("AddDependent: %v", err) + } + if d := next.Snapshots["daily"].Dependents; len(d) != 1 || d[0].TargetID != idFor("t1") || d[0].Root != rn { + t.Fatalf("dependents %+v; want t1 with the snapshot's root", d) + } + if _, err := next.Encode(); err != nil { + t.Fatalf("HEAD after AddDependent does not encode: %v", err) + } + if _, changed, err := next.AddDependent("daily", t1, rn); err != nil || changed { + t.Fatalf("AddDependent again: %t %v; want a replay", changed, err) + } + if _, _, err := h.AddDependent("weekly", t1, rn); !errors.Is(err, ErrNoSnapshot) { + t.Fatalf("AddDependent of a missing snapshot: %v", err) + } + if _, _, err := h.AddDependent("daily", t1, RootName{Hash: Sum([]byte("other"))}); !errors.Is(err, ErrNoSnapshot) { + t.Fatalf("AddDependent on a snapshot whose root changed since the check: %v", err) + } + if _, _, err := h.AddDependent("daily", Dependent{Target: "t1"}, rn); err == nil { + t.Fatal("AddDependent without the target's id accepted") + } + d := deletingHead() + d.Snapshots = map[string]Snapshot{"daily": {Root: rn}} + if _, _, err := d.AddDependent("daily", t1, rn); !errors.Is(err, ErrVolumeDeleting) { + t.Fatalf("AddDependent on a deleting volume: %v", err) + } +} + +// RunAddDependent refuses a snapshot that names another volume's chunks: +// a restore target of a restore target would make the dependency deeper +// than one. +func TestRunAddDependent_RefusesAForeignSource(t *testing.T) { + ctx := context.Background() + o, h, _, _ := removeFixture(t) + foreign := manifest(Ref{Owner: "src", OwnerID: idFor("src"), Chunk: NameChunk(1, []byte("x"))}) + data := map[string][]byte{} + frn := writeImage(t, data, foreign, nil) + for p, b := range data { + o.objs[p] = &memObject{data: b, meta: ObjectMeta{Session: "s0"}} + } + h.Snapshots["restored"] = Snapshot{Root: frn} + r, err := NewReader(removeBase, "v1", o.fetch) + if err != nil { + t.Fatal(err) + } + st := &memHead{h: h} + if _, err := RunAddDependent(ctx, st, r, "restored", Dependent{Target: "t", TargetID: idFor("t")}); !errors.Is(err, ErrForeignSource) || st.updates != 0 { + t.Fatalf("AddDependent on a snapshot naming foreign chunks: %v (%d writes); want ErrForeignSource", err, st.updates) + } + if _, err := RunAddDependent(ctx, st, r, "daily", Dependent{Target: "t", TargetID: idFor("t")}); err != nil || len(st.h.Snapshots["daily"].Dependents) != 1 { + t.Fatalf("AddDependent on an own snapshot: %v", err) + } +} + +func TestRunAddDependent_InterruptAtEveryStep(t *testing.T) { + o, h, _, _ := removeFixture(t) + r, err := NewReader(removeBase, "v1", o.fetch) + if err != nil { + t.Fatal(err) + } + h.Activity = Activity{Kind: ActIdle} + interruptHead(t, *h, func(st HeadStore) error { + _, err := RunAddDependent(context.Background(), st, r, "daily", Dependent{Target: "t", TargetID: idFor("t")}) + return err + }, func(t *testing.T, h Head) { + if d := h.Snapshots["daily"].Dependents; len(d) != 1 || d[0].TargetID != idFor("t") { + t.Fatalf("dependents %+v", d) + } + }) +} + +func TestRetireSnapshot_Closure(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + h := idleHead() + h.Snapshots = map[string]Snapshot{ + "auto": {Root: rn, Meta: SnapshotMeta{CreatedNs: 1, Class: ClassSemantic}}, + "pinned": {Root: rn, Meta: SnapshotMeta{CreatedNs: 1, Class: ClassPinned}}, + "held": {Root: rn, Meta: SnapshotMeta{CreatedNs: 1, ExpiresNs: 100}}, + "depends": {Root: rn, Dependents: deps(rn, "t1")}, + } + if next, changed, err := h.RetireSnapshot("auto", 50); err != nil || !changed || len(next.Snapshots) != 3 { + t.Fatalf("retire an unpinned snapshot: %t %v", changed, err) + } + for name, now := range map[string]int64{"pinned": 50, "held": 50} { + if _, _, err := h.RetireSnapshot(name, now); !errors.Is(err, ErrPinned) { + t.Errorf("retire %s at %d: %v; want ErrPinned", name, now, err) + } + } + if _, changed, err := h.RetireSnapshot("held", 100); err != nil || !changed { + t.Fatalf("retire after the expiry: %t %v", changed, err) + } + if _, _, err := h.RetireSnapshot("depends", 50); !errors.Is(err, ErrHasDependents) { + t.Fatalf("retire a depended-on snapshot: %v", err) + } + if _, changed, err := h.RetireSnapshot("gone", 50); err != nil || changed { + t.Fatalf("retire a missing name: %t %v; want a replay", changed, err) + } + // The operator's delete is not refused by a pin. + if _, changed, err := h.DeleteSnapshot("pinned"); err != nil || !changed { + t.Fatalf("operator delete of a pinned snapshot: %t %v", changed, err) + } +} + +func TestRunRetireSnapshot_InterruptAtEveryStep(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + h := idleHead() + h.Snapshots = map[string]Snapshot{"auto": {Root: rn, Meta: SnapshotMeta{CreatedNs: 1}}} + interruptHead(t, h, func(st HeadStore) error { _, err := RunRetireSnapshot(context.Background(), st, "auto", 2); return err }, + func(t *testing.T, h Head) { + if _, ok := h.Snapshots["auto"]; ok { + t.Fatal("snapshot still in HEAD") + } + }) +} + +// A snapshot's retention facts are written by the commit that creates the +// name, kept across every later transition and encoding, never changed by +// a replay; invalid facts are refused. +func TestSnapshotMeta_WrittenOnceByTheCommit(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + h := idleHead() + h.Activity = Activity{Kind: ActSnap, Session: "s1"} + me := HolderID{Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID} + meta := SnapshotMeta{CreatedNs: 7, Class: ClassScheduled, ExpiresNs: 9, Labels: map[string]string{"swb.schedule.keep": "3"}} + next, _, err := h.Commit(me, "s1", rn, 1, "daily", meta, StateLive) + if err != nil { + t.Fatal(err) + } + b, err := next.Encode() + if err != nil { + t.Fatal(err) + } + back, err := DecodeHead(b, 2, next.VolumeID) + if err != nil || back.Snapshots["daily"].Meta.Class != ClassScheduled || back.Snapshots["daily"].Meta.Labels["swb.schedule.keep"] != "3" || back.Snapshots["daily"].Meta.CreatedNs != 7 { + t.Fatalf("meta after encode/decode: %+v %v", back.Snapshots["daily"], err) + } + cl := back.clone() + meta.Labels["swb.schedule.keep"] = "99" + if cl.Snapshots["daily"].Meta.Labels["swb.schedule.keep"] != "3" || next.Snapshots["daily"].Meta.Labels["swb.schedule.keep"] != "3" { + t.Fatal("the caller's labels map aliases HEAD's") + } + again, changed, err := next.Commit(me, "s1", rn, 1, "daily", SnapshotMeta{Class: ClassPinned}, StateLive) + if err != nil || changed || again.Snapshots["daily"].Meta.Class != ClassScheduled { + t.Fatalf("a replay with other facts: %t %v %+v; want a replay keeping the first facts", changed, err, again.Snapshots["daily"].Meta) + } + bad := map[string]SnapshotMeta{ + "class": {Class: "forever"}, + "time": {CreatedNs: -1}, + "labels": {Labels: map[string]string{"a": "1", "b": "2", "c": "3", "d": "4", "e": "5"}}, + "long label": {Labels: map[string]string{"k": strings.Repeat("v", MaxLabelValueBytes+1)}}, + } + for name, m := range bad { + if _, _, err := h.Commit(me, "s1", rn, 1, "x", m, StateLive); !errors.Is(err, ErrMalformed) { + t.Errorf("commit with a bad %s: %v; want ErrMalformed", name, err) + } + } +} + +// HEAD at its snapshot cap, each snapshot with the largest facts, stays +// inline (measured and bounded here). +func TestHead_SizeAtTheSnapshotCap(t *testing.T) { + h := idleHead() + h.Snapshots = map[string]Snapshot{} + fill := func(c byte, n int) string { return strings.Repeat(string(c), n) } + for i := 0; i < MaxSnapshots; i++ { + labels := map[string]string{} + for j := 0; j < MaxSnapshotLabels; j++ { + labels[fmt.Sprintf("%s%02d", fill('k', MaxLabelKeyBytes-2), j)] = fill('v', MaxLabelValueBytes) + } + name := fmt.Sprintf("%s%04d", fill('n', MaxSnapshotNameBytes-4), i) + rn := RootName{Hash: Sum([]byte(name))} + var ds []Dependent + for d := 0; d < MaxDependents && i < MaxDependentsPerHead/MaxDependents; d++ { + tn := fmt.Sprintf("%s%02d", fill('t', 62), d) + ds = append(ds, Dependent{Target: tn, TargetID: idFor(tn + name), Root: rn}) + } + sort.Slice(ds, func(a, b int) bool { return bytes.Compare(ds[a].TargetID[:], ds[b].TargetID[:]) < 0 }) + h.Snapshots[name] = Snapshot{Root: rn, Meta: SnapshotMeta{CreatedNs: 1 << 62, Class: ClassScheduled, ExpiresNs: 1 << 62, Labels: labels}, Dependents: ds} + } + b, err := h.Encode() + if err != nil { + t.Fatal(err) + } + t.Logf("HEAD at %d snapshots with the largest names and labels and %d dependents: %d bytes", MaxSnapshots, MaxDependentsPerHead, len(b)) + if len(b) > 16<<10 { + t.Fatalf("HEAD at the cap is %d bytes; want at most 16 KiB", len(b)) + } +} + +// The bounds are refused where they enter (snapshot create, restore) and +// the codec refuses an oversized HEAD as a backstop. +func TestHead_BoundsRefused(t *testing.T) { + rn := RootName{Hash: Sum([]byte("r"))} + h := idleHead() + h.Activity = Activity{Kind: ActSnap, Session: "s1"} + me := HolderID{Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID} + if _, _, err := h.Commit(me, "s1", rn, 1, strings.Repeat("n", MaxSnapshotNameBytes+1), SnapshotMeta{}, StateLive); !errors.Is(err, ErrMalformed) { + t.Fatalf("a %d-byte snapshot name: %v", MaxSnapshotNameBytes+1, err) + } + for name, m := range map[string]SnapshotMeta{ + "long key": {Labels: map[string]string{strings.Repeat("k", MaxLabelKeyBytes+1): "v"}}, + "long value": {Labels: map[string]string{"k": strings.Repeat("v", MaxLabelValueBytes+1)}}, + } { + if _, _, err := h.Commit(me, "s1", rn, 1, "x", m, StateLive); !errors.Is(err, ErrMalformed) { + t.Errorf("%s: %v", name, err) + } + } + idle := idleHead() + idle.Snapshots = map[string]Snapshot{"daily": {Root: rn}} + for d := 0; d < MaxDependents; d++ { + var err error + if idle, _, err = idle.AddDependent("daily", Dependent{Target: fmt.Sprintf("t%d", d), TargetID: idFor(fmt.Sprintf("t%d", d))}, rn); err != nil { + t.Fatal(err) + } + } + if _, _, err := idle.AddDependent("daily", Dependent{Target: "t9", TargetID: idFor("t9")}, rn); !errors.Is(err, ErrTooManyDependents) || !strings.Contains(err.Error(), "make it independent") { + t.Fatalf("a fifth restore target: %v; want ErrTooManyDependents naming the cure", err) + } + spread := idleHead() + spread.Snapshots = map[string]Snapshot{} + for i := 0; i < MaxDependentsPerHead/MaxDependents+1; i++ { + spread.Snapshots[fmt.Sprintf("s%d", i)] = Snapshot{Root: rn} + } + k := 0 + for i := 0; i < MaxDependentsPerHead/MaxDependents; i++ { + for d := 0; d < MaxDependents; d++ { + tn := fmt.Sprintf("t%d", k) + k++ + var err error + if spread, _, err = spread.AddDependent(fmt.Sprintf("s%d", i), Dependent{Target: tn, TargetID: idFor(tn)}, rn); err != nil { + t.Fatal(err) + } + } + } + last := fmt.Sprintf("s%d", MaxDependentsPerHead/MaxDependents) + if _, _, err := spread.AddDependent(last, Dependent{Target: "tx", TargetID: idFor("tx")}, rn); !errors.Is(err, ErrTooManyDependents) { + t.Fatalf("restore target %d of the volume: %v; want ErrTooManyDependents", MaxDependentsPerHead+1, err) + } + full := idleHead() + full.Activity = Activity{Kind: ActSnap, Session: "s1"} + full.Snapshots = map[string]Snapshot{} + for i := 0; i < MaxSnapshots; i++ { + full.Snapshots[fmt.Sprintf("s%d", i)] = Snapshot{Root: rn} + } + if _, _, err := full.Commit(me, "s1", rn, 1, "one-more", SnapshotMeta{}, StateLive); !errors.Is(err, ErrTooManySnapshots) || !strings.Contains(err.Error(), "let retention prune") { + t.Fatalf("snapshot %d of the volume: %v; want ErrTooManySnapshots naming the cure", MaxSnapshots+1, err) + } + big := idleHead() + big.Snapshots = map[string]Snapshot{} + for i := 0; i < 1000; i++ { + n := fmt.Sprintf("%060d", i) + big.Snapshots[n] = Snapshot{Root: rn} + } + if _, err := big.Encode(); err == nil { + t.Fatal("a HEAD over its bounds encoded") + } +} + +// Reachability, removal and the volume delete never read a snapshot's +// retention facts: wall-clock times and classes decide policy only. +func TestGuard_SafetyIgnoresSnapshotMeta(t *testing.T) { + for _, f := range []string{"remove.go", "read.go", "delete.go", "objects.go", "create.go"} { + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for _, banned := range []string{".Meta", "SnapshotMeta", "CreatedNs", "ExpiresNs", "PinnedAt"} { + if strings.Contains(string(b), banned) { + t.Errorf("%s uses %s: reachability, removal and delete must not read retention facts", f, banned) + } + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index 70e27297d9..271488fe14 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -22,7 +22,7 @@ func TestTransitions_RefuseAStaleHolder(t *testing.T) { steps := map[string]func(Head, HolderID) error{ "Begin": func(h Head, c HolderID) error { _, _, err := h.Begin(c, "s"); return err }, "Abort": func(h Head, c HolderID) error { _, _, err := h.Abort(c, "s"); return err }, - "Commit": func(h Head, c HolderID) error { _, _, err := h.Commit(c, "s", rn, 1, "", StateLive); return err }, + "Commit": func(h Head, c HolderID) error { _, _, err := h.Commit(c, "s", rn, 1, "", SnapshotMeta{}, StateLive); return err }, "BeginClean": func(h Head, c HolderID) error { _, _, err := h.BeginClean(c, "c"); return err }, "EndClean": func(h Head, c HolderID) error { _, _, err := h.EndClean(c, "c"); return err }, "Claim": func(h Head, c HolderID) error { _, _, err := h.Claim(c); return err }, @@ -85,7 +85,19 @@ func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) { // id are its cases in start_test.go (TestStart_Refusals and the same-host // forced successor); startCheck is Start's check, run again inside the // claim (TestStart_ValidatesAgainstTheHeadItUpdates). - covered := map[string]bool{"RemoveUnreachable": true, "Start": true, "startCheck": true} + // DetachedBy: my own committed, idle detach proves nothing to a stale + // caller in any one dimension. + mine := Head{Gen: 1, State: StateDetached, Epoch: me.Epoch, Holder: me.Holder, ClaimID: me.ClaimID} + mine.Activity.Kind = ActIdle + if !DetachedBy(mine, me) { + t.Fatal("DetachedBy refused the holder's own detach") + } + for who, c := range callers { + if DetachedBy(mine, c) { + t.Errorf("DetachedBy accepted %s", who) + } + } + covered := map[string]bool{"RemoveUnreachable": true, "Start": true, "startCheck": true, "DetachedBy": true} var missing []string for fname, src := range packageSources(t, false) { file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) diff --git a/seaweed-block/core/frontend/chunkstore/layout/start.go b/seaweed-block/core/frontend/chunkstore/layout/start.go index d312c5a67a..4303b4d768 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/start.go +++ b/seaweed-block/core/frontend/chunkstore/layout/start.go @@ -13,6 +13,9 @@ var ( // ErrStaleLocalRoot: the local root belongs to an earlier claim of this // server (a same-host forced move published past it). ErrStaleLocalRoot = errors.New("layout: local root is from an earlier claim") + // ErrCannotStartFrom: the step the local root takes after its claim + // could not succeed on this HEAD; nothing is written. + ErrCannotStartFrom = errors.New("layout: the local root cannot start from this HEAD") ) // StaleLocalRootCure is the way back a stale-root refusal names: after a @@ -30,9 +33,16 @@ const MissingLocalRootCure = "check for a wrong or unmounted data directory; if // reported non-fresh before that, its position below HEAD's would be // refused as an old copy. type LocalRoot struct { + Geometry ClaimID string Fresh bool Position uint64 // the position the local root holds synced + // CanStartFrom answers, before the claim, whether the step the local + // root takes after it (seed at HEAD's position, attach a completed + // base, or nothing) can succeed on this HEAD: nil, or the refusal that + // step would give. A fresh root without it is refused: the question is + // never skipped. + CanStartFrom func(h Head) error } // Start is the HEAD side of a holder's start on the line it was granted @@ -47,7 +57,12 @@ type LocalRoot struct { // older than HEAD's image and is ErrStaleLocalRoot. An older epoch, // another server at HEAD's epoch, a deleting volume and an absent HEAD // are refused. -func Start(ctx context.Context, st HeadStore, lease LeaseWait, line HolderID, local LocalRoot) (Head, error) { +type StartStore interface { + HeadStore + ReadVolumeRecord(context.Context) (Volume, bool, error) +} + +func Start(ctx context.Context, st StartStore, lease LeaseWait, line HolderID, local LocalRoot) (Head, error) { if local.ClaimID == "" { return Head{}, errors.New("layout: start needs the local root's claim id") } @@ -58,11 +73,37 @@ func Start(ctx context.Context, st HeadStore, lease LeaseWait, line HolderID, lo if !found { return Head{}, ErrHeadAbsent } + v, present, err := st.ReadVolumeRecord(ctx) + if err != nil { + return Head{}, err + } + if !present { + return Head{}, ErrMissing + } + if v.ID != h.VolumeID { + return Head{}, ErrIdentity + } + if err := v.Geometry.Check(); err != nil { + return Head{}, err + } + if local.Geometry != v.Geometry { + return Head{}, fmt.Errorf("%w: local %+v differs from VOLUME %+v", ErrGeometryMismatch, local.Geometry, v.Geometry) + } if err := startCheck(h, line, local); err != nil { return Head{}, err } if h.Epoch == line.Epoch && h.Holder == line.Holder && h.State == StateLive { - return h, nil // HEAD holds this root's claim id: it continues + // HEAD holds this root's claim id: it continues, after ending the + // transaction the previous process of this claim left open (never a + // new one beside it): its session is rolled back, its cleaning ended. + me := HolderID{Epoch: line.Epoch, Holder: line.Holder, ClaimID: local.ClaimID} + switch h.Activity.Kind { + case ActSnap: + return RunAbort(ctx, st, me, h.Activity.Session) + case ActClean: + return RunEndClean(ctx, st, me, h.Activity.Session) + } + return h, nil } // The claim re-checks the local root against the very HEAD it updates: // another lineage's claim or a higher published position after the @@ -76,24 +117,42 @@ func Start(ctx context.Context, st HeadStore, lease LeaseWait, line HolderID, lo // and server a root without HEAD's claim id, and above HEAD's epoch a // non-fresh root of another lineage. func startCheck(h Head, line HolderID, local LocalRoot) error { - if h.State == StateDetached && line.Epoch == h.Epoch { - return ErrDetached - } - if !local.Fresh && local.ClaimID == h.ClaimID && local.Position < h.Position && line.Epoch >= h.Epoch { - return fmt.Errorf("%w (%w): the local root holds position %d, HEAD published %d: an old copy of this lineage", ErrStaleLocalRoot, ErrNotHolder, local.Position, h.Position) - } - if h.Epoch == line.Epoch && h.Holder == line.Holder && h.State == StateLive { - switch { - case h.ClaimID == local.ClaimID: - return nil - case local.Fresh: - return fmt.Errorf("%w at epoch %d: %s", ErrMissingLocalRoot, h.Epoch, MissingLocalRootCure) - default: - return fmt.Errorf("%w (%w): HEAD holds claim %q at epoch %d, the local root carries %q: %s", ErrStaleLocalRoot, ErrNotHolder, h.ClaimID, h.Epoch, local.ClaimID, StaleLocalRootCure) + if err := func() error { + if h.State == StateDetached && line.Epoch == h.Epoch { + return ErrDetached } + if !local.Fresh && local.ClaimID == h.ClaimID && local.Position < h.Position && line.Epoch >= h.Epoch { + return fmt.Errorf("%w (%w): the local root holds position %d, HEAD published %d: an old copy of this lineage", ErrStaleLocalRoot, ErrNotHolder, local.Position, h.Position) + } + if h.Epoch == line.Epoch && h.Holder == line.Holder && h.State == StateLive { + switch { + case h.ClaimID == local.ClaimID: + return nil + case local.Fresh: + return fmt.Errorf("%w at epoch %d: %s", ErrMissingLocalRoot, h.Epoch, MissingLocalRootCure) + default: + return fmt.Errorf("%w (%w): HEAD holds claim %q at epoch %d, the local root carries %q: %s", ErrStaleLocalRoot, ErrNotHolder, h.ClaimID, h.Epoch, local.ClaimID, StaleLocalRootCure) + } + } + if line.Epoch > h.Epoch && !local.Fresh && local.ClaimID != h.ClaimID { + return fmt.Errorf("%w (%w): the local root carries claim %q, HEAD's lineage is %q: %s", ErrStaleLocalRoot, ErrNotHolder, local.ClaimID, h.ClaimID, StaleLocalRootCure) + } + return nil + }(); err != nil { + return err } - if line.Epoch > h.Epoch && !local.Fresh && local.ClaimID != h.ClaimID { - return fmt.Errorf("%w (%w): the local root carries claim %q, HEAD's lineage is %q: %s", ErrStaleLocalRoot, ErrNotHolder, local.ClaimID, h.ClaimID, StaleLocalRootCure) + // One question before any claim: can the step this root takes after it + // succeed on this HEAD? (A deleting volume is refused by the claim as + // such.) A fresh root must ask it. + if h.State != StateDeleting && h.State != StateDeleted { + if local.CanStartFrom == nil && local.Fresh { + return fmt.Errorf("%w: a fresh local root must say whether it can start from HEAD", ErrCannotStartFrom) + } + if local.CanStartFrom != nil { + if err := local.CanStartFrom(h); err != nil { + return fmt.Errorf("%w: HEAD position %d: %w", ErrCannotStartFrom, h.Position, err) + } + } } return nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout/start_any_test.go b/seaweed-block/core/frontend/chunkstore/layout/start_any_test.go new file mode 100644 index 0000000000..0a408bad2d --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/start_any_test.go @@ -0,0 +1,5 @@ +package layout + +// anyStart is a local root that can start from any HEAD: these tests do +// not model the local store (start_seed_test does). +func anyStart(Head) error { return nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout/start_seed_test.go b/seaweed-block/core/frontend/chunkstore/layout/start_seed_test.go new file mode 100644 index 0000000000..c8e592a39a --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/start_seed_test.go @@ -0,0 +1,104 @@ +package layout + +import ( + "context" + "errors" + "testing" +) + +// A fresh local root seeds its frontier at HEAD's position once it starts, +// so Start refuses a position its store cannot take BEFORE any claim: a +// refusal writes nothing. The rule comes from the local store +// (LocalRoot.CanStartFrom); here a store that takes positions below 5. (A +// position of MaxUint64 cannot be written at all: the Encode test below.) + +var seedGeometry = Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096} + +func startsBelow5(h Head) error { + if h.Position >= 5 { + return errors.New("the store cannot seed this position") + } + return nil +} + +func TestStart_FreshRootRefusesAHeadItCannotStartFromBeforeClaim(t *testing.T) { + unclaimed := Unclaimed(idFor("v1"), nil) + unclaimed.Gen = 1 + for name, c := range map[string]struct { + h Head + line HolderID + }{ + "higher epoch": {startHead(3, "s1/r1", "k-old"), HolderID{Epoch: 4, Holder: "s2/r1"}}, + "unclaimed": {unclaimed, HolderID{Epoch: 1, Holder: "s1/r1"}}, + } { + t.Run(name, func(t *testing.T) { + local := LocalRoot{Geometry: seedGeometry, ClaimID: "k-new", Fresh: true, CanStartFrom: startsBelow5} + // control: a position the store can take is claimed + ok := c.h + ok.Position = 3 + st, _, err := start(t, ok, c.line, local) + if err != nil || st.updates == 0 { + t.Fatalf("control, position 3: %v (%d writes); want a claim", err, st.updates) + } + bad := c.h + bad.Position = 9 + before := bad + st, _, err = start(t, bad, c.line, local) + if !errors.Is(err, ErrCannotStartFrom) { + t.Fatalf("HEAD position 9: %v; want ErrCannotStartFrom", err) + } + if st.updates != 0 || st.h.Gen != before.Gen || st.h.Epoch != before.Epoch || st.h.ClaimID != before.ClaimID { + t.Fatalf("a refused start wrote HEAD: %+v (%d writes)", st.h, st.updates) + } + }) + } +} + +// The check is never skipped: a fresh root that does not say which +// positions it can seed is refused, HEAD unchanged. +func TestStart_FreshRootWithoutASeedRuleIsRefused(t *testing.T) { + st, _, err := start(t, startHead(3, "s1/r1", "k-old"), HolderID{Epoch: 4, Holder: "s2/r1"}, LocalRoot{Geometry: seedGeometry, ClaimID: "k-new", Fresh: true}) + if !errors.Is(err, ErrCannotStartFrom) || st.updates != 0 { + t.Fatalf("fresh root without CanStartFrom: %v (%d writes); want ErrCannotStartFrom, no write", err, st.updates) + } +} + +// The claim re-checks against the very HEAD it updates: a position that +// the root can no longer start from, between Start's read and the claim, is refused by the +// claim's own condition, HEAD unchanged. +func TestStart_TheClaimRechecksTheSeedRule(t *testing.T) { + h := startHead(3, "s1/r1", "k-old") + h.Position = 9 + st := &memHead{h: &h} + calls := 0 + local := LocalRoot{Geometry: seedGeometry, ClaimID: "k-new", Fresh: true, CanStartFrom: func(Head) error { + calls++ + if calls > 1 { + return errors.New("the store changed") + } + return nil + }} + _, err := Start(context.Background(), st, &fakeLease{ended: true}, HolderID{Epoch: 4, Holder: "s2/r1"}, local) + if !errors.Is(err, ErrCannotStartFrom) || st.updates != 0 || calls < 2 { + t.Fatalf("claim re-check: %v (%d writes, %d checks); want the claim's own check to refuse, no write", err, st.updates, calls) + } +} + +// No commit produces a position with no room for a next LSN; a HEAD already +// at that position (an older writer) keeps it and is not re-checked. +func TestCommit_RefusesToProduceAPositionWithNoNextLSN(t *testing.T) { + me := HolderID{Epoch: 3, Holder: "s1/r1", ClaimID: "k3"} + h := startHead(3, "s1/r1", "k3") + h.State, h.Activity, h.Position = StateLive, Activity{Kind: ActSnap, Session: "s1"}, 9 + root := RootName{Hash: Hash{1}} + if _, _, err := h.Commit(me, "s1", root, 10, "", SnapshotMeta{}, StateLive); err != nil { + t.Fatalf("control, commit at 10: %v", err) + } + if _, _, err := h.Commit(me, "s1", root, ^uint64(0), "", SnapshotMeta{}, StateLive); !errors.Is(err, ErrNoNextPosition) { + t.Fatalf("commit at MaxUint64: %v; want ErrNoNextPosition", err) + } + h.Position = ^uint64(0) + if _, _, err := h.Commit(me, "s1", root, ^uint64(0), "", SnapshotMeta{}, StateDetached); err != nil { + t.Fatalf("a HEAD already at MaxUint64 stops there (detach): %v", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/start_test.go b/seaweed-block/core/frontend/chunkstore/layout/start_test.go index b2c4ef8b01..7b2c0af259 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/start_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/start_test.go @@ -29,7 +29,7 @@ func start(t *testing.T, h Head, line HolderID, local LocalRoot) (*memHead, Head func TestStart_OwnEpochFreshRootRefusedBeforeClaim(t *testing.T) { h := startHead(3, "s1/r1", "k-old") line := HolderID{Epoch: 3, Holder: "s1/r1"} - fresh := LocalRoot{ClaimID: "k-new", Fresh: true} + fresh := LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k-new", Fresh: true, CanStartFrom: anyStart} st, _, err := start(t, h, line, fresh) if !errors.Is(err, ErrMissingLocalRoot) { t.Fatalf("own-epoch fresh root: %v; want ErrMissingLocalRoot", err) @@ -50,7 +50,7 @@ func TestStart_OwnEpochFreshRootRefusedBeforeClaim(t *testing.T) { // The same root restarting at its own epoch continues: its marker is the // claim id HEAD holds. No claim is written. func TestStart_OwnEpochSameRootContinues(t *testing.T) { - st, got, err := start(t, startHead(3, "s1/r1", "k3"), HolderID{Epoch: 3, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3"}) + st, got, err := start(t, startHead(3, "s1/r1", "k3"), HolderID{Epoch: 3, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k3"}) if err != nil || st.updates != 0 || got.ClaimID != "k3" { t.Fatalf("same-root restart: %+v %v (%d writes); want continue without a write", got, err, st.updates) } @@ -60,7 +60,7 @@ func TestStart_OwnEpochSameRootContinues(t *testing.T) { // with the same marker: HEAD holds that claim id at this epoch, so it // continues. func TestStart_LostClaimReplyContinues(t *testing.T) { - st, got, err := start(t, startHead(5, "s1/r1", "k5"), HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{ClaimID: "k5", Fresh: true}) + st, got, err := start(t, startHead(5, "s1/r1", "k5"), HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k5", Fresh: true, CanStartFrom: anyStart}) if err != nil || st.updates != 0 || got.Epoch != 5 { t.Fatalf("restart after a lost claim reply: %+v %v (%d writes)", got, err, st.updates) } @@ -74,7 +74,7 @@ func TestStart_SameHostForcedSuccessorRefusesTheRemountedOldRoot(t *testing.T) { rn := RootName{Hash: Sum([]byte("successor image"))} h := startHead(4, "s1/r1", "k4") h.Current = &rn - st, _, err := start(t, h, HolderID{Epoch: 4, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3"}) + st, _, err := start(t, h, HolderID{Epoch: 4, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k3"}) if !errors.Is(err, ErrStaleLocalRoot) || !errors.Is(err, ErrNotHolder) { t.Fatalf("remounted old root: %v; want ErrStaleLocalRoot and fenced (ErrNotHolder)", err) } @@ -87,7 +87,7 @@ func TestStart_SameHostForcedSuccessorRefusesTheRemountedOldRoot(t *testing.T) { // claims with its marker's claim id. func TestStart_FreshRootAtHigherEpochClaims(t *testing.T) { for _, server := range []string{"s1/r1", "s2/r1"} { - st, got, err := start(t, startHead(3, "s1/r1", "k3"), HolderID{Epoch: 4, Holder: server}, LocalRoot{ClaimID: "k4", Fresh: true}) + st, got, err := start(t, startHead(3, "s1/r1", "k3"), HolderID{Epoch: 4, Holder: server}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k4", Fresh: true, CanStartFrom: anyStart}) if err != nil || st.updates != 1 || got.Epoch != 4 || got.Holder != server || got.ClaimID != "k4" { t.Fatalf("fresh root at epoch 4 on %s: %+v %v (%d writes)", server, got, err, st.updates) } @@ -97,17 +97,17 @@ func TestStart_FreshRootAtHigherEpochClaims(t *testing.T) { // An older line is fenced; the same epoch held by another server is not // this holder's; an absent HEAD is refused (nothing is created). func TestStart_Refusals(t *testing.T) { - if _, _, err := start(t, startHead(4, "s1/r1", "k4"), HolderID{Epoch: 3, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3"}); !errors.Is(err, ErrStaleEpoch) { + if _, _, err := start(t, startHead(4, "s1/r1", "k4"), HolderID{Epoch: 3, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k3"}); !errors.Is(err, ErrStaleEpoch) { t.Errorf("older line: %v; want ErrStaleEpoch", err) } - if _, _, err := start(t, startHead(4, "s1/r1", "k4"), HolderID{Epoch: 4, Holder: "s2/r1"}, LocalRoot{ClaimID: "k9", Fresh: true}); !errors.Is(err, ErrNotHolder) { + if _, _, err := start(t, startHead(4, "s1/r1", "k4"), HolderID{Epoch: 4, Holder: "s2/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k9", Fresh: true, CanStartFrom: anyStart}); !errors.Is(err, ErrNotHolder) { t.Errorf("same epoch, another server: %v; want ErrNotHolder", err) } st := &memHead{} - if _, err := Start(context.Background(), st, &fakeLease{ended: true}, HolderID{Epoch: 1, Holder: "s1/r1"}, LocalRoot{ClaimID: "k1", Fresh: true}); !errors.Is(err, ErrHeadAbsent) || st.updates != 0 { + if _, err := Start(context.Background(), st, &fakeLease{ended: true}, HolderID{Epoch: 1, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k1", Fresh: true, CanStartFrom: anyStart}); !errors.Is(err, ErrHeadAbsent) || st.updates != 0 { t.Errorf("absent HEAD: %v", err) } - if _, _, err := start(t, startHead(3, "s1/r1", "k3"), HolderID{Epoch: 4, Holder: "s1/r1"}, LocalRoot{}); err == nil { + if _, _, err := start(t, startHead(3, "s1/r1", "k3"), HolderID{Epoch: 4, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}}); err == nil { t.Error("start without a local claim id accepted") } } @@ -121,7 +121,7 @@ func TestStart_HigherEpochRefusesAnOlderLineage(t *testing.T) { rn := RootName{Hash: Sum([]byte("image published at epoch 4"))} h := startHead(4, "s1/r1", "k4") h.Current = &rn - st, _, err := start(t, h, HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3"}) + st, _, err := start(t, h, HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k3"}) if !errors.Is(err, ErrStaleLocalRoot) || !errors.Is(err, ErrNotHolder) { t.Fatalf("old root at a higher epoch: %v; want ErrStaleLocalRoot, fenced", err) } @@ -130,7 +130,7 @@ func TestStart_HigherEpochRefusesAnOlderLineage(t *testing.T) { } // The continuing lineage (the root HEAD's claim id names) claims at the // higher epoch, keeping its data. - st2, got, err := start(t, h, HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{ClaimID: "k4"}) + st2, got, err := start(t, h, HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k4"}) if err != nil || st2.updates != 1 || got.Epoch != 5 || got.ClaimID != "k4" { t.Fatalf("continuing lineage at epoch 5: %+v %v (%d writes)", got, err, st2.updates) } @@ -143,11 +143,11 @@ func TestStart_OldCopyOfTheRightRootRefused(t *testing.T) { h := startHead(4, "s1/r1", "k4") h.Position = 100 for _, epoch := range []uint64{4, 5} { - st, _, err := start(t, h, HolderID{Epoch: epoch, Holder: "s1/r1"}, LocalRoot{ClaimID: "k4", Position: 99}) + st, _, err := start(t, h, HolderID{Epoch: epoch, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k4", Position: 99}) if !errors.Is(err, ErrStaleLocalRoot) || st.updates != 0 { t.Fatalf("root at position 99 under HEAD at 100, epoch %d: %v (%d writes); want ErrStaleLocalRoot, no write", epoch, err, st.updates) } - st, _, err = start(t, h, HolderID{Epoch: epoch, Holder: "s1/r1"}, LocalRoot{ClaimID: "k4", Position: 100}) + st, _, err = start(t, h, HolderID{Epoch: epoch, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k4", Position: 100}) if err != nil { t.Fatalf("root at HEAD's position, epoch %d: %v", epoch, err) } @@ -160,7 +160,7 @@ func TestStart_OldCopyOfTheRightRootRefused(t *testing.T) { // claims or finds its own claim and continues; it is never refused. func TestStart_InterruptAtTheClaim(t *testing.T) { for _, fresh := range []bool{true, false} { - local := LocalRoot{ClaimID: "k3", Fresh: fresh} + local := LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k3", Fresh: fresh, CanStartFrom: anyStart} for _, after := range []bool{false, true} { h := startHead(3, "s1/r1", "k3") if fresh { @@ -192,14 +192,14 @@ func TestStart_FreshAcrossACrashContinuesTheRestore(t *testing.T) { h.Position = 50 st := &memHead{h: &h} line := HolderID{Epoch: 4, Holder: "s1/r1"} - if _, err := Start(context.Background(), st, &fakeLease{ended: true}, line, LocalRoot{ClaimID: "k4", Fresh: true}); err != nil { + if _, err := Start(context.Background(), st, &fakeLease{ended: true}, line, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k4", Fresh: true, CanStartFrom: anyStart}); err != nil { t.Fatal(err) } - got, err := Start(context.Background(), st, &fakeLease{ended: true}, line, LocalRoot{ClaimID: "k4", Fresh: true}) + got, err := Start(context.Background(), st, &fakeLease{ended: true}, line, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k4", Fresh: true, CanStartFrom: anyStart}) if err != nil || got.ClaimID != "k4" || got.Epoch != 4 { t.Fatalf("restart of a still-fresh root: %+v %v; want continue", got, err) } - if _, err := Start(context.Background(), st, &fakeLease{ended: true}, line, LocalRoot{ClaimID: "k4", Position: 0}); !errors.Is(err, ErrStaleLocalRoot) { + if _, err := Start(context.Background(), st, &fakeLease{ended: true}, line, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k4", Position: 0}); !errors.Is(err, ErrStaleLocalRoot) { t.Fatalf("the same root reported non-fresh at 0 under 50: %v; want ErrStaleLocalRoot", err) } } @@ -210,7 +210,7 @@ func TestStart_DeletingVolumeRefused(t *testing.T) { h := startHead(3, "s1/r1", "k3") h.State = StateDeleting for _, line := range []HolderID{{Epoch: 3, Holder: "s1/r1"}, {Epoch: 4, Holder: "s1/r1"}} { - st, _, err := start(t, h, line, LocalRoot{ClaimID: "k3"}) + st, _, err := start(t, h, line, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k3"}) if !errors.Is(err, ErrVolumeDeleting) || st.updates != 0 { t.Fatalf("start at epoch %d of a deleting volume: %v (%d writes); want ErrVolumeDeleting", line.Epoch, err, st.updates) } @@ -221,7 +221,7 @@ func TestStart_DeletingVolumeRefused(t *testing.T) { // another root claimed in between, so it is refused as stale, and the // error names the cure. func TestStart_StaleRootNamesTheCure(t *testing.T) { - _, _, err := start(t, startHead(5, "s2/r1", "k5"), HolderID{Epoch: 6, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3"}) + _, _, err := start(t, startHead(5, "s2/r1", "k5"), HolderID{Epoch: 6, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k3"}) if !errors.Is(err, ErrStaleLocalRoot) || !strings.Contains(err.Error(), StaleLocalRootCure) { t.Fatalf("old directory after a move away and back: %v; want ErrStaleLocalRoot naming %q", err, StaleLocalRootCure) } @@ -241,7 +241,7 @@ func TestStart_ValidatesAgainstTheHeadItUpdates(t *testing.T) { h.Position = 50 st := &memHead{h: &h} st.afterRead = func() { change(st.h) } - _, err := Start(context.Background(), st, &fakeLease{ended: true}, HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{ClaimID: "k3", Position: 50}) + _, err := Start(context.Background(), st, &fakeLease{ended: true}, HolderID{Epoch: 5, Holder: "s1/r1"}, LocalRoot{Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k3", Position: 50}) if !errors.Is(err, ErrStaleLocalRoot) || st.updates != 0 { t.Fatalf("start after HEAD changed under it: %v (%d writes); want ErrStaleLocalRoot, nothing written", err, st.updates) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/verify.go b/seaweed-block/core/frontend/chunkstore/layout/verify.go new file mode 100644 index 0000000000..feb4827778 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/verify.go @@ -0,0 +1,426 @@ +package layout + +import ( + "context" + "errors" + "fmt" + "path" + "sort" +) + +// Verify is a read-only check of one volume's store on this layout: HEAD, +// every root HEAD names (the current image and each snapshot), their +// segments and the chunks they name. It never writes or deletes. With +// Orphans it also lists the volume's own pool, seg and root names that no +// reachable root names (removal 7' deletes those inside the lease; Verify +// only reports them). + +// Verify depths. +const ( + DepthNames = "names" // every named object exists (chunks by name only) + DepthFull = "full" // and every chunk's bytes hash to its name +) + +// Finding classes. +const ( + FindMissing = "MISSING" + FindCorrupt = "CORRUPT" // bytes do not hash to the name, or do not decode + FindMalformed = "MALFORMED" + FindOrphan = "ORPHAN" + FindIdentity = "IDENTITY" // a chunk reference names an owner id its VOLUME does not hold +) + +// List returns the entry names of the directory p. A missing directory is +// (nil, nil). +type List func(ctx context.Context, p string) ([]string, error) + +// VerifyOptions configures one pass. +type VerifyOptions struct { + Depth string // DepthNames (default) or DepthFull + Orphans bool // also report unreachable own names (needs List) + List List +} + +// Finding is one problem found at Path (relative to ). +type Finding struct { + Class, Path, Detail string +} + +// VerifyResult is one pass. Complete is false when the pass could not read +// what it needed; Incomplete says why. Findings are sorted by path. +type VerifyResult struct { + Complete bool + Incomplete string + Roots, Segments int + Chunks, ChunksZero int + OrphansChecked bool + Findings []Finding +} + +type verifier struct { + base, vol string + fetch Fetch + opts VerifyOptions + res VerifyResult + ownPool map[string]bool // reachable own names, by path relative to the volume + ownMeta map[string]bool + owners map[string]ownerID // VOLUME id per chunk owner, read once +} + +type ownerID struct { + id VolumeID + ok bool +} + +// Verify checks vol under base; see the top of this file. +func Verify(ctx context.Context, base, vol string, fetch Fetch, opts VerifyOptions) (VerifyResult, error) { + if err := checkOwner(vol); err != nil { + return VerifyResult{}, err + } + if fetch == nil { + return VerifyResult{}, errors.New("layout: verify needs a fetch") + } + if opts.Depth == "" { + opts.Depth = DepthNames + } + if opts.Depth != DepthNames && opts.Depth != DepthFull { + return VerifyResult{}, fmt.Errorf("layout: verify depth %q", opts.Depth) + } + if opts.Orphans && opts.List == nil { + return VerifyResult{}, errors.New("layout: verify orphans needs a list") + } + v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}} + v.res.Complete = true + head, ok, err := v.head(ctx, vol) + if err != nil { + return VerifyResult{}, err + } + if ok { + for _, rn := range HeadRoots(head) { + if err := v.root(ctx, vol, rn, true); err != nil { + return VerifyResult{}, err + } + } + if opts.Orphans { + if err := v.orphans(ctx, head); err != nil { + return VerifyResult{}, err + } + } + } + sort.Slice(v.res.Findings, func(i, j int) bool { + a, b := v.res.Findings[i], v.res.Findings[j] + return a.Path < b.Path || a.Path == b.Path && a.Class < b.Class + }) + return v.res, nil +} + +func (v *verifier) find(class, p, detail string) { + v.res.Findings = append(v.res.Findings, Finding{Class: class, Path: p, Detail: detail}) +} + +func (v *verifier) incomplete(why string) { + if v.res.Complete { + v.res.Complete, v.res.Incomplete = false, why + } +} + +// head reads vol's VOLUME and then its HEAD, decoded against the VOLUME's +// id (a HEAD of another volume id does not decode). A missing or malformed +// record is a finding and leaves nothing to walk; a read error is returned. +func (v *verifier) head(ctx context.Context, vol string) (Head, bool, error) { + id, ok, err := v.volumeID(ctx, vol, true) + if err != nil || !ok { + return Head{}, false, err + } + p := path.Join(vol, HeadName) + b, ok, err := v.fetch(ctx, path.Join(v.base, p)) + if err != nil { + return Head{}, false, fmt.Errorf("layout: read %s: %w", p, err) + } + if !ok { + v.find(FindMissing, p, "no HEAD") + v.incomplete("no HEAD") + return Head{}, false, nil + } + h, err := DecodeHead(b, 0, id) + if err != nil { + v.find(FindMalformed, p, err.Error()) + v.incomplete("HEAD does not decode against the VOLUME id") + return Head{}, false, nil + } + return h, true, nil +} + +// volumeID reads vol's VOLUME record. report: findings for this volume +// (false for a dependent, where absence only means "no longer a dependent"). +func (v *verifier) volumeID(ctx context.Context, vol string, report bool) (VolumeID, bool, error) { + p := path.Join(vol, VolumeName) + b, ok, err := v.fetch(ctx, path.Join(v.base, p)) + if err != nil { + return VolumeID{}, false, fmt.Errorf("layout: read %s: %w", p, err) + } + if !ok { + if report { + v.find(FindMissing, p, "no VOLUME") + v.incomplete("no VOLUME") + } + return VolumeID{}, false, nil + } + rec, err := DecodeVolume(b) + if err != nil { + if report { + v.find(FindMalformed, p, err.Error()) + v.incomplete("VOLUME does not decode") + } + return VolumeID{}, false, nil + } + return rec.ID, true, nil +} + +// HeadRoots is every root h names: its current image and each snapshot's +// (in snapshot name order), once each. +func HeadRoots(h Head) []RootName { + seen := map[RootName]bool{} + var out []RootName + add := func(rn RootName) { + if !seen[rn] { + seen[rn] = true + out = append(out, rn) + } + } + if h.Current != nil { + add(*h.Current) + } + names := make([]string, 0, len(h.Snapshots)) + for n := range h.Snapshots { + names = append(names, n) + } + sort.Strings(names) + for _, n := range names { + add(h.Snapshots[n].Root) + } + return out +} + +// classify turns a read error into a finding; a plain read failure is +// returned instead (the pass cannot judge what it could not read). +func (v *verifier) classify(p string, err error) error { + switch { + case errors.Is(err, ErrMissing): + v.find(FindMissing, p, err.Error()) + case errors.Is(err, ErrCorrupt): + v.find(FindCorrupt, p, err.Error()) + default: + return err + } + return nil +} + +// root walks one root of owner: its segments and the chunks they name. +// count is false for a dependent's roots (walked only to learn which of +// this volume's names they reach). +func (v *verifier) root(ctx context.Context, owner string, rn RootName, count bool) error { + r, err := NewReader(v.base, owner, v.fetch) + if err != nil { + return err + } + if owner == v.vol { + v.ownMeta[rn.Path()] = true + } + img, err := r.Open(ctx, rn) + if err != nil { + if !count { + v.incomplete("a dependent's root " + path.Join(owner, rn.Path()) + " is unreadable") + return nil + } + return v.classify(path.Join(owner, rn.Path()), err) + } + if count { + v.res.Roots++ + } + shards := make([]uint64, 0, len(img.root.Segments)) + for s := range img.root.Segments { + shards = append(shards, s) + } + sort.Slice(shards, func(i, j int) bool { return shards[i] < shards[j] }) + for _, s := range shards { + sn := img.root.Segments[s] + if owner == v.vol { + v.ownMeta[sn.Path()] = true + } + seg, _, err := img.Segment(ctx, s) + if err != nil { + if !count { + v.incomplete("a dependent's segment " + path.Join(owner, sn.Path()) + " is unreadable") + continue + } + if err := v.classify(path.Join(owner, sn.Path()), err); err != nil { + return err + } + continue + } + if count { + v.res.Segments++ + } + if err := v.chunks(ctx, r, seg, count); err != nil { + return err + } + } + return nil +} + +func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count bool) error { + idx := make([]uint64, 0, len(seg.Chunks)) + for i := range seg.Chunks { + idx = append(idx, i) + } + sort.Slice(idx, func(i, j int) bool { return idx[i] < idx[j] }) + for _, i := range idx { + ref := seg.Chunks[i] + if ref.Owner == v.vol { + v.ownPool[ref.Chunk.Path()] = true + } + if !count { + continue + } + v.res.Chunks++ + p := path.Join(ref.Owner, ref.Chunk.Path()) + o, seen := v.owners[ref.Owner] + if !seen { + id, ok, err := v.volumeID(ctx, ref.Owner, false) + if err != nil { + return err + } + o = ownerID{id, ok} + v.owners[ref.Owner] = o + } + if !o.ok || o.id != ref.OwnerID { + v.find(FindIdentity, p, fmt.Sprintf("names owner %s id %s; its VOLUME has %s", ref.Owner, ref.OwnerID, map[bool]string{true: o.id.String(), false: "none"}[o.ok])) + continue + } + if v.opts.Depth == DepthFull { + if _, err := r.get(ctx, ref.Owner, ref.Chunk.Path(), ref.Chunk.Hash); err != nil { + if err := v.classify(p, err); err != nil { + return err + } + } + continue + } + _, ok, err := v.fetch(ctx, path.Join(v.base, p)) + if err != nil { + return fmt.Errorf("layout: read %s: %w", p, err) + } + if !ok { + v.find(FindMissing, p, "chunk named by a segment is not in the pool") + } + } + return nil +} + +// orphans lists the volume's own pool, seg and root names and reports those +// no reachable root names. A dependent's roots reach this volume's chunks +// too; if any dependent cannot be walked, no orphan is reported (a false +// orphan is worse than none). +func (v *verifier) orphans(ctx context.Context, h Head) error { + deps := map[string]VolumeID{} + for _, s := range h.Snapshots { + for _, d := range s.Dependents { + deps[d.Target] = d.TargetID + } + } + names := make([]string, 0, len(deps)) + for d := range deps { + names = append(names, d) + } + sort.Strings(names) + for _, d := range names { + dh, live, err := v.depHead(ctx, d, deps[d]) + if err != nil { + return err + } + if !live { + continue + } + for _, rn := range HeadRoots(dh) { + if err := v.root(ctx, d, rn, false); err != nil { + return err + } + } + } + if !v.res.Complete { + return nil + } + var found []Finding + for _, dir := range []string{RootDir, SegDir} { + names, err := v.opts.List(ctx, path.Join(v.base, v.vol, dir)) + if err != nil { + return fmt.Errorf("layout: list %s: %w", path.Join(v.vol, dir), err) + } + for _, n := range names { + rel := path.Join(dir, n) + if bad := parseMeta(dir, n); bad != nil { + found = append(found, Finding{FindMalformed, path.Join(v.vol, rel), bad.Error()}) + } else if !v.ownMeta[rel] { + found = append(found, Finding{FindOrphan, path.Join(v.vol, rel), "no reachable root names it"}) + } + } + } + shards, err := v.opts.List(ctx, path.Join(v.base, v.vol, PoolDir)) + if err != nil { + return fmt.Errorf("layout: list %s: %w", path.Join(v.vol, PoolDir), err) + } + for _, sd := range shards { + names, err := v.opts.List(ctx, path.Join(v.base, v.vol, PoolDir, sd)) + if err != nil { + return fmt.Errorf("layout: list %s: %w", path.Join(v.vol, PoolDir, sd), err) + } + for _, n := range names { + c, perr := ParseChunkName(n) + rel := path.Join(PoolDir, sd, n) + switch { + case perr != nil: + found = append(found, Finding{FindMalformed, path.Join(v.vol, rel), perr.Error()}) + case c.Dir() != path.Join(PoolDir, sd): + found = append(found, Finding{FindMalformed, path.Join(v.vol, rel), "chunk in the wrong pool directory"}) + case !v.ownPool[rel]: + found = append(found, Finding{FindOrphan, path.Join(v.vol, rel), "no reachable root names it"}) + } + } + } + v.res.OrphansChecked = true + v.res.Findings = append(v.res.Findings, found...) + return nil +} + +// depHead reads a dependent's HEAD. A target whose VOLUME is gone or has +// another id is no longer a dependent (a volume created again under the +// name matches no dependent): live false, no doubt. A live target whose +// HEAD cannot be read leaves the orphan report undecidable. +func (v *verifier) depHead(ctx context.Context, d string, want VolumeID) (Head, bool, error) { + if checkOwner(d) != nil { + return Head{}, false, nil + } + id, ok, err := v.volumeID(ctx, d, false) + if err != nil || !ok || id != want { + return Head{}, false, err + } + b, ok, err := v.fetch(ctx, path.Join(v.base, d, HeadName)) + if err != nil { + return Head{}, false, fmt.Errorf("layout: read %s: %w", path.Join(d, HeadName), err) + } + h, derr := DecodeHead(b, 0, id) + if !ok || derr != nil { + v.incomplete("dependent " + d + " has no readable HEAD: orphans not reported") + return Head{}, false, nil + } + return h, true, nil +} + +func parseMeta(dir, n string) error { + if dir == RootDir { + _, err := ParseRootName(n) + return err + } + _, err := ParseSegName(n) + return err +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/verify_test.go b/seaweed-block/core/frontend/chunkstore/layout/verify_test.go new file mode 100644 index 0000000000..4d2763f023 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/verify_test.go @@ -0,0 +1,271 @@ +package layout + +import ( + "context" + "errors" + "path" + "sort" + "strings" + "testing" +) + +// memStore is a store of whole objects by path, with directory listing. +type memStore struct { + obj map[string][]byte + readErr string // a path whose read fails +} + +func (m *memStore) fetch(_ context.Context, p string) ([]byte, bool, error) { + if p == m.readErr { + return nil, false, errors.New("injected read failure") + } + b, ok := m.obj[p] + return b, ok, nil +} + +func (m *memStore) list(_ context.Context, dir string) ([]string, error) { + seen := map[string]bool{} + for p := range m.obj { + if rest, ok := strings.CutPrefix(p, dir+"/"); ok { + seen[strings.SplitN(rest, "/", 2)[0]] = true + } + } + out := make([]string, 0, len(seen)) + for n := range seen { + out = append(out, n) + } + sort.Strings(out) + return out, nil +} + +const vbase = "/chunks" + +// putImage stores the chunks of data (index -> bytes, owner vol) and their root; returns the root name. +func putImage(t *testing.T, m *memStore, vol string, data map[uint64]string, borrowed map[uint64]Ref) RootName { + t.Helper() + manifest := map[uint64]Ref{} + for i, d := range data { + c := NameChunk(i, []byte(d)) + m.obj[path.Join(vbase, vol, c.Path())] = []byte(d) + manifest[i] = Ref{Owner: vol, OwnerID: vid(vol, 0), Chunk: c} + } + for i, r := range borrowed { + manifest[i] = r + } + root, segs, err := Build(manifest) + if err != nil { + t.Fatal(err) + } + for n, b := range segs { + m.obj[path.Join(vbase, vol, n.Path())] = b + } + rn, rb, err := NameRoot(root) + if err != nil { + t.Fatal(err) + } + m.obj[path.Join(vbase, vol, rn.Path())] = rb + return rn +} + +// vid is a fixed id per volume name (n: a generation, to model a volume created again). +func vid(vol string, n byte) VolumeID { + var id VolumeID + copy(id[:], vol) + id[15] = n + 1 + return id +} + +func vputVolume(t *testing.T, m *memStore, vol string, id VolumeID) { + t.Helper() + b, err := Volume{ID: id, Name: vol, Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat}.Encode() + if err != nil { + t.Fatal(err) + } + m.obj[path.Join(vbase, vol, VolumeName)] = b +} + +func putHead(t *testing.T, m *memStore, vol string, cur *RootName, snaps map[string]Snapshot) { + t.Helper() + vputVolume(t, m, vol, vid(vol, 0)) + b, err := Head{VolumeID: vid(vol, 0), Epoch: 1, Holder: "h1", ClaimID: "c1", Activity: Activity{Kind: ActIdle}, + Current: cur, Snapshots: snaps}.Encode() + if err != nil { + t.Fatal(err) + } + m.obj[path.Join(vbase, vol, HeadName)] = b +} + +func newVol(t *testing.T) (*memStore, RootName) { + m := &memStore{obj: map[string][]byte{}} + rn := putImage(t, m, "v1", map[uint64]string{0: "aaaa", 7: "bbbb", ShardSize + 3: "cccc"}, nil) + putHead(t, m, "v1", &rn, nil) + return m, rn +} + +func run(t *testing.T, m *memStore, opts VerifyOptions) VerifyResult { + t.Helper() + opts.List = m.list + r, err := Verify(context.Background(), vbase, "v1", m.fetch, opts) + if err != nil { + t.Fatal(err) + } + return r +} + +func classes(r VerifyResult) string { + var s []string + for _, f := range r.Findings { + s = append(s, f.Class+" "+f.Path) + } + return strings.Join(s, "; ") +} + +func TestVerifyCleanVolume(t *testing.T) { + m, _ := newVol(t) + r := run(t, m, VerifyOptions{Depth: DepthFull, Orphans: true}) + if !r.Complete || len(r.Findings) != 0 || r.Roots != 1 || r.Segments != 2 || r.Chunks != 3 || !r.OrphansChecked { + t.Fatalf("clean volume: %+v", r) + } +} + +func chunkPath(i uint64, d string) string { + return path.Join(vbase, "v1", NameChunk(i, []byte(d)).Path()) +} + +func TestVerifyFindsMissingAndCorrupt(t *testing.T) { + m, rn := newVol(t) + delete(m.obj, chunkPath(7, "bbbb")) + m.obj[chunkPath(0, "aaaa")] = []byte("XXXX") + r := run(t, m, VerifyOptions{Depth: DepthFull}) + if c := classes(r); !strings.Contains(c, "MISSING v1/pool/0/7-") || !strings.Contains(c, "CORRUPT v1/pool/0/0-") || len(r.Findings) != 2 { + t.Fatalf("full depth: %s", c) + } + // names depth: presence only, by design (the bytes are not read) + r = run(t, m, VerifyOptions{Depth: DepthNames}) + if c := classes(r); !strings.Contains(c, "MISSING v1/pool/0/7-") || strings.Contains(c, "CORRUPT") { + t.Fatalf("names depth: %s", c) + } + // a corrupt root and a missing segment + m2, rn2 := newVol(t) + m2.obj[path.Join(vbase, "v1", rn2.Path())] = []byte("not a root") + if c := classes(run(t, m2, VerifyOptions{})); !strings.Contains(c, "CORRUPT v1/root/") { + t.Fatalf("corrupt root: %s", c) + } + m3, _ := newVol(t) + for p := range m3.obj { + if strings.Contains(p, "/seg/1-") { + delete(m3.obj, p) + } + } + if c := classes(run(t, m3, VerifyOptions{})); !strings.Contains(c, "MISSING v1/seg/1-") { + t.Fatalf("missing segment: %s", c) + } + _ = rn +} + +func TestVerifyHeadMissingOrMalformedIsIncomplete(t *testing.T) { + m, _ := newVol(t) + delete(m.obj, path.Join(vbase, "v1", HeadName)) + r := run(t, m, VerifyOptions{Orphans: true}) + if r.Complete || classes(r) != "MISSING v1/HEAD" || r.OrphansChecked { + t.Fatalf("no HEAD: %+v", r) + } + m.obj[path.Join(vbase, "v1", HeadName)] = []byte("{") + if r = run(t, m, VerifyOptions{}); r.Complete || !strings.HasPrefix(classes(r), "MALFORMED v1/HEAD") { + t.Fatalf("bad HEAD: %+v", r) + } +} + +func TestVerifyWalksSnapshotRoots(t *testing.T) { + m, cur := newVol(t) + snap := putImage(t, m, "v1", map[uint64]string{2: "ssss"}, nil) + putHead(t, m, "v1", &cur, map[string]Snapshot{"s1": {Root: snap}}) + if r := run(t, m, VerifyOptions{Depth: DepthFull, Orphans: true}); !r.Complete || len(r.Findings) != 0 || r.Roots != 2 { + t.Fatalf("with snapshot: %+v", r) + } + delete(m.obj, chunkPath(2, "ssss")) + if c := classes(run(t, m, VerifyOptions{})); c != "MISSING v1/pool/0/"+NameChunk(2, []byte("ssss")).String() { + t.Fatalf("snapshot-only chunk: %s", c) + } +} + +func TestVerifyOrphans(t *testing.T) { + m, _ := newVol(t) + extra := NameChunk(9, []byte("zzzz")) + m.obj[path.Join(vbase, "v1", extra.Path())] = []byte("zzzz") + m.obj[path.Join(vbase, "v1", SegDir, "garbage")] = []byte("x") + r := run(t, m, VerifyOptions{Orphans: true}) + if c := classes(r); c != "ORPHAN v1/"+extra.Path()+"; MALFORMED v1/seg/garbage" && c != "MALFORMED v1/seg/garbage; ORPHAN v1/"+extra.Path() { + t.Fatalf("orphans: %s", c) + } + if r = run(t, m, VerifyOptions{}); len(r.Findings) != 0 || r.OrphansChecked { + t.Fatalf("orphans are reported only on request: %+v", r) + } +} + +func TestVerifyDependentReachIsNotOrphanAndUnreadableDependentSuppresses(t *testing.T) { + m, cur := newVol(t) + // v1 snapshot s1 names chunk 4; restore target v2's current root borrows it + snap := putImage(t, m, "v1", map[uint64]string{4: "dddd"}, nil) + putHead(t, m, "v1", &cur, map[string]Snapshot{"s1": {Root: snap, Dependents: []Dependent{{Target: "v2", TargetID: vid("v2", 0), Root: snap}}}}) + borrowed := NameChunk(5, []byte("eeee")) + m.obj[path.Join(vbase, "v1", borrowed.Path())] = []byte("eeee") // only v2 names it + v2 := putImage(t, m, "v2", nil, map[uint64]Ref{5: {Owner: "v1", OwnerID: vid("v1", 0), Chunk: borrowed}}) + putHead(t, m, "v2", &v2, nil) + if r := run(t, m, VerifyOptions{Orphans: true}); !r.Complete || len(r.Findings) != 0 || !r.OrphansChecked { + t.Fatalf("a chunk only the dependent names is not an orphan: %+v", r) + } + head2 := m.obj[path.Join(vbase, "v2", HeadName)] + delete(m.obj, path.Join(vbase, "v2", HeadName)) + if r := run(t, m, VerifyOptions{Orphans: true}); r.Complete || r.OrphansChecked || len(r.Findings) != 0 { + t.Fatalf("an unreadable dependent must suppress orphans: %+v", r) + } + // v2 created again under the same name (new id): no longer a dependent, so the borrowed chunk is an orphan + m.obj[path.Join(vbase, "v2", HeadName)] = head2 + vputVolume(t, m, "v2", vid("v2", 1)) + if r := run(t, m, VerifyOptions{Orphans: true}); !r.Complete || classes(r) != "ORPHAN v1/"+borrowed.Path() { + t.Fatalf("a re-created target matches no dependent: %+v", r) + } +} + +func TestVerifyVolumeRecordAndHeadID(t *testing.T) { + m, _ := newVol(t) + delete(m.obj, path.Join(vbase, "v1", VolumeName)) + if r := run(t, m, VerifyOptions{}); r.Complete || classes(r) != "MISSING v1/VOLUME" { + t.Fatalf("no VOLUME: %+v", r) + } + vputVolume(t, m, "v1", vid("v1", 9)) // a VOLUME of another id: HEAD names v1's first id + if r := run(t, m, VerifyOptions{}); r.Complete || !strings.HasPrefix(classes(r), "MALFORMED v1/HEAD") { + t.Fatalf("HEAD of another volume id: %+v", r) + } +} + +func TestVerifyChunkOwnerIdentity(t *testing.T) { + m, _ := newVol(t) + vputVolume(t, m, "v1", vid("v1", 9)) // VOLUME re-created: chunk refs name the old id (HEAD too) + m2, _ := newVol(t) + snap := putImage(t, m2, "v1", nil, map[uint64]Ref{4: {Owner: "v3", OwnerID: vid("v3", 0), Chunk: NameChunk(4, []byte("gggg"))}}) + cur := putImage(t, m2, "v1", map[uint64]string{0: "aaaa"}, nil) + putHead(t, m2, "v1", &cur, map[string]Snapshot{"s1": {Root: snap}}) + m2.obj[path.Join(vbase, "v3", NameChunk(4, []byte("gggg")).Path())] = []byte("gggg") // v3 has no VOLUME + if c := classes(run(t, m2, VerifyOptions{Depth: DepthFull})); !strings.HasPrefix(c, "IDENTITY v3/pool/0/4-") { + t.Fatalf("a chunk of an owner without VOLUME: %s", c) + } + vputVolume(t, m2, "v3", vid("v3", 1)) // an owner VOLUME of another id + if c := classes(run(t, m2, VerifyOptions{Depth: DepthFull})); !strings.HasPrefix(c, "IDENTITY v3/pool/0/4-") { + t.Fatalf("a chunk of an owner with another id: %s", c) + } + vputVolume(t, m2, "v3", vid("v3", 0)) + if r := run(t, m2, VerifyOptions{Depth: DepthFull}); len(r.Findings) != 0 { + t.Fatalf("matching owner id: %s", classes(r)) + } + _ = m +} + +func TestVerifyReadErrorIsReturned(t *testing.T) { + m, _ := newVol(t) + m.readErr = chunkPath(7, "bbbb") + if _, err := Verify(context.Background(), vbase, "v1", m.fetch, VerifyOptions{}); err == nil { + t.Fatal("a read failure must be returned, not judged") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/volume.go b/seaweed-block/core/frontend/chunkstore/layout/volume.go index a83a913eeb..4e9718a867 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/volume.go +++ b/seaweed-block/core/frontend/chunkstore/layout/volume.go @@ -5,6 +5,7 @@ import ( "crypto/rand" "encoding/hex" "encoding/json" + "errors" "fmt" ) @@ -64,33 +65,65 @@ const VolumeFormat = 1 // Volume is the VOLUME record: the volume's id, its name when created, and // the layout format. +// Geometry is immutable and lives only in VOLUME. +type Geometry struct { + SizeBytes uint64 + BlockSize uint32 + ChunkBytes uint64 +} + +// ErrGeometryMismatch refuses local or restore geometry that differs from VOLUME. +var ErrGeometryMismatch = errors.New("layout: geometry_mismatch") + +func (g Geometry) Check() error { + if g.SizeBytes == 0 || g.BlockSize == 0 || g.ChunkBytes == 0 || g.SizeBytes%uint64(g.BlockSize) != 0 || g.ChunkBytes%uint64(g.BlockSize) != 0 { + return fmt.Errorf("%w: size_bytes, block_size and chunk_bytes must be nonzero block multiples", ErrMalformed) + } + return nil +} + +// CheckIdentity validates a volume reference without inventing geometry. +func (v Volume) CheckIdentity() error { + if v.ID.IsZero() { + return fmt.Errorf("%w: VOLUME without an id", ErrMalformed) + } + if err := checkOwner(v.Name); err != nil { + return err + } + if err := validName("volume name", v.Name); err != nil { + return err + } + if v.Format != VolumeFormat { + return fmt.Errorf("%w: VOLUME format %d, want %d", ErrMalformed, v.Format, VolumeFormat) + } + return nil +} + type Volume struct { + Geometry ID VolumeID Name string Format int } type volumeDoc struct { - ID string `json:"id"` - Name string `json:"name"` - Format int `json:"format"` + SizeBytes uint64 `json:"size_bytes"` + BlockSize uint32 `json:"block_size"` + ChunkBytes uint64 `json:"chunk_bytes"` + ID string `json:"id"` + Name string `json:"name"` + Format int `json:"format"` } // Encode returns the record's canonical bytes. func (v Volume) Encode() ([]byte, error) { - if v.ID.IsZero() { - return nil, fmt.Errorf("%w: VOLUME without an id", ErrMalformed) - } - if err := checkOwner(v.Name); err != nil { + if err := v.CheckIdentity(); err != nil { return nil, err } - if err := validName("volume name", v.Name); err != nil { + if err := v.Geometry.Check(); err != nil { return nil, err } - if v.Format != VolumeFormat { - return nil, fmt.Errorf("%w: VOLUME format %d, want %d", ErrMalformed, v.Format, VolumeFormat) - } - return json.Marshal(volumeDoc{ID: v.ID.String(), Name: v.Name, Format: v.Format}) + return json.Marshal(volumeDoc{SizeBytes: v.SizeBytes, BlockSize: v.BlockSize, ChunkBytes: v.ChunkBytes, ID: v.ID.String(), Name: v.Name, Format: v.Format}) } // DecodeVolume parses canonical VOLUME bytes. @@ -105,7 +138,7 @@ func DecodeVolume(b []byte) (Volume, error) { if err != nil { return Volume{}, err } - v := Volume{ID: id, Name: d.Name, Format: d.Format} + v := Volume{ID: id, Name: d.Name, Format: d.Format, Geometry: Geometry{SizeBytes: d.SizeBytes, BlockSize: d.BlockSize, ChunkBytes: d.ChunkBytes}} again, err := v.Encode() if err != nil { return Volume{}, err diff --git a/seaweed-block/core/frontend/chunkstore/layout/volume_geometry_test.go b/seaweed-block/core/frontend/chunkstore/layout/volume_geometry_test.go new file mode 100644 index 0000000000..9eb78f5be7 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/volume_geometry_test.go @@ -0,0 +1,63 @@ +package layout + +import ( + "context" + "errors" + "reflect" + "testing" +) + +func TestVolumeRequiresGeometry(t *testing.T) { + raw := []byte(`{"id":"01010101010101010101010101010101","name":"v","format":1}`) + if _, err := DecodeVolume(raw); !errors.Is(err, ErrMalformed) { + t.Fatalf("VOLUME without geometry accepted: %v", err) + } +} + +func TestVolumeGeometryChecksAndIsImmutable(t *testing.T) { + good := Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096} + for _, bad := range []Geometry{{}, {SizeBytes: good.SizeBytes, ChunkBytes: good.ChunkBytes}, {SizeBytes: 1, BlockSize: 4096, ChunkBytes: 4096}, {SizeBytes: 4096, BlockSize: 4096, ChunkBytes: 1}} { + if err := bad.Check(); !errors.Is(err, ErrMalformed) { + t.Fatalf("bad geometry accepted: %+v %v", bad, err) + } + } + st := newMemNewVolume() + v := Volume{ID: idFor("v"), Name: "v", Format: VolumeFormat, Geometry: good} + if _, err := CreateVolume(context.Background(), st, v); err != nil { + t.Fatal(err) + } + v.SizeBytes *= 2 + if _, err := CreateVolume(context.Background(), st, v); !errors.Is(err, ErrGeometryMismatch) { + t.Fatal("resized volume accepted", err) + } +} + +func TestStartGeometryMismatchPrecedesClaim(t *testing.T) { + h := startHead(1, "s/r", "k") + for _, g := range []Geometry{{SizeBytes: 128 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, {SizeBytes: 64 * 4096, BlockSize: 512, ChunkBytes: 4 * 4096}, {SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 8 * 4096}} { + st := &memHead{h: &h} + _, err := Start(context.Background(), st, &fakeLease{ended: true}, HolderID{Epoch: 2, Holder: "s/r"}, LocalRoot{Geometry: g, ClaimID: "new", Fresh: true, CanStartFrom: anyStart}) + if !errors.Is(err, ErrGeometryMismatch) || st.updates != 0 { + t.Fatalf("geometry mismatch changed HEAD: %v writes=%d", err, st.updates) + } + } +} + +func TestVolumeGeometryLivesOnlyInVolume(t *testing.T) { + doc := reflect.TypeOf(volumeDoc{}) + want := map[string]bool{"size_bytes": true, "block_size": true, "chunk_bytes": true, "id": true, "name": true, "format": true} + if doc.NumField() != len(want) { + t.Fatal("VOLUME fields changed; enumerate the format", doc.NumField()) + } + for i := 0; i < doc.NumField(); i++ { + if !want[doc.Field(i).Tag.Get("json")] { + t.Fatal("unexpected VOLUME field", doc.Field(i).Name) + } + } + head := reflect.TypeOf(Head{}) + for _, name := range []string{"SizeBytes", "BlockSize", "ChunkBytes", "Geometry"} { + if _, ok := head.FieldByName(name); ok { + t.Fatal("geometry duplicated in HEAD", name) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/volume_test.go b/seaweed-block/core/frontend/chunkstore/layout/volume_test.go index 08ac14c0a3..daafcdb11f 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/volume_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/volume_test.go @@ -27,12 +27,12 @@ func TestVolumeID_RandomAndParsed(t *testing.T) { } func TestVolume_GoldenEncodingRoundTrip(t *testing.T) { - v := Volume{ID: idFor("v1"), Name: "v1", Format: VolumeFormat} + v := Volume{ID: idFor("v1"), Name: "v1", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat} b, err := v.Encode() if err != nil { t.Fatal(err) } - want := `{"id":"` + idFor("v1").String() + `","name":"v1","format":1}` + want := `{"size_bytes":262144,"block_size":4096,"chunk_bytes":16384,"id":"` + idFor("v1").String() + `","name":"v1","format":1}` if string(b) != want { t.Fatalf("encoding\n got %s\nwant %s", b, want) } @@ -41,9 +41,9 @@ func TestVolume_GoldenEncodingRoundTrip(t *testing.T) { t.Fatalf("decode: %+v %v", back, err) } for name, bad := range map[string]Volume{ - "zero id": {Name: "v1", Format: VolumeFormat}, - "name with path": {ID: idFor("v1"), Name: "a/b", Format: VolumeFormat}, - "invalid UTF-8": {ID: idFor("v1"), Name: "a\xff", Format: VolumeFormat}, + "zero id": {Name: "v1", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat}, + "name with path": {ID: idFor("v1"), Name: "a/b", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat}, + "invalid UTF-8": {ID: idFor("v1"), Name: "a\xff", Geometry: Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: VolumeFormat}, "other format": {ID: idFor("v1"), Name: "v1", Format: 2}, } { if _, err := bad.Encode(); !errors.Is(err, ErrMalformed) { diff --git a/seaweed-block/core/frontend/chunkstore/layout_clean_e2e_test.go b/seaweed-block/core/frontend/chunkstore/layout_clean_e2e_test.go new file mode 100644 index 0000000000..f6f683c7c3 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_clean_e2e_test.go @@ -0,0 +1,99 @@ +package chunkstore + +import ( + "bytes" + "context" + "path" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// poolObjects is the number of chunk objects in v's pool. +func poolObjects(t *testing.T, c *BCatalog, v VolumeRef) int { + t.Helper() + names, err := c.listObjects(context.Background(), v) + if err != nil { + t.Fatal(err) + } + n := 0 + for _, p := range names { + if strings.HasPrefix(p, layout.PoolDir+"/") { + n++ + } + } + return n +} + +// Release-blocking cleaning end to end through the engine and the layout +// remote: the engine writes and takes snapshot s1, overwrites a block and +// takes s2; s1 is deleted; the holder's cleaning (LayoutRemote.Clean with +// the catalog's removal step) removes exactly the chunk only s1 named, the +// pool shrinks by it, and a fresh host reads the current image back intact, +// as does s2. Control: while s1 still exists the cleaning removes nothing. +func TestLayoutRemote_CleanAfterOverwriteAndSnapshotDelete(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + want := map[uint32][]byte{0: block(1), 9: block(2), 63: block(4)} + writeSync(t, s, want) + r.SetSnapshot("s1", layout.SnapshotMeta{CreatedNs: 1, Class: layout.ClassSemantic}) + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("capture s1: %v", err) + } + want[9] = block(9) + writeSync(t, s, map[uint32][]byte{9: want[9]}) + r.SetSnapshot("s2", layout.SnapshotMeta{CreatedNs: 2, Class: layout.ClassSemantic}) + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("capture s2: %v", err) + } + // A real filer lists the shard directory it created; the fake keeps entries only. + if err := lh.cat.f.CreateEntry(ctx, path.Join(lh.cat.base, lh.v.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil { + t.Fatal(err) + } + clean := func() CleanResult { + t.Helper() + var res CleanResult + if err := r.Clean(ctx, func(ctx context.Context, me layout.HolderID, session string) error { + var err error + res, err = lh.cat.RemoveUnreachableAll(ctx, lh.v, me, session) + return err + }); err != nil { + t.Fatalf("clean: %v", err) + } + if h := lh.head(); h.Activity.Kind != layout.ActIdle { + t.Fatalf("HEAD after the cleaning: %+v; want idle", h.Activity) + } + return res + } + + before := poolObjects(t, lh.cat, lh.v) + if res := clean(); res.Removed != 0 { + t.Fatalf("clean with s1 held: %+v; want nothing removed", res) + } + if _, err := lh.cat.DeleteSnapshot(ctx, lh.v, "s1"); err != nil { + t.Fatal(err) + } + if res := clean(); res.Removed != 1 { + t.Fatalf("clean after deleting s1: %+v; want exactly the overwritten chunk", res) + } + if after := poolObjects(t, lh.cat, lh.v); after != before-1 { + t.Fatalf("pool objects %d -> %d; want one fewer", before, after) + } + lh.readBack("fresh", want) + _, rd, err := lh.cat.open(lh.v) + if err != nil { + t.Fatal(err) + } + img, err := rd.Open(ctx, lh.head().Snapshots["s2"].Root) + if err != nil { + t.Fatal(err) + } + c, err := img.Chunk(ctx, 1) + if err != nil || !bytes.Equal(c.Data[1*4096:2*4096], want[9]) { + t.Fatalf("s2 chunk 1 after the cleaning: %v; want block 9 intact", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_create.go b/seaweed-block/core/frontend/chunkstore/layout_create.go new file mode 100644 index 0000000000..d5fcc6eec8 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_create.go @@ -0,0 +1,83 @@ +package chunkstore + +import ( + "context" + "errors" + "fmt" + "strconv" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +var _ layout.NewVolumeStore = (*LayoutStore)(nil) +var _ layout.TargetStore = (*LayoutStore)(nil) + +// CreateHead writes the volume's first HEAD (unclaimed) exclusively; +// layout.ErrExists if a HEAD is already there. +func (s *LayoutStore) CreateHead(ctx context.Context, h layout.Head) error { + if h.State != layout.StateLive || h.Holder != "" { + return errors.New("chunkstore: only an unclaimed live HEAD is created") + } + return s.createHead(ctx, h) +} + +// CreateDeletedHead writes a deleted HEAD (a tombstone) exclusively; +// layout.ErrExists if a HEAD is already there. +func (s *LayoutStore) CreateDeletedHead(ctx context.Context, h layout.Head) error { + if h.State != layout.StateDeleted { + return errors.New("chunkstore: only a deleted HEAD is created as a tombstone") + } + return s.createHead(ctx, h) +} + +func (s *LayoutStore) createHead(ctx context.Context, h layout.Head) error { + if h.VolumeID != s.id { + return layout.ErrIdentity + } + raw, err := h.Encode() + if err != nil { + return err + } + e := layoutEntry(layout.HeadName, raw) + e.Extended = map[string][]byte{layoutKind: []byte("head"), layoutGen: []byte(strconv.FormatUint(1, 10)), layoutVolume: []byte(s.id.String())} + err = s.f.CreateEntry(ctx, s.root, e, true) + if errors.Is(err, ErrExists) { + return layout.ErrExists + } + return err +} + +// ReadVolumeRecord reads the volume's VOLUME record. +func (s *LayoutStore) ReadVolumeRecord(ctx context.Context) (layout.Volume, bool, error) { + e, err := s.f.LookupEntry(ctx, s.root, layout.VolumeName) + if errors.Is(err, ErrNotFound) { + return layout.Volume{}, false, nil + } + if err != nil { + return layout.Volume{}, false, err + } + v, err := layout.DecodeVolume(e.Content) + if err != nil { + return layout.Volume{}, false, fmt.Errorf("%w: VOLUME: %v", layout.ErrCorrupt, err) + } + return v, true, nil +} + +// CreateVolumeRecord writes the VOLUME record exclusively; layout.ErrExists +// if one is already there. +func (s *LayoutStore) CreateVolumeRecord(ctx context.Context, v layout.Volume) error { + if v.ID != s.id { + return layout.ErrIdentity + } + raw, err := v.Encode() + if err != nil { + return err + } + e := layoutEntry(layout.VolumeName, raw) + e.Extended = map[string][]byte{layoutKind: []byte("volume"), layoutVolume: []byte(s.id.String())} + err = s.f.CreateEntry(ctx, s.root, e, true) + if errors.Is(err, ErrExists) { + return layout.ErrExists + } + return err +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_create_test.go b/seaweed-block/core/frontend/chunkstore/layout_create_test.go new file mode 100644 index 0000000000..6ef8d1c181 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_create_test.go @@ -0,0 +1,66 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// A volume created on the filer store reads back its VOLUME and its +// unclaimed HEAD, re-creates as a replay, and the first Start claims it +// from a fresh root through the same store. +func TestLayoutStoreCreateVolumeThenStart(t *testing.T) { + s, _, _ := layoutStoreFixture(t) + ctx := context.Background() + v := layout.Volume{ID: s.id, Name: "v", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat} + if _, err := layout.CreateVolume(ctx, s, v); err != nil { + t.Fatal(err) + } + if got, found, err := s.ReadVolumeRecord(ctx); err != nil || !found || got != v { + t.Fatalf("VOLUME read back %+v %t %v", got, found, err) + } + if _, err := layout.CreateVolume(ctx, s, v); err != nil { + t.Fatalf("re-create: %v", err) + } + h, err := layout.Start(ctx, s, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "root", Fresh: true, CanStartFrom: anyStart}) + if err != nil || h.Epoch != 1 || h.ClaimID != "root" || h.Gen != 2 { + t.Fatalf("first Start: %+v %v", h, err) + } + if err := s.CreateHead(ctx, layout.Unclaimed(s.id, nil)); !errors.Is(err, layout.ErrExists) { + t.Fatalf("second HEAD create: %v; want ErrExists", err) + } +} + +// The store creates only the two shapes the kernel creates, of its own +// volume id: an unclaimed live HEAD, and a deleted HEAD as a tombstone; a +// tombstone makes a later create of the volume's HEAD fail. +func TestLayoutStoreCreatesOnlyKernelShapes(t *testing.T) { + s, f, _ := layoutStoreFixture(t) + ctx := context.Background() + claimed := layout.Unclaimed(s.id, nil) + claimed.Epoch, claimed.Holder, claimed.ClaimID = 1, "s/r", "k" + other, _ := layout.NewVolumeID() + for name, err := range map[string]error{ + "claimed HEAD": s.CreateHead(ctx, claimed), + "live HEAD as a tombstone": s.CreateDeletedHead(ctx, layout.Unclaimed(s.id, nil)), + "another volume's HEAD": s.CreateHead(ctx, layout.Unclaimed(other, nil)), + "another volume's VOLUME": s.CreateVolumeRecord(ctx, layout.Volume{ID: other, Name: "v", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}), + } { + if err == nil { + t.Errorf("%s created", name) + } + } + if len(f.written) != 0 { + t.Fatalf("refused creates wrote %d entries", len(f.written)) + } + tomb := layout.Unclaimed(s.id, nil) + tomb.State = layout.StateDeleted + if err := s.CreateDeletedHead(ctx, tomb); err != nil { + t.Fatal(err) + } + if _, err := layout.CreateVolume(ctx, s, layout.Volume{ID: s.id, Name: "v", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}); !errors.Is(err, layout.ErrVolumeDeleting) { + t.Fatalf("create after the tombstone: %v; want ErrVolumeDeleting", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_fence_latch_test.go b/seaweed-block/core/frontend/chunkstore/layout_fence_latch_test.go new file mode 100644 index 0000000000..4fd6ce2030 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_fence_latch_test.go @@ -0,0 +1,134 @@ +package chunkstore + +import ( + "context" + "errors" + "path/filepath" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// moveHeadOnPut is the layout remote with HEAD moved by another owner at +// its first chunk upload: the cut's commit is the site that observes it. +type moveHeadOnPut struct { + *LayoutRemote + once sync.Once + move func() +} + +func (r *moveHeadOnPut) Put(ctx context.Context, key string, data []byte) error { + r.once.Do(r.move) + return r.LayoutRemote.Put(ctx, key, data) +} + +// Every identity-moved signal latches the layer fenced at every call site +// that can observe it, so the one place writes are admitted (Fenced, read by +// the durable backend's ready check) refuses them from then on: an +// ex-holder never acknowledges a write it can no longer publish. A new +// signal or site belongs in this table. +func TestLayoutFenceLatchesAtEverySite(t *testing.T) { + signals := map[string]func(h layout.Head) layout.Head{ + "newer epoch": func(h layout.Head) layout.Head { h.Epoch++; h.Holder = "b"; return h }, + "same epoch, holder": func(h layout.Head) layout.Head { h.Holder = "b"; return h }, + "same epoch, claim": func(h layout.Head) layout.Head { h.ClaimID = "k-other"; return h }, + "volume deleting": func(h layout.Head) layout.Head { h.State = layout.StateDeleting; return h }, + } + type site struct { + name string + onPut bool // HEAD moves at the first upload instead of before the call + observe func(context.Context, *storage.WALStore, storage.ChunkLayer) error + } + sites := []site{ + {"cut", false, func(ctx context.Context, _ *storage.WALStore, l storage.ChunkLayer) error { + _, err := l.Capture(ctx) + return err + }}, + {"commit after upload", true, func(ctx context.Context, _ *storage.WALStore, l storage.ChunkLayer) error { + _, err := l.Capture(ctx) + return err + }}, + {"make remote durable", false, func(ctx context.Context, s *storage.WALStore, l storage.ChunkLayer) error { + return l.MakeRemoteDurable(ctx, s.NextLSN()-1) + }}, + {"detach", false, func(ctx context.Context, _ *storage.WALStore, l storage.ChunkLayer) error { + _, err := l.Detach(ctx) + return err + }}, + // The holder's cleaning runs outside the layer; its refusal is + // classified (LayoutErr) and handed to the layer, as the provider's + // maintenance loop does. + {"cleaning", false, nil}, + } + for sigName, move := range signals { + for _, st := range sites { + t.Run(sigName+"/"+st.name, func(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + moveHead := func() { + hs, err := lh.cat.Store(lh.v) + if err != nil { + t.Error(err) + return + } + h, _, err := hs.ReadHead(ctx) + if err != nil { + t.Error(err) + return + } + if err := hs.UpdateHead(ctx, h.Gen, move(h)); err != nil { + t.Error(err) + } + } + s, err := storage.CreateWALStoreWithOptions(filepath.Join(lh.dir, "s"), lrBlocks, 4096, storage.WALStoreOptions{ChunkBlocks: lrChunkBlocks}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + var remote storage.ChunkRemote = r + if st.onPut { + remote = &moveHeadOnPut{LayoutRemote: r, move: moveHead} + } + l, err := storage.AttachChunkLayer(s, remote, storage.ChunkLayerConfig{ChunkBlocks: lrChunkBlocks, Epoch: lh.me.Epoch, Holder: lh.me.Holder, FreshFromHead: true}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = l.Close() }) + writeSync(t, s, map[uint32][]byte{1: block(1)}) + if !st.onPut { + moveHead() + } + if st.observe == nil { // cleaning + cerr := r.Clean(ctx, func(ctx context.Context, me layout.HolderID, s string) error { + _, rerr := lh.cat.RemoveUnreachableAll(ctx, lh.v, me, s) + return rerr + }) + err = LayoutErr(cerr) + if obs, ok := l.(interface{ ObserveRemoteError(error) error }); ok { + _ = obs.ObserveRemoteError(err) + } + } else { + err = st.observe(ctx, s, l) + } + if err == nil { + t.Fatalf("%s did not observe the moved HEAD", st.name) + } + if !l.Fenced() { + t.Fatalf("%s observed %v but the layer is not fenced: writes would still be admitted", st.name, err) + } + if _, err := l.Capture(ctx); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("a capture after the latch: %v; want ErrChunkLayerFenced", err) + } + }) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_geometry_test.go b/seaweed-block/core/frontend/chunkstore/layout_geometry_test.go new file mode 100644 index 0000000000..dbe95f19ab --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_geometry_test.go @@ -0,0 +1,55 @@ +package chunkstore + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "testing" +) + +func TestBCatalogRestoreCopiesVolumeGeometry(t *testing.T) { + ctx := context.Background() + c, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/geometry") + if err != nil { + t.Fatal(err) + } + src, target := newRef(t, "source"), newRef(t, "target") + g := layout.Geometry{SizeBytes: 128 * 4096, BlockSize: 4096, ChunkBytes: 8 * 4096} + if _, err := c.CreateVolume(ctx, src, g); err != nil { + t.Fatal(err) + } + st, _ := c.Store(src) + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + if _, err := layout.Start(ctx, st, okClaimLease{}, me, layout.LocalRoot{Geometry: g, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + const session = "snap" + if _, err := layout.RunBegin(ctx, st, me, session); err != nil { + t.Fatal(err) + } + root, _, _ := layout.Build(nil) + rn, raw, _ := layout.NameRoot(root) + if err := layout.EnsureObject(ctx, st, rn.Path(), raw, session); err != nil { + t.Fatal(err) + } + if _, err := layout.RunCommit(ctx, st, st, src.Name, me, layout.CommitRequest{Session: session, Snapshot: "s", State: layout.StateLive}); err != nil { + t.Fatal(err) + } + if _, err := c.Restore(ctx, src, "s", target); err != nil { + t.Fatal(err) + } + ts, _ := c.Store(target) + v, found, err := ts.ReadVolumeRecord(ctx) + if err != nil || !found || v.Geometry != g { + t.Fatalf("restored geometry %+v found=%v err=%v", v.Geometry, found, err) + } + wrong := newRef(t, "wrong") + bad := g + bad.ChunkBytes *= 2 + if _, err := c.CreateVolume(ctx, wrong, bad); err != nil { + t.Fatal(err) + } + if _, err := c.Restore(ctx, src, "s", wrong); !errors.Is(err, layout.ErrGeometryMismatch) { + t.Fatal("restore into different geometry accepted", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_noop_model_trace_test.go b/seaweed-block/core/frontend/chunkstore/layout_noop_model_trace_test.go new file mode 100644 index 0000000000..d2fdd8a751 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_noop_model_trace_test.go @@ -0,0 +1,69 @@ +package chunkstore + +import ( + "bytes" + "context" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// A stop can abort its session while an adapter HEAD read is already in +// progress, before the adapter consumes the abandonment notice. The read +// then observes an ended session and invalidates its staging view. That +// view change alone must not fence the holder on its next no-op cut. +func TestLayoutRemote_NoOpCutAfterStopAbortKeepsTheHolder(t *testing.T) { + for _, readBeforeNotice := range []bool{false, true} { + name := "notice-before-read" + if readBeforeNotice { + name = "read-before-notice" + } + t.Run(name, func(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{2: block(2)}) + if _, err := l.Capture(ctx); err != nil { + t.Fatal(err) + } + before := lh.head() + session, err := r.Begin(ctx) + if err != nil { + t.Fatal(err) + } + st, err := lh.cat.Store(lh.v) + if err != nil { + t.Fatal(err) + } + // This is the stop's kernel abort. Splitting its kernel write + // from its non-blocking adapter notice forces the model order. + if _, err := layout.RunAbort(ctx, st, lh.me, session); err != nil { + t.Fatal(err) + } + if readBeforeNotice { + if _, err := r.GetHead(ctx); err != nil { + t.Fatal(err) + } + } + r.Abort() + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("no-op cut after an aborted stop fenced the unchanged holder: %v", err) + } + after := lh.head() + if after.Epoch != before.Epoch || after.Holder != before.Holder || after.ClaimID != before.ClaimID || + after.State != layout.StateLive || after.Position != before.Position || + after.Current == nil || before.Current == nil || *after.Current != *before.Current { + t.Fatalf("abort/no-op changed holder or image: before %+v, after %+v", before, after) + } + got, err := s.Read(2) + if err != nil || !bytes.Equal(got, block(2)) { + t.Fatalf("acknowledged bytes after resume: %x, %v", got, err) + } + writeSync(t, s, map[uint32][]byte{3: block(3)}) + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("holder could not publish after resume: %v", err) + } + }) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go b/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go index 928e4d1c78..a10f9f05a1 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_objects_integration_test.go @@ -5,118 +5,12 @@ package chunkstore import ( "context" "errors" - "path" "testing" "time" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) -// filerObjects is a layout.ObjectStore on a real filer: an object is an -// entry under root whose extended attributes carry the writer's session -// and the removal mark ("-" when unmarked); every change of an existing -// entry is a conditional update or delete on those attributes. -type filerObjects struct { - cl *SWFS - root string -} - -const ( - objSessKey = "swb-sess" - objMarkKey = "swb-mark" - unmarked = "-" -) - -func (f filerObjects) loc(rel string) (string, string) { - full := path.Join(f.root, rel) - return path.Dir(full), path.Base(full) -} - -func metaOf(e *filerpb.Entry) layout.ObjectMeta { - m := layout.ObjectMeta{Session: string(e.GetExtended()[objSessKey]), Mark: string(e.GetExtended()[objMarkKey])} - if m.Mark == unmarked { - m.Mark = "" - } - return m -} - -func markValue(m string) []byte { - if m == "" { - return []byte(unmarked) - } - return []byte(m) -} - -func expected(m layout.ObjectMeta) map[string][]byte { - return map[string][]byte{objSessKey: []byte(m.Session), objMarkKey: markValue(m.Mark)} -} - -func layoutErr(err error) error { - if errors.Is(err, ErrPrecondition) { - return layout.ErrPrecondition - } - return err -} - -func (f filerObjects) Stat(ctx context.Context, rel string) (layout.ObjectMeta, bool, error) { - dir, name := f.loc(rel) - e, err := f.cl.LookupEntry(ctx, dir, name) - if errors.Is(err, ErrNotFound) { - return layout.ObjectMeta{}, false, nil - } - if err != nil { - return layout.ObjectMeta{}, false, err - } - return metaOf(e), true, nil -} - -func (f filerObjects) Create(ctx context.Context, rel string, data []byte, session string) error { - dir, name := f.loc(rel) - e := &filerpb.Entry{Name: name, Content: data, Attributes: &filerpb.FuseAttributes{FileMode: 0o644, Mtime: time.Now().Unix()}, - Extended: map[string][]byte{objSessKey: []byte(session), objMarkKey: []byte(unmarked)}} - err := f.cl.CreateEntry(ctx, dir, e, true) - if errors.Is(err, ErrExists) { - return layout.ErrExists - } - return layoutErr(err) -} - -// rewrite updates the entry's attributes to next, conditional on expect. -func (f filerObjects) rewrite(ctx context.Context, rel string, expect, next layout.ObjectMeta) error { - dir, name := f.loc(rel) - e, err := f.cl.LookupEntry(ctx, dir, name) - if errors.Is(err, ErrNotFound) { - return layout.ErrPrecondition - } - if err != nil { - return err - } - e.Extended[objSessKey] = []byte(next.Session) - e.Extended[objMarkKey] = markValue(next.Mark) - return layoutErr(f.cl.UpdateEntry(ctx, dir, e, expected(expect))) -} - -func (f filerObjects) Reuse(ctx context.Context, rel string, expect layout.ObjectMeta, session string) error { - return f.rewrite(ctx, rel, expect, layout.ObjectMeta{Session: session}) -} - -func (f filerObjects) Mark(ctx context.Context, rel string, expect layout.ObjectMeta, mark string) error { - return f.rewrite(ctx, rel, expect, layout.ObjectMeta{Session: expect.Session, Mark: mark}) -} - -func (f filerObjects) DeleteMarked(ctx context.Context, rel string, mark string) error { - dir, name := f.loc(rel) - err := f.cl.DeleteEntry(ctx, dir, name, map[string][]byte{objMarkKey: markValue(mark)}) - if errors.Is(err, ErrPrecondition) { - if _, found, serr := f.Stat(ctx, rel); serr == nil && !found { - return nil // a missing entry succeeds - } - return layout.ErrPrecondition - } - return err -} - // On a real filer (stock weed): the removal's two conditional writes and // the upload's reuse write behave as the layout needs. A delete whose // mark does not match is refused; a reuse (another session, mark cleared) @@ -127,15 +21,23 @@ func TestIntegration_ObjectMarkAndConditionalDelete(t *testing.T) { c := startWeed(t) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() - const root = "/swblock/objs/v1" - f := filerObjects{cl: c.client(t, root+"/"), root: root} + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + root := "/swblock/objs/" + layout.VolumeDir("v1", id) + cl := c.client(t, root+"/") + f, err := NewLayoutStore(cl, cl, root, id) + if err != nil { + t.Fatal(err) + } rel := layout.NameChunk(5, []byte("orphan")).Path() if err := layout.EnsureObject(ctx, f, rel, []byte("orphan"), "s0"); err != nil { t.Fatal(err) } plan, found, err := f.Stat(ctx, rel) - if err != nil || !found || plan != (layout.ObjectMeta{Session: "s0"}) { + if err != nil || !found || plan != (layout.ObjectMeta{Session: "s0", Volume: id}) { t.Fatalf("created object: %+v %t %v", plan, found, err) } if err := f.Mark(ctx, rel, plan, "c1"); err != nil { @@ -151,7 +53,7 @@ func TestIntegration_ObjectMarkAndConditionalDelete(t *testing.T) { if err := layout.EnsureObject(ctx, f, rel, []byte("orphan"), "successor"); err != nil { t.Fatal(err) } - if m, _, _ := f.Stat(ctx, rel); m != (layout.ObjectMeta{Session: "successor"}) { + if m, _, _ := f.Stat(ctx, rel); m != (layout.ObjectMeta{Session: "successor", Volume: id}) { t.Fatalf("after the reuse: %+v; want session successor, unmarked", m) } if err := f.DeleteMarked(ctx, rel, "c1"); !errors.Is(err, layout.ErrPrecondition) { @@ -178,3 +80,56 @@ func TestIntegration_ObjectMarkAndConditionalDelete(t *testing.T) { t.Fatalf("delete of a missing entry: %v; want success", err) } } + +// On a real filer: the catalog's whole life of a restore. A source with a +// committed snapshot; a restore target that reads the source's chunk +// through its copied root; the snapshot refused deletion while the target +// depends on it; the target's delete empties its pool, keeps its VOLUME +// and a deleted HEAD, and releases the source, whose snapshot then deletes. +func TestIntegration_CatalogRestoreAndDelete(t *testing.T) { + c := startWeed(t) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + const base = "/swblock/cat" + cl := c.client(t, base+"/") + cat, err := NewBCatalog(cl, cl, base) + if err != nil { + t.Fatal(err) + } + src, tgt := newRef(t, "src"), newRef(t, "t") + if _, err := cat.CreateVolume(ctx, src, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + data := []byte("real source chunk") + commitSnapshot(t, cat, src, data, "daily") + th, err := cat.Restore(ctx, src, "daily", tgt) + if err != nil { + t.Fatalf("restore: %v", err) + } + _, tr, err := cat.open(tgt) + if err != nil { + t.Fatal(err) + } + img, err := tr.Open(ctx, *th.Current) + if err != nil { + t.Fatal(err) + } + if got, err := img.Chunk(ctx, 1); err != nil || string(got.Data) != string(data) { + t.Fatalf("target reads the source's chunk: %+v %v", got, err) + } + if _, err := cat.DeleteSnapshot(ctx, src, "daily"); !errors.Is(err, layout.ErrHasDependents) { + t.Fatalf("delete a depended-on snapshot: %v", err) + } + if err := cat.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err != nil { + t.Fatalf("delete the target: %v", err) + } + if objs, err := cat.listObjects(ctx, tgt); err != nil || len(objs) != 0 { + t.Fatalf("target objects after delete: %v %v", objs, err) + } + if h, found, err := cat.ReadHead(ctx, tgt); err != nil || !found || h.State != layout.StateDeleted { + t.Fatalf("target HEAD after delete: %+v %t %v", h, found, err) + } + if _, err := cat.DeleteSnapshot(ctx, src, "daily"); err != nil { + t.Fatalf("delete the released snapshot: %v", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go new file mode 100644 index 0000000000..a86cd28a58 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -0,0 +1,783 @@ +package chunkstore + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "strings" + "sync" + "sync/atomic" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// LayoutRemote is the chunk engine's remote (storage.ChunkRemote) on the +// content-named layout, for the holder me of one volume. The engine keeps +// its view at H, its copy-on-write and its base + dirty record; this maps +// its remote calls onto the kernel's snapshot transaction: +// - the first upload of a cut opens a session (Begin; a fresh id, never +// reused); every upload is EnsureObject of the content-named chunk; +// - CASHead is the Commit (current root, position, state, and the +// snapshot named by SetSnapshot), conditional on the generation the +// engine read: the one before this session's Begin; +// - a session of this holder found open with no session in memory (a +// crash) is rolled back before anything else. +// +// Keys are layout::: (ChunkKey), so a key +// alone resolves the owner's directory and is verified by name. +// sessionStore is what the remote writes through: HEAD and the objects. +type sessionStore interface { + layout.HeadStore + layout.ObjectStore +} + +type LayoutRemote struct { + st sessionStore + r *layout.Reader + vol VolumeRef + me layout.HolderID + + mu sync.Mutex + session string + // visible is the HEAD generation the engine sees: it moves with this + // remote's commits and with writes of anyone else, never with this + // remote's own Begin, Abort or cleaning; ownGen is HEAD's generation + // after this remote's last own write. + visible, ownGen uint64 + // seen is the image HEAD named when visible was last set: a write of + // anyone else that leaves it equal (a snapshot delete, retention, a + // dependent added) does not move visible. + seen imageTuple + // forceView moves visible at the next HEAD read even when the image is + // unchanged: this remote's session ended without its commit, so what + // the engine staged in it is void and must be dropped. + forceView bool + // abandoned is set by the engine when a cut ends without a commit + // (Abort): the next call drops the session and the pending name. + abandoned atomic.Bool + pending *pendingSnapshot + // snapErr is why the last commit could not name its snapshot (the cut + // itself committed unnamed); TakeSnapshotErr hands it to the request. + snapErr error + // cleaning is this process's open cleaning: its session and the way to + // end it early, so a cut or a stop never waits on it or fails busy. + cleaning string + cleanCancel context.CancelFunc + cleanDone chan struct{} + lastCommit layout.Head +} + +type pendingSnapshot struct { + name string + meta layout.SnapshotMeta +} + +var ( + _ storage.ChunkRemote = (*LayoutRemote)(nil) + _ storage.ChunkKeyer = (*LayoutRemote)(nil) +) + +// NewLayoutRemote returns the remote of volume v for the holder me (the +// line its Start claimed). +func NewLayoutRemote(cat *BCatalog, v VolumeRef, me layout.HolderID) (*LayoutRemote, error) { + if me.Epoch == 0 || me.Holder == "" || me.ClaimID == "" { + return nil, errors.New("chunkstore: layout remote needs the holder's epoch, holder and claim id") + } + st, r, err := cat.open(v) + if err != nil { + return nil, err + } + return &LayoutRemote{st: st, r: r, vol: v, me: me}, nil +} + +// SetSnapshot names the snapshot the next commit records, with its +// retention facts; a commit consumes it. +func (l *LayoutRemote) SetSnapshot(name string, meta layout.SnapshotMeta) { + l.mu.Lock() + defer l.mu.Unlock() + l.pending = &pendingSnapshot{name: name, meta: meta} +} + +// DropSnapshot withdraws a pending snapshot name whose request gave up (its +// cut failed): the name never rides onto a later cut, which would name an +// image the requester was told was not taken. A cut that keeps its session +// for a retry does not drop it by itself. +func (l *LayoutRemote) DropSnapshot() { + l.mu.Lock() + defer l.mu.Unlock() + l.pending = nil +} + +// layoutKeyPrefix marks a key that is a layout reference. +const layoutKeyPrefix = "layout:" + +// LayoutKey is the engine key of a layout reference. +func LayoutKey(ref layout.Ref) string { + return layoutKeyPrefix + ref.Owner + ":" + ref.OwnerID.String() + ":" + ref.Chunk.String() +} + +// ParseLayoutKey parses LayoutKey's form. +func ParseLayoutKey(key string) (layout.Ref, error) { + rest, ok := strings.CutPrefix(key, layoutKeyPrefix) + parts := strings.Split(rest, ":") + if !ok || len(parts) != 3 { + return layout.Ref{}, fmt.Errorf("%w: %q is not a layout key", storage.ErrChunkKeyInvalid, key) + } + id, err := layout.ParseVolumeID(parts[1]) + if err != nil { + return layout.Ref{}, fmt.Errorf("%w: %q: %w", storage.ErrChunkKeyInvalid, key, err) + } + name, err := layout.ParseChunkName(parts[2]) + if err != nil { + return layout.Ref{}, fmt.Errorf("%w: %q: %w", storage.ErrChunkKeyInvalid, key, err) + } + ref := layout.Ref{Owner: parts[0], OwnerID: id, Chunk: name} + // One key per reference: a key that does not round-trip (an uppercase + // id, a padded index, ...) or names no volume is not a layout key. + if id.IsZero() || parts[0] == "" || LayoutKey(ref) != key { + return layout.Ref{}, fmt.Errorf("%w: %q is not a canonical layout key", storage.ErrChunkKeyInvalid, key) + } + return ref, nil +} + +// ChunkKey names the key of this volume's chunk idx whose bytes hash to sum. +func (l *LayoutRemote) ChunkKey(idx uint64, sum [32]byte) string { + return LayoutKey(l.own(idx, sum)) +} + +func (l *LayoutRemote) own(idx uint64, sum [32]byte) layout.Ref { + return layout.Ref{Owner: l.vol.Name, OwnerID: l.vol.ID, Chunk: layout.ChunkName{Index: idx, Hash: sum}} +} + +// openSessionLocked opens this cut's session if none is open: a session of +// this holder left open by a crash is rolled back first. +func (l *LayoutRemote) openSessionLocked(ctx context.Context) error { + if l.session != "" { + return nil + } + if err := l.stopCleaningLocked(ctx); err != nil { + return err + } + if _, err := l.rollBackLocked(ctx); err != nil { + return err + } + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return err + } + s := "s-" + hex.EncodeToString(b[:]) + h, err := layout.RunBegin(ctx, l.st, l.me, s) + if err != nil { + return layoutRemoteErr(err) + } + l.session, l.ownGen = s, h.Gen + return nil +} + +// rollBackLocked rolls back a session of this holder that HEAD shows open +// but this process does not hold (it died with the process), and returns +// HEAD. +func (l *LayoutRemote) rollBackLocked(ctx context.Context) (layout.Head, error) { + h, found, err := l.st.ReadHead(ctx) + if err != nil { + return layout.Head{}, err + } + if !found { + return layout.Head{}, layout.ErrHeadAbsent + } + l.viewLocked(h) + mine := h.Epoch == l.me.Epoch && h.Holder == l.me.Holder && h.ClaimID == l.me.ClaimID + switch { + case mine && h.Activity.Kind == layout.ActSnap && h.Activity.Session != l.session: + if h, err = layout.RunAbort(ctx, l.st, l.me, h.Activity.Session); err != nil { + return layout.Head{}, layoutRemoteErr(err) + } + l.ownGen = h.Gen + case mine && h.Activity.Kind == layout.ActClean && h.Activity.Session != l.cleaning: + if h, err = layout.RunEndClean(ctx, l.st, l.me, h.Activity.Session); err != nil { + return layout.Head{}, layoutRemoteErr(err) + } + l.ownGen = h.Gen + } + return h, nil +} + +// Put stores the chunk under its content name in this cut's session; it +// returns only once the object entry exists. +func (l *LayoutRemote) Put(ctx context.Context, key string, data []byte) error { + ref, err := ParseLayoutKey(key) + if err != nil { + return err + } + if ref.OwnerID != l.vol.ID || ref.Chunk != layout.NameChunk(ref.Chunk.Index, data) { + return fmt.Errorf("%w: %q is not this volume's name for these bytes", storage.ErrChunkKeyInvalid, key) + } + l.mu.Lock() + defer l.mu.Unlock() + l.takeAbandonLocked() + if err := l.openSessionLocked(ctx); err != nil { + return err + } + return layoutRemoteErr(layout.EnsureObject(ctx, l.st, ref.Chunk.Path(), data, l.session)) +} + +// Get reads a chunk by its key through the volume's reader: the owner's +// directory, its VOLUME id checked, the bytes checked against the name. +func (l *LayoutRemote) Get(ctx context.Context, key string) ([]byte, error) { + ref, err := ParseLayoutKey(key) + if err != nil { + return nil, err + } + b, err := l.r.ReadRef(ctx, ref) + return b, layoutRemoteErr(err) +} + +// GetHead reads HEAD as the engine's view: the generation the engine last +// saw (the one before this process's open session), the position, and the +// current root resolved to the chunk map. A session of this holder left +// open by a crash is rolled back first. +func (l *LayoutRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + l.mu.Lock() + defer l.mu.Unlock() + l.takeAbandonLocked() + h, err := l.rollBackLocked(ctx) + if err != nil { + return storage.ChunkHead{}, err + } + if h.State == layout.StateDeleting || h.State == layout.StateDeleted { + return storage.ChunkHead{}, storage.ErrChunkHeadDeleted + } + // Another claim at this holder's own epoch is another owner of HEAD: the + // head the engine sees carries no claim id, so it must not read as its own. + if h.Epoch == l.me.Epoch && h.Holder == l.me.Holder && h.ClaimID != l.me.ClaimID { + return storage.ChunkHead{}, fmt.Errorf("%w: HEAD is held by %s at epoch %d (claim %q)", storage.ErrChunkLayerFenced, h.Holder, h.Epoch, h.ClaimID) + } + out := storage.ChunkHead{Gen: l.visible, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.Position, Chunks: map[uint64]storage.ChunkRef{}, State: "active"} + if h.State == layout.StateDetached { + out.State = "detached" + out.DetachedBy = &storage.ChunkDetachedBy{Holder: h.Holder, Epoch: h.Epoch, Gen: h.Gen} + } + if h.Current == nil { + return out, nil + } + m, err := l.manifest(ctx, *h.Current) + if err != nil { + return storage.ChunkHead{}, err + } + for idx, ref := range m { + out.Chunks[idx] = storage.ChunkRef{Key: LayoutKey(ref), SHA256: ref.Chunk.Hash, Encoding: "full"} + } + return out, nil +} + +// manifest is the chunk map root names. +func (l *LayoutRemote) manifest(ctx context.Context, rn layout.RootName) (map[uint64]layout.Ref, error) { + m := map[uint64]layout.Ref{} + err := l.r.EachRef(ctx, rn, layout.AllShards, func(idx uint64, ref layout.Ref) bool { + m[idx] = ref + return true + }) + if err != nil { + return nil, layoutRemoteErr(err) + } + return m, nil +} + +// CASHead commits next as this cut's session: the root of next's chunk +// map, position next.RemoteLSN, detached when next is, and the pending +// snapshot name. It uses the engine view from before this session's Begin. +// A concurrent operator-only HEAD update is rebased with a bounded retry; +// a foreign claim or detached/deleted state remains a final refusal. +func (l *LayoutRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + l.mu.Lock() + defer l.mu.Unlock() + l.takeAbandonLocked() + if expected.Epoch != l.me.Epoch || next.Epoch != l.me.Epoch { + return 0, storage.ErrChunkHeadPrecondition + } + h, found, err := l.st.ReadHead(ctx) + if err != nil { + return 0, err + } + if !found { + return 0, layout.ErrHeadAbsent + } + l.viewLocked(h) + if expected.Gen != l.visible { + return 0, storage.ErrChunkHeadPrecondition + } + prev, nextM, err := l.manifests(ctx, h, next) + if err != nil { + return 0, err + } + if err := l.openSessionLocked(ctx); err != nil { + return 0, err + } + if err := l.writeRootLocked(ctx, nextM); err != nil { + return 0, err + } + req := layout.CommitRequest{Session: l.session, Prev: prev, Next: nextM, Position: next.RemoteLSN, State: layout.StateLive} + if next.State == "detached" { + req.State = layout.StateDetached + } + if l.pending != nil { + if err := layout.CheckSnapshot(l.pending.name, l.pending.meta); err != nil { + // A name or facts the commit would refuse: the cut commits + // unnamed and the request gets the refusal. + l.snapErr, l.pending = err, nil + } else { + req.Snapshot, req.Meta = l.pending.name, l.pending.meta + } + } + var got layout.Head + // An operator may change only HEAD's snapshot/dependent table between + // Commit's read and conditional write. Re-read and retry that same image + // with the same session; a different claim is a final fence. The bound + // keeps a busy operator from starving the holder's cut indefinitely. + const maxMetadataCommitAttempts = 4 + for attempt := 0; attempt < maxMetadataCommitAttempts; attempt++ { + got, err = layout.RunCommit(ctx, l.st, l.st, l.vol.Name, l.me, req) + if err != nil && req.Snapshot != "" && snapshotRefusal(err) { + // This snapshot cannot be named; the cut still commits unnamed and + // the request gets the typed refusal. + l.snapErr, l.pending = err, nil + req.Snapshot, req.Meta = "", layout.SnapshotMeta{} + got, err = layout.RunCommit(ctx, l.st, l.st, l.vol.Name, l.me, req) + } + if !errors.Is(err, layout.ErrPrecondition) { + break + } + cur, found, readErr := l.st.ReadHead(ctx) + if readErr != nil { + return 0, layoutRemoteErr(readErr) + } + if !found { + return 0, storage.ErrChunkHeadDeleted + } + if cur.Epoch != l.me.Epoch || cur.Holder != l.me.Holder || cur.ClaimID != l.me.ClaimID { + return 0, fmt.Errorf("%w: layout HEAD claim changed during commit", storage.ErrChunkLayerFenced) + } + if cur.State == layout.StateDetached { + return 0, storage.ErrChunkLayerFenced + } + if cur.State == layout.StateDeleting || cur.State == layout.StateDeleted { + return 0, storage.ErrChunkHeadDeleted + } + if imageOf(cur) != imageOf(h) || cur.Activity != (layout.Activity{Kind: layout.ActSnap, Session: l.session}) { + return 0, storage.ErrChunkHeadPrecondition + } + l.viewLocked(cur) + } + if err != nil { + if errors.Is(err, layout.ErrStaleBase) { + return 0, storage.ErrChunkHeadPrecondition + } + if errors.Is(err, layout.ErrNotPrepared) { + // An upload of an ended session (a staged pre-copy): forget the + // engine's view so its re-read finds a newer generation and + // drops what it staged; the retry uploads again. + l.forceView = true + return 0, fmt.Errorf("%w: %w", storage.ErrChunkHeadPrecondition, err) + } + // An unknown outcome is decided by the engine's next HEAD read, + // which also re-derives this session from HEAD (syncSessionLocked). + return 0, layoutRemoteErr(err) + } + l.session, l.pending, l.lastCommit = "", nil, got + l.ownGen, l.visible, l.seen = got.Gen, got.Gen, imageOf(got) + return got.Gen, nil +} + +// manifests are HEAD's current chunk map and next's, as layout references: +// a key the engine got from HEAD keeps its reference (also another +// volume's); a chunk the engine uploaded is this volume's by name. +func (l *LayoutRemote) manifests(ctx context.Context, h layout.Head, next storage.ChunkHead) (map[uint64]layout.Ref, map[uint64]layout.Ref, error) { + prev := map[uint64]layout.Ref{} + if h.Current != nil { + m, err := l.manifest(ctx, *h.Current) + if err != nil { + return nil, nil, err + } + prev = m + } + nm := make(map[uint64]layout.Ref, len(next.Chunks)) + for idx, c := range next.Chunks { + if c.Encoding != "full" { + return nil, nil, fmt.Errorf("%w: chunk %d encoding %q (only full: the stored bytes are the logical bytes)", ErrUnsupportedEncoding, idx, c.Encoding) + } + ref, err := ParseLayoutKey(c.Key) + if err != nil { + return nil, nil, err + } + if ref.Chunk.Index != idx || ref.Chunk.Hash != c.SHA256 { + return nil, nil, fmt.Errorf("%w: chunk %d key %q does not name its bytes", storage.ErrChunkKeyInvalid, idx, c.Key) + } + nm[idx] = ref + } + return prev, nm, nil +} + +// writeRootLocked writes next's segments and root in this session, so the +// commit finds them prepared. +func (l *LayoutRemote) writeRootLocked(ctx context.Context, next map[uint64]layout.Ref) error { + root, segs, err := layout.Build(next) + if err != nil { + return err + } + _, err = layout.PrepareRoot(ctx, l.st, root, segs, l.session) + return layoutRemoteErr(err) +} + +// Begin opens the cut's session on HEAD (the kernel's Begin), or replays +// the open one, and returns it. +func (l *LayoutRemote) Begin(ctx context.Context) (string, error) { + l.mu.Lock() + defer l.mu.Unlock() + l.takeAbandonLocked() + if err := l.openSessionLocked(ctx); err != nil { + return "", err + } + return l.session, nil +} + +// Delete is not a removal path on the layout (cleaning removes names). +func (l *LayoutRemote) Delete(context.Context, string) error { return nil } + +// ErrRemoteDamaged: the remote image is damaged (an object HEAD names is +// missing or does not hash to its name, or a VOLUME id does not match): +// never retried as unavailable. The block keeps serving locally; its +// backup is degraded and the operator sees the error. +var ErrRemoteDamaged = errors.New("chunkstore: the remote image is damaged") + +// ErrUnsupportedEncoding: a chunk encoding other than full (the content +// name hashes the stored bytes, which must be the logical bytes). +var ErrUnsupportedEncoding = errors.New("chunkstore: unsupported chunk encoding on the layout") + +// snapshotRefusal reports a commit-time refusal of the snapshot name alone +// (the name's own form is checked before the commit, CheckSnapshot). +func snapshotRefusal(err error) bool { + return errors.Is(err, layout.ErrTooManySnapshots) || errors.Is(err, layout.ErrSnapshotExists) +} + +// kernelRefusals are answers of the store (a condition failed), as opposed +// to the store not answering. +var kernelRefusals = []error{layout.ErrPrecondition, layout.ErrNotHolder, layout.ErrNoSession, layout.ErrBusy, layout.ErrDetached, + layout.ErrVolumeDeleting, layout.ErrStaleEpoch, layout.ErrNotPrepared, layout.ErrStaleBase, layout.ErrHeadAbsent, + layout.ErrMalformed, layout.ErrGeometryMismatch, layout.ErrTooManySnapshots, layout.ErrSnapshotExists, layout.ErrPositionBehind} + +func isKernelRefusal(err error) bool { + for _, k := range kernelRefusals { + if errors.Is(err, k) { + return true + } + } + return false +} + +// CommitPendingSnapshot names HEAD's current image with the snapshot set +// by SetSnapshot when no cut committed it (the engine had nothing to +// publish): one session, the current root and position again, the name. +// Nothing pending is a no-op. A name or facts the kernel refuses is the +// typed refusal. +func (l *LayoutRemote) CommitPendingSnapshot(ctx context.Context) error { + l.mu.Lock() + defer l.mu.Unlock() + l.takeAbandonLocked() + if l.pending == nil { + return nil + } + p := l.pending + if err := layout.CheckSnapshot(p.name, p.meta); err != nil { + l.pending = nil + return err + } + if err := l.openSessionLocked(ctx); err != nil { + return err + } + h, found, err := l.st.ReadHead(ctx) + if err != nil { + return layoutRemoteErr(err) + } + if !found { + return layout.ErrHeadAbsent + } + l.viewLocked(h) + m := map[uint64]layout.Ref{} + if h.Current != nil { + if m, err = l.manifest(ctx, *h.Current); err != nil { + return err + } + } + if err := l.writeRootLocked(ctx, m); err != nil { + return err + } + got, err := layout.RunCommit(ctx, l.st, l.st, l.vol.Name, l.me, layout.CommitRequest{Session: l.session, Prev: m, Next: m, Position: h.Position, State: layout.StateLive, Snapshot: p.name, Meta: p.meta}) + if err != nil { + if snapshotRefusal(err) { + l.pending = nil + return err + } + return layoutRemoteErr(err) + } + // The image is the one the engine already holds (same root and + // position): an own write that leaves the engine's view where it is. + l.session, l.pending, l.lastCommit = "", nil, got + l.ownGen = got.Gen + return nil +} + +// TakeSnapshotErr returns, and clears, why the last commit could not name +// its snapshot (nil when it did, or none was asked). +func (l *LayoutRemote) TakeSnapshotErr() error { + l.mu.Lock() + defer l.mu.Unlock() + err := l.snapErr + l.snapErr = nil + return err +} + +// The outcomes of AbortOpenSession. +const ( + SessionDetached = "detached" // HEAD is this holder's detached commit: the stop is done + SessionAborted = "aborted" // an open session of this holder was rolled back + SessionIdle = "idle" // nothing of this holder was open +) + +// AbortOpenSession settles this holder's open transaction before a stop +// resumes serving or retries. It takes no lock of the remote, so it never +// waits behind a commit in flight (the very one it may abort) and honours +// ctx; the kernel's conditional writes decide between them: an abort that +// lands first makes the commit's update fail, a commit that lands first is +// what HEAD then reports. A cleaning of this holder that HEAD shows open is +// ended, then a session of this holder is rolled back (held here or left by +// a dead process); the remote drops the session and its pending name at its +// next call. HEAD of another holder, epoch or claim id is a fence, never +// idle. +func (l *LayoutRemote) AbortOpenSession(ctx context.Context) (string, error) { + for { + h, found, err := l.st.ReadHead(ctx) + if err != nil { + return "", layoutRemoteErr(err) + } + if !found { + return "", layout.ErrHeadAbsent + } + if h.Epoch != l.me.Epoch || h.Holder != l.me.Holder || h.ClaimID != l.me.ClaimID { + return "", fmt.Errorf("%w: HEAD is held by %s at epoch %d (claim %q)", storage.ErrChunkLayerFenced, h.Holder, h.Epoch, h.ClaimID) + } + switch { + case h.State == layout.StateDetached: + return SessionDetached, nil + case h.State != layout.StateLive: + return "", layoutRemoteErr(fmt.Errorf("%w: HEAD is %s", layout.ErrVolumeDeleting, h.State)) + case h.Activity.Kind == layout.ActClean: + if _, err := layout.RunEndClean(ctx, l.st, l.me, h.Activity.Session); err != nil && !errors.Is(err, layout.ErrPrecondition) { + return "", layoutRemoteErr(err) + } + continue // read HEAD again: a session may follow + case h.Activity.Kind == layout.ActSnap: + if _, err := layout.RunAbort(ctx, l.st, l.me, h.Activity.Session); err != nil { + if errors.Is(err, layout.ErrPrecondition) { + continue // HEAD moved (the commit landed): read it again + } + return "", layoutRemoteErr(err) + } + l.abandoned.Store(true) + return SessionAborted, nil + } + return SessionIdle, nil + } +} + +// ReadHead reads the volume's HEAD as the kernel holds it (a stop's +// unknown outcome is decided from it: detached at my epoch and position). +func (l *LayoutRemote) ReadHead(ctx context.Context) (layout.Head, error) { + h, found, err := l.st.ReadHead(ctx) + if err != nil { + return layout.Head{}, err + } + if !found { + return layout.Head{}, layout.ErrHeadAbsent + } + return h, nil +} + +// LastCommit is HEAD as this remote's last commit left it (for a stop's +// unknown outcome, read HEAD again). +func (l *LayoutRemote) LastCommit() layout.Head { + l.mu.Lock() + defer l.mu.Unlock() + return l.lastCommit +} + +// Clean runs one cleaning of this holder between sessions: clean(c) opens +// HEAD, run removes unreachable names under session c, and clean(c) ends. +// A cut or a stop that needs HEAD meanwhile cancels run's context and +// waits for it to end: neither waits on a cleaning nor fails busy. A pass +// cancelled between its mark and its delete leaves a mark the next +// cleaning takes over (the removal plans every found name). +func (l *LayoutRemote) Clean(ctx context.Context, run func(ctx context.Context, me layout.HolderID, session string) error) error { + l.mu.Lock() + l.takeAbandonLocked() + if l.session != "" || l.cleaning != "" { + l.mu.Unlock() + return layout.ErrBusy + } + if _, err := l.rollBackLocked(ctx); err != nil { + l.mu.Unlock() + return err + } + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + l.mu.Unlock() + return err + } + c := "c-" + hex.EncodeToString(b[:]) + bh, err := layout.RunBeginClean(ctx, l.st, l.me, c) + if err != nil { + l.mu.Unlock() + return layoutRemoteErr(err) + } + l.ownGen = bh.Gen + cctx, cancel := context.WithCancel(ctx) + done := make(chan struct{}) + l.cleaning, l.cleanCancel, l.cleanDone = c, cancel, done + l.mu.Unlock() + + runErr := run(cctx, l.me, c) + // Bounded by the caller's context: a stop on a hung filer does not + // wait for the close; a cleaning left open is ended by the next cut + // (rollBackLocked) or the holder's next claim. + eh, endErr := layout.RunEndClean(ctx, l.st, l.me, c) + cancel() + + l.mu.Lock() + if endErr == nil { + l.ownGen = eh.Gen + } + l.cleaning, l.cleanCancel = "", nil + close(done) + l.mu.Unlock() + if runErr != nil && !errors.Is(runErr, context.Canceled) { + return runErr + } + return layoutRemoteErr(endErr) +} + +// syncSessionLocked drops the in-memory session unless HEAD still shows it +// open: a commit that applied and then lost its reply, or a session another +// actor ended, never leaves a stale session behind. +func (l *LayoutRemote) syncSessionLocked(h layout.Head) { + if l.session != "" && h.Activity != (layout.Activity{Kind: layout.ActSnap, Session: l.session}) { + l.session, l.forceView = "", true + } +} + +// viewLocked takes HEAD h as read: a generation this remote did not write +// itself (someone else's write, or the first read) becomes the engine's +// view; the session is re-derived from h. +func (l *LayoutRemote) viewLocked(h layout.Head) { + l.syncSessionLocked(h) + if h.Gen != l.ownGen || l.forceView { + if t := imageOf(h); l.forceView || l.visible == 0 || t != l.seen { + l.visible, l.seen = h.Gen, t + } + l.ownGen, l.forceView = h.Gen, false + } +} + +// imageTuple is what the engine's view of HEAD depends on: the image and +// who holds it, not the snapshot table. +type imageTuple struct { + current layout.RootName + hasRoot bool + position uint64 + state string + epoch uint64 + holder string + claimID string +} + +func imageOf(h layout.Head) imageTuple { + t := imageTuple{position: h.Position, state: h.State, epoch: h.Epoch, holder: h.Holder, claimID: h.ClaimID} + if h.Current != nil { + t.current, t.hasRoot = *h.Current, true + } + return t +} + +// Abort is the engine's notice that a cut ended without a commit. It +// never blocks: the next call drops the session (HEAD's read then rolls +// it back) and the pending snapshot name, which never rides onto a later +// cut. +func (l *LayoutRemote) Abort() { l.abandoned.Store(true) } + +func (l *LayoutRemote) takeAbandonLocked() { + if l.abandoned.Swap(false) { + // Uploads the engine staged in the dropped session are caught by the + // commit (not prepared), which forces the view then. + l.session, l.pending = "", nil + } +} + +// stopCleaningLocked cancels this process's open cleaning and waits for +// it to end, at most until ctx ends (it releases mu while waiting). +func (l *LayoutRemote) stopCleaningLocked(ctx context.Context) error { + for l.cleaning != "" { + cancel, done := l.cleanCancel, l.cleanDone + cancel() + l.mu.Unlock() + select { + case <-done: + case <-ctx.Done(): + l.mu.Lock() + return fmt.Errorf("%w: waiting for this process's cleaning to end: %w", storage.ErrChunkRemoteUnavailable, ctx.Err()) + } + l.mu.Lock() + } + return nil +} + +// layoutRemoteErr maps a kernel result to the engine's action (the seam's +// closure table): +// - not the holder, a stale epoch, detached: fenced, final (no retry); +// - generation moved, my session gone: HEAD precondition (the engine +// re-reads HEAD and decides); +// - the volume is being deleted: HEAD deleted (the engine stops); +// - my own cleaning open (busy): remote unavailable (retry later; never a +// fence); +// - damage (corrupt, missing, another volume's id): ErrRemoteDamaged, a +// hard reported error, never a retry; +// - any other refusal is returned as it is; +// - the store does not answer: remote unavailable (the session is +// dropped locally; the next cut rolls it back). +// +// LayoutErr classifies a layout error from a call made outside the remote +// (the holder's cleaning) the way the remote classifies its own: an +// identity-moved refusal is storage.ErrChunkLayerFenced, a volume being +// deleted storage.ErrChunkHeadDeleted. +func LayoutErr(err error) error { return layoutRemoteErr(err) } + +func layoutRemoteErr(err error) error { + switch { + case err == nil: + return nil + case errors.Is(err, layout.ErrNotHolder), errors.Is(err, layout.ErrStaleEpoch), errors.Is(err, layout.ErrDetached), + errors.Is(err, layout.ErrPositionBehind): + return fmt.Errorf("%w: %w", storage.ErrChunkLayerFenced, err) + case errors.Is(err, layout.ErrPrecondition), errors.Is(err, layout.ErrNoSession): + return fmt.Errorf("%w: %w", storage.ErrChunkHeadPrecondition, err) + case errors.Is(err, layout.ErrVolumeDeleting): + return fmt.Errorf("%w: %w", storage.ErrChunkHeadDeleted, err) + case errors.Is(err, layout.ErrBusy): + return fmt.Errorf("%w: %w", storage.ErrChunkRemoteUnavailable, err) + case errors.Is(err, layout.ErrCorrupt), errors.Is(err, layout.ErrIdentity), errors.Is(err, layout.ErrMissing): + return fmt.Errorf("%w: %w", ErrRemoteDamaged, err) + case isKernelRefusal(err): + return err + } + return fmt.Errorf("%w: %w", storage.ErrChunkRemoteUnavailable, err) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_clean_bound_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_clean_bound_test.go new file mode 100644 index 0000000000..e16faaa6ab --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_clean_bound_test.go @@ -0,0 +1,105 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// The holder's cleaning and a cut meet in one remote: a cut cancels the +// cleaning through the remote's state and waits for it to end. Both waits +// are bounded by the caller's context, so a stop on a hung filer never +// waits unbounded inside the guest freeze. + +// A cleaning whose removal step ignores cancellation (a filer call that +// hangs): the cut's Begin cancels it and waits only until its own context +// ends, then reports the remote unavailable; it does not hang. +func TestLayoutRemote_ACutWaitsForAHungCleaningOnlyUntilItsContextEnds(t *testing.T) { + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + started, release := make(chan struct{}), make(chan struct{}) + cleaned := make(chan error, 1) + go func() { + cleaned <- r.Clean(context.Background(), func(context.Context, layout.HolderID, string) error { + close(started) + <-release // ignores the cancellation, like a hung filer call + return nil + }) + }() + <-started + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + done := make(chan error, 1) + go func() { _, err := r.Begin(ctx); done <- err }() + select { + case err := <-done: + if !errors.Is(err, storage.ErrChunkRemoteUnavailable) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Begin over a hung cleaning: %v; want remote unavailable (deadline exceeded)", err) + } + case <-time.After(5 * time.Second): + close(release) + t.Fatal("Begin waited for a hung cleaning past its own context") + } + close(release) + if err := <-cleaned; err != nil && !errors.Is(err, context.Canceled) { + t.Logf("the released cleaning ended with %v", err) + } +} + +// hungEndStore lets every HEAD update through except the cleaning's close, +// which hangs until the caller's context ends (a filer that stops answering). +type hungEndStore struct{ sessionStore } + +func (s hungEndStore) UpdateHead(ctx context.Context, gen uint64, next layout.Head) error { + cur, _, err := s.sessionStore.ReadHead(ctx) + if err == nil && cur.Activity.Kind == layout.ActClean && next.Activity.Kind == layout.ActIdle { + <-ctx.Done() + return ctx.Err() + } + return s.sessionStore.UpdateHead(ctx, gen, next) +} + +// The cleaning's close (EndClean) on a store that stops answering ends with +// the caller's context instead of hanging; the cleaning left open on HEAD is +// ended by the next cut. +func TestLayoutRemote_TheCleaningsCloseIsBoundedByTheCallersContext(t *testing.T) { + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + orig := r.st + r.st = hungEndStore{orig} + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + done := make(chan error, 1) + go func() { + done <- r.Clean(ctx, func(context.Context, layout.HolderID, string) error { return nil }) + }() + select { + case err := <-done: + if err == nil { + t.Fatal("a cleaning whose close never landed reported success") + } + case <-time.After(5 * time.Second): + t.Fatal("the cleaning's close waited past the caller's context") + } + if h := lh.head(); h.Activity.Kind != layout.ActClean { + t.Fatalf("HEAD after the unanswered close: %+v; want the cleaning still open", h.Activity) + } + // the next cut ends the cleaning left open and opens its own session + r.st = orig + if _, err := r.Begin(context.Background()); err != nil { + t.Fatalf("the next cut after an unended cleaning: %v", err) + } + if h := lh.head(); h.Activity.Kind != layout.ActSnap { + t.Fatalf("HEAD after the next cut's Begin: %+v; want its session open", h.Activity) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_readback_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_readback_test.go new file mode 100644 index 0000000000..023d4f486e --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_readback_test.go @@ -0,0 +1,357 @@ +package chunkstore + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// commitThenChangeHEAD places an operator write after the holder's commit but +// before the engine's confirmation read, which is the ordering that used to +// make a healthy holder fence itself. +type commitThenChangeHEAD struct { + *LayoutRemote + armed bool + change func(context.Context) error +} + +// conflictBeforeCommitStore places a second HEAD writer after Commit read its +// base but before its conditional write. The underlying store gives the +// commit a definite generation refusal. +type conflictBeforeCommitStore struct { + sessionStore + armed bool + change func(context.Context) error +} + +func (s *conflictBeforeCommitStore) UpdateHead(ctx context.Context, gen uint64, next layout.Head) error { + if s.armed && next.Activity.Kind == layout.ActIdle && next.Current != nil { + s.armed = false + if err := s.change(ctx); err != nil { + return err + } + } + return s.sessionStore.UpdateHead(ctx, gen, next) +} + +func TestLayoutRemote_OperatorHEADWriteDuringCommitRetries(t *testing.T) { + for _, tc := range []struct { + name string + change func(context.Context, *layoutHost, sessionStore) error + }{ + {"delete snapshot", func(ctx context.Context, _ *layoutHost, st sessionStore) error { + _, err := layout.RunDeleteSnapshot(ctx, st, "old") + return err + }}, + {"retire snapshot", func(ctx context.Context, _ *layoutHost, st sessionStore) error { + _, err := layout.RunRetireSnapshot(ctx, st, "old", 10) + return err + }}, + {"add dependent", func(ctx context.Context, lh *layoutHost, st sessionStore) error { + _, reader, err := lh.cat.open(lh.v) + if err != nil { + return err + } + _, err = layout.RunAddDependent(ctx, st, reader, "old", layout.Dependent{Target: "target", TargetID: layout.VolumeID{7}}) + return err + }}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, layer, remote := lh.attach("active", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{2: block(2)}) + remote.SetSnapshot("old", layout.SnapshotMeta{CreatedNs: 1}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + st := &conflictBeforeCommitStore{sessionStore: remote.st, armed: true} + st.change = func(ctx context.Context) error { return tc.change(ctx, lh, st.sessionStore) } + remote.st = st + writeSync(t, s, map[uint32][]byte{9: block(9)}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatalf("same-holder commit after operator write: %v", err) + } + if st.armed { + t.Fatal("operator write was not injected before the conditional commit") + } + if _, err := layer.Capture(ctx); err != nil { + t.Fatalf("next cut after operator write: %v", err) + } + lh.readBack("reader", map[uint32][]byte{2: block(2), 9: block(9)}) + }) + } +} + +func TestLayoutRemote_ForeignClaimDuringCommitFences(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, layer, remote := lh.attach("active", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{2: block(2)}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + st := &conflictBeforeCommitStore{sessionStore: remote.st, armed: true} + st.change = func(ctx context.Context) error { + _, err := layout.RunClaim(ctx, st.sessionStore, okClaimLease{}, layout.HolderID{Epoch: lh.me.Epoch + 1, Holder: "foreign", ClaimID: "foreign-claim"}) + return err + } + remote.st = st + writeSync(t, s, map[uint32][]byte{9: block(9)}) + if _, err := layer.Capture(ctx); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("foreign claim during commit: %v; want final fence", err) + } + if st.armed { + t.Fatal("foreign claim was not injected before the conditional commit") + } +} + +func (r *commitThenChangeHEAD) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + gen, err := r.LayoutRemote.CASHead(ctx, expected, next) + if err == nil && r.armed { + r.armed = false + if err := r.change(ctx); err != nil { + return 0, err + } + } + return gen, err +} + +func TestLayoutRemote_OperatorHEADWriteBetweenCommitAndReadback(t *testing.T) { + for _, tc := range []struct { + name string + change func(context.Context, *layoutHost) error + }{ + {"delete snapshot", func(ctx context.Context, lh *layoutHost) error { + _, err := lh.cat.DeleteSnapshot(ctx, lh.v, "old") + return err + }}, + {"retire snapshot", func(ctx context.Context, lh *layoutHost) error { + st, _ := lh.cat.Store(lh.v) + _, err := layout.RunRetireSnapshot(ctx, st, "old", 10) + return err + }}, + {"add dependent", func(ctx context.Context, lh *layoutHost) error { + st, reader, err := lh.cat.open(lh.v) + if err != nil { + return err + } + _, err = layout.RunAddDependent(ctx, st, reader, "old", layout.Dependent{Target: "target", TargetID: layout.VolumeID{7}}) + return err + }}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, err := storage.CreateWALStoreWithOptions(lh.dir+"/active", lrBlocks, 4096, storage.WALStoreOptions{ChunkBlocks: lrChunkBlocks}) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + inner, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + r := &commitThenChangeHEAD{LayoutRemote: inner} + layer, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: lrChunkBlocks, Epoch: lh.me.Epoch, Holder: lh.me.Holder, FreshFromHead: true}) + if err != nil { + t.Fatal(err) + } + writeSync(t, s, map[uint32][]byte{2: block(2)}) + inner.SetSnapshot("old", layout.SnapshotMeta{CreatedNs: 1}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + r.change = func(ctx context.Context) error { return tc.change(ctx, lh) } + r.armed = true + if _, err := s.Write(3, block(3)); err != nil { + t.Fatal(err) + } + if _, err := layer.Capture(ctx); err != nil { + t.Fatalf("cut after operator HEAD write: %v", err) + } + if r.armed { + t.Fatal("operator write was not injected after the commit") + } + writeSync(t, s, map[uint32][]byte{4: block(4)}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatalf("next cut after operator HEAD write: %v", err) + } + lh.readBack("reader", map[uint32][]byte{2: block(2), 3: block(3), 4: block(4)}) + }) + } +} + +// The layout records chunk names, not each chunk's birth LSN. A later cut +// that advances HEAD while reusing an older chunk must still permit a no-op +// cut: the same object and holder cannot become a competing publication. +func TestLayoutRemote_ReusedChunkBirthDoesNotFenceNoopCut(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, layer, _ := lh.attach("active", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{1: block(1)}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + writeSync(t, s, map[uint32][]byte{9: block(9)}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + if _, err := layer.Capture(ctx); err != nil { + t.Fatalf("no-op cut fenced the same holder after reusing a chunk: %v", err) + } + lh.readBack("reader", map[uint32][]byte{1: block(1), 9: block(9)}) +} + +// A successful Commit may lose its reply. The next HEAD read must use the +// pending engine refs for that published image, including a reused old chunk. +func TestLayoutRemote_ReusedChunkBirthAfterLostCommitReply(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, layer, remote := lh.attach("active", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{1: block(1)}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + lost := &lostReplyStore{sessionStore: remote.st, armed: true} + remote.st = lost + writeSync(t, s, map[uint32][]byte{9: block(9)}) + _, _ = layer.Capture(ctx) + if lost.armed { + t.Fatal("the commit reply was not lost") + } + if _, err := layer.Capture(ctx); err != nil { + t.Fatalf("no-op cut after a lost commit reply: %v", err) + } + lh.readBack("reader", map[uint32][]byte{1: block(1), 9: block(9)}) +} + +// A new adapter keeps no state of the commit. Hold the engine's unresolved +// proposal while replacing its adapter, as a crash/reopen would do to that +// adapter state; the durable proposal must still settle as the same image. +type replacedLayoutRemote struct{ *LayoutRemote } + +func TestLayoutRemote_LostCommitReplyRestartKeepsSameProposal(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, err := storage.CreateWALStoreWithOptions(lh.dir+"/active", lrBlocks, 4096, storage.WALStoreOptions{ChunkBlocks: lrChunkBlocks}) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + remote, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + swapped := &replacedLayoutRemote{LayoutRemote: remote} + layer, err := storage.AttachChunkLayer(s, swapped, storage.ChunkLayerConfig{ChunkBlocks: lrChunkBlocks, Epoch: lh.me.Epoch, Holder: lh.me.Holder, FreshFromHead: true}) + if err != nil { + t.Fatal(err) + } + writeSync(t, s, map[uint32][]byte{1: block(1)}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + lost := &lostReplyStore{sessionStore: remote.st, armed: true} + remote.st = lost + writeSync(t, s, map[uint32][]byte{9: block(9)}) + _, _ = layer.Capture(ctx) + if lost.armed { + t.Fatal("the commit reply was not lost") + } + newRemote, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + swapped.LayoutRemote = newRemote + if _, err := layer.Capture(ctx); err != nil { + t.Fatalf("same proposal after restart and lost reply fenced: %v", err) + } + lh.readBack("reader", map[uint32][]byte{1: block(1), 9: block(9)}) +} + +type pauseCleanEndStore struct { + sessionStore + persisted chan struct{} + release chan struct{} + once sync.Once +} + +func (s *pauseCleanEndStore) UpdateHead(ctx context.Context, gen uint64, next layout.Head) error { + if err := s.sessionStore.UpdateHead(ctx, gen, next); err != nil { + return err + } + if next.Activity.Kind == layout.ActIdle { + var waitErr error + s.once.Do(func() { + close(s.persisted) + select { + case <-s.release: + case <-ctx.Done(): + waitErr = ctx.Err() + } + }) + return waitErr + } + return nil +} + +// The clean-end HEAD write can become visible before Clean has reacquired +// the adapter mutex to record its generation. A read in that gap must keep +// the holder's engine view, and the next cut must still succeed. +func TestLayoutRemote_CleanEndBetweenCommitAndReadback(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, layer, remote := lh.attach("active", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{2: block(2)}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + before, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + st := &pauseCleanEndStore{sessionStore: remote.st, persisted: make(chan struct{}), release: make(chan struct{})} + remote.st = st + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(st.release) }) } + defer release() + done := make(chan error, 1) + go func() { done <- remote.Clean(ctx, func(context.Context, layout.HolderID, string) error { return nil }) }() + select { + case <-st.persisted: + case err := <-done: + t.Fatalf("clean ended before its HEAD write was observed: %v", err) + case <-time.After(3 * time.Second): + t.Fatal("clean end did not reach the persisted HEAD write") + } + mid, err := remote.GetHead(ctx) + if err != nil || mid.Gen != before.Gen { + t.Fatalf("clean end changed the engine view: gen %d -> %d, err=%v", before.Gen, mid.Gen, err) + } + release() + if err := <-done; err != nil { + t.Fatal(err) + } + writeSync(t, s, map[uint32][]byte{9: block(9)}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatalf("next cut after clean end: %v", err) + } + lh.readBack("reader", map[uint32][]byte{2: block(2), 9: block(9)}) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_same_proposal_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_same_proposal_test.go new file mode 100644 index 0000000000..aad307e00d --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_same_proposal_test.go @@ -0,0 +1,157 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A commit whose reply is lost is settled by reading HEAD back: the engine +// asks "is HEAD the image I proposed?". The layout keeps no chunk birth, so +// the answer must come from identity and image only (epoch, holder, +// position, detached state; per chunk key, hash, encoding). A chunk whose +// birth is below the cut position, or one inherited from an earlier cut, +// is the same image whatever birth the adapter reports: no fence. + +// lostThenDownStore loses the reply of the next commit (it applies) and, +// when down is set, then fails every HEAD read until it is brought up: the +// lost commit stays unresolved in this process. +type lostThenDownStore struct { + sessionStore + armed, down, lost bool +} + +func (s *lostThenDownStore) UpdateHead(ctx context.Context, gen uint64, next layout.Head) error { + err := s.sessionStore.UpdateHead(ctx, gen, next) + if err == nil && s.armed && next.Activity.Kind == layout.ActIdle { + s.armed, s.lost = false, true + return errors.New("reply lost") + } + return err +} + +func (s *lostThenDownStore) ReadHead(ctx context.Context) (layout.Head, bool, error) { + if s.lost && s.down { + return layout.Head{}, false, errors.New("store unreachable") + } + return s.sessionStore.ReadHead(ctx) +} + +func requireNotFenced(t *testing.T, err error, what string) { + t.Helper() + if err != nil { + t.Fatalf("%s: %v (fenced=%t); want the lost commit settled as this proposal", what, err, errors.Is(err, storage.ErrChunkLayerFenced)) + } +} + +// Cut 0: two chunks written at different LSNs, so the first chunk's birth +// is below the cut position. +func TestLayoutRemote_LostReplyOfTheFirstCutIsNotAFence(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + lost := &lostThenDownStore{sessionStore: r.st, armed: true} + r.st = lost + want := map[uint32][]byte{3: block(3)} + writeSync(t, s, want) + want[30] = block(30) + writeSync(t, s, map[uint32][]byte{30: want[30]}) + _, err := l.Capture(ctx) + if !lost.lost { + t.Fatal("the fault never fired") + } + requireNotFenced(t, err, "cut 0 with its reply lost") + want[50] = block(50) + writeSync(t, s, map[uint32][]byte{50: want[50]}) + _, err = l.Capture(ctx) + requireNotFenced(t, err, "the cut after") + _ = s.Close() + lh.readBack("b", want) +} + +// Cut 1: one chunk changes, the other is inherited from cut 0. +func TestLayoutRemote_LostReplyOfALaterCutWithAnInheritedChunkIsNotAFence(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + want := map[uint32][]byte{3: block(3)} + writeSync(t, s, want) + if _, err := l.Capture(ctx); err != nil { + t.Fatal(err) + } + lost := &lostThenDownStore{sessionStore: r.st, armed: true} + r.st = lost + want[30] = block(30) + writeSync(t, s, map[uint32][]byte{30: want[30]}) + _, err := l.Capture(ctx) + if !lost.lost { + t.Fatal("the fault never fired") + } + requireNotFenced(t, err, "cut 1 with its reply lost") + _ = s.Close() + lh.readBack("b", want) +} + +// A cut whose image is unchanged (a write that restores the same bytes +// moves only the position): the same proposal, no fence. +func TestLayoutRemote_LostReplyOfANoOpCutIsNotAFence(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + want := map[uint32][]byte{3: block(3), 30: block(30)} + writeSync(t, s, map[uint32][]byte{3: want[3]}) + writeSync(t, s, map[uint32][]byte{30: want[30]}) + if _, err := l.Capture(ctx); err != nil { + t.Fatal(err) + } + lost := &lostThenDownStore{sessionStore: r.st, armed: true} + r.st = lost + writeSync(t, s, map[uint32][]byte{3: want[3]}) // same bytes again + _, err := l.Capture(ctx) + if !lost.lost { + t.Fatal("the fault never fired: the no-op cut committed nothing") + } + requireNotFenced(t, err, "a no-op cut with its reply lost") + _ = s.Close() + lh.readBack("b", want) +} + +// The same across a process restart: the commit applied, its reply was +// lost and HEAD could not be read back, so the process ends with the +// commit unresolved. The restarted process starts on that HEAD and cuts. +func TestLayoutRemote_LostReplyResolvedAcrossAProcessRestart(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + want := map[uint32][]byte{3: block(3)} + writeSync(t, s, want) + if _, err := l.Capture(ctx); err != nil { + t.Fatal(err) + } + lost := &lostThenDownStore{sessionStore: r.st, armed: true, down: true} + r.st = lost + want[30] = block(30) + writeSync(t, s, map[uint32][]byte{30: want[30]}) + if _, err := l.Capture(ctx); err == nil { + t.Fatal("fixture: the cut reported success though its reply was lost and HEAD unreadable") + } + if !lost.lost { + t.Fatal("the fault never fired") + } + _ = s.Close() // the process ends with the commit unresolved + + s2, l2, _ := lh.attach("a", false, false) + defer s2.Close() + want[50] = block(50) + writeSync(t, s2, map[uint32][]byte{50: want[50]}) + _, err := l2.Capture(ctx) + requireNotFenced(t, err, "the restarted process's first cut") + _ = s2.Close() + lh.readBack("b", want) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_session_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_session_test.go new file mode 100644 index 0000000000..b0fde09c8a --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_session_test.go @@ -0,0 +1,194 @@ +package chunkstore + +import ( + "context" + "errors" + "path/filepath" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func headActivity(t *testing.T, lh *layoutHost) layout.Activity { + t.Helper() + h, _, err := lh.cat.ReadHead(context.Background(), lh.v) + if err != nil { + t.Fatal(err) + } + return h.Activity +} + +// The engine's Abort never blocks and writes nothing; the session it gave +// up is ended at the remote's next HEAD read (the next cut's, or a +// scheduler tick's), so HEAD is never left in snap(s) for long. +func TestLayoutRemote_AbortEndsTheSessionAtTheNextHeadRead(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + s, err := r.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if act := headActivity(t, lh); act.Kind != layout.ActSnap || act.Session != s { + t.Fatalf("after Begin: HEAD %+v, want snap(%s)", act, s) + } + r.Abort() + if act := headActivity(t, lh); act.Kind != layout.ActSnap || act.Session != s { + t.Fatalf("Abort wrote HEAD (%+v): it must only take the notice", act) + } + if _, err := r.GetHead(ctx); err != nil { + t.Fatal(err) + } + if act := headActivity(t, lh); act.Kind != layout.ActIdle { + t.Fatalf("after the next HEAD read: HEAD %+v, want the given-up session ended", act) + } +} + +// Abort, and the HEAD read that follows it, never end a session that is +// not this remote's own (epoch, holder and claim id): a newer holder's +// open session survives a deposed remote's Abort. +func TestLayoutRemote_AbortNeverEndsAnotherHoldersSession(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + old, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + if _, err := old.Begin(ctx); err != nil { + t.Fatal(err) + } + st, _ := lh.cat.Store(lh.v) + newer := layout.HolderID{Epoch: 2, Holder: "b", ClaimID: "k-b"} + if _, err := layout.Start(ctx, st, okClaimLease{}, layout.HolderID{Epoch: 2, Holder: "b"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 8 * 4096}, ClaimID: "k-b", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + if _, err := layout.RunBegin(ctx, st, newer, "s-b"); err != nil { + t.Fatal(err) + } + old.Abort() + _, _ = old.GetHead(ctx) // the deposed remote's next read + if act := headActivity(t, lh); act.Kind != layout.ActSnap || act.Session != "s-b" { + t.Fatalf("HEAD after the deposed remote's Abort and read: %+v, want the newer holder's snap(s-b)", act) + } +} + +// The bound on a given-up session with no cut after it: the next cleaning +// tick ends it before it cleans (no Begin, no cut in between), so HEAD +// leaves snap(s) at the next cut, cleaning tick or stop, whichever comes +// first. +func TestLayoutRemote_AbortedSessionEndsAtTheNextCleaningTick(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + s, err := r.Begin(ctx) + if err != nil { + t.Fatal(err) + } + r.Abort() + if act := headActivity(t, lh); act.Kind != layout.ActSnap || act.Session != s { + t.Fatalf("after Abort: HEAD %+v, want the given-up snap(%s) still there", act, s) + } + ran := false + if err := r.Clean(ctx, func(context.Context, layout.HolderID, string) error { + ran = true + if act := headActivity(t, lh); act.Kind != layout.ActClean { + t.Fatalf("while cleaning: HEAD %+v, want the session ended and clean open", act) + } + return nil + }); err != nil { + t.Fatal(err) + } + if act := headActivity(t, lh); !ran || act.Kind != layout.ActIdle { + t.Fatalf("after the cleaning tick: ran=%t HEAD %+v, want idle", ran, act) + } +} + +// countingRemote counts the engine's uploads and the commits the kernel +// refuses as not prepared (uploads of an ended session). +type countingRemote struct { + *LayoutRemote + puts, notPrepared int + again []string // keys uploaded more than once + seen map[string]bool +} + +func (c *countingRemote) Put(ctx context.Context, key string, data []byte) error { + c.puts++ + if c.seen == nil { + c.seen = map[string]bool{} + } + if c.seen[key] { + c.again = append(c.again, key) + } + c.seen[key] = true + return c.LayoutRemote.Put(ctx, key, data) +} + +func (c *countingRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + gen, err := c.LayoutRemote.CASHead(ctx, expected, next) + if errors.Is(err, layout.ErrNotPrepared) { + c.notPrepared++ + } + return gen, err +} + +// A cut refused by admission after its uploads keeps them and their +// session; the retry commits them in that session: no commit is refused as +// not prepared and nothing is uploaded again (pre-copy converges under +// sustained writes). +func TestLayoutRemote_AdmissionRefusalKeepsTheSessionSoTheRetryConverges(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, err := storage.CreateWALStoreWithOptions(filepath.Join(lh.dir, "adm"), lrBlocks, 4096, storage.WALStoreOptions{ChunkBlocks: lrChunkBlocks}) + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + lr, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + r := &countingRemote{LayoutRemote: lr} + refuse := true + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: lrChunkBlocks, Epoch: lh.me.Epoch, Holder: lh.me.Holder, FreshFromHead: true, + CaptureAllowed: func() error { + if refuse && r.puts > 0 { // refused after the uploads, before the commit + return errors.New("demoted") + } + return nil + }}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + writeSync(t, s, map[uint32][]byte{1: block(1), 9: block(9), 17: block(17)}) + if _, err := l.Cut(ctx); err == nil { + t.Fatal("cut refused by admission returned success") + } + uploaded := r.puts + if uploaded == 0 { + t.Fatal("control: the refusal came before any upload") + } + if act := headActivity(t, lh); act.Kind != layout.ActSnap { + t.Fatalf("after the refusal: HEAD %+v, want the cut's session still open", act) + } + refuse = false + if _, err := l.Cut(ctx); err != nil { + t.Fatalf("retry: %v", err) + } + if r.notPrepared != 0 || len(r.again) != 0 { + t.Fatalf("retry: %d commits refused as not prepared, uploaded again %q; want 0 and none", r.notPrepared, r.again) + } + if act := headActivity(t, lh); act.Kind != layout.ActIdle { + t.Fatalf("after the retry: HEAD %+v, want the commit to end the session", act) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_sites_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_sites_test.go new file mode 100644 index 0000000000..793bdd736f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_sites_test.go @@ -0,0 +1,89 @@ +package chunkstore + +import ( + "go/parser" + "go/token" + "os" + "path/filepath" + "strconv" + "strings" + "testing" +) + +// layoutRemoteSites are the production calls of NewLayoutRemote: one, the +// blockvolume's ChunkLayoutRemoteFor, which the durable provider calls once +// per attachment and caches (its LayoutRemote accessor returns that one). +// A second LayoutRemote of a volume in a process would roll back the +// first's live session at its first HEAD read, so a new site fails here. +var layoutRemoteSites = map[string]int{"cmd/blockvolume/main.go": 1} + +func TestLayoutRemote_OneConstructorSite(t *testing.T) { + root := filepath.Join("..", "..", "..") + found := map[string]int{} + for _, top := range []string{"core", "cmd"} { + err := filepath.Walk(filepath.Join(root, top), func(p string, fi os.FileInfo, err error) error { + if err != nil || fi.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return err + } + rel, _ := filepath.Rel(root, p) + // durable/testutil is a fixture package, never a production constructor site. + if strings.HasPrefix(filepath.ToSlash(rel), "core/frontend/durable/testutil/") { + return nil + } + b, err := os.ReadFile(p) + if err != nil { + return err + } + if n := strings.Count(string(b), "NewLayoutRemote("); n > 0 && !strings.HasSuffix(filepath.ToSlash(p), "chunkstore/layout_remote.go") { + found[filepath.ToSlash(rel)] = n + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + if len(found) != len(layoutRemoteSites) { + t.Fatalf("NewLayoutRemote production sites %v; want %v (one runtime per attachment)", found, layoutRemoteSites) + } + for f, n := range layoutRemoteSites { + if found[f] != n { + t.Fatalf("NewLayoutRemote production sites %v; want %v (one runtime per attachment)", found, layoutRemoteSites) + } + } +} + +// A production import would turn the fixture-package exception above into a +// blind spot, so the import boundary is guarded independently. +func TestLayoutRemote_NoProductionTestutilImports(t *testing.T) { + root := filepath.Join("..", "..", "..") + const fixtureImport = "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" + for _, top := range []string{"core", "cmd"} { + err := filepath.Walk(filepath.Join(root, top), func(p string, fi os.FileInfo, err error) error { + if err != nil || fi.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return err + } + rel, _ := filepath.Rel(root, p) + if strings.HasPrefix(filepath.ToSlash(rel), "core/frontend/durable/testutil/") { + return nil + } + f, err := parser.ParseFile(token.NewFileSet(), p, nil, parser.ImportsOnly) + if err != nil { + return err + } + for _, imp := range f.Imports { + name, err := strconv.Unquote(imp.Path.Value) + if err != nil { + return err + } + if name == fixtureImport || strings.HasPrefix(name, fixtureImport+"/") { + t.Errorf("production file %s imports durable/testutil", filepath.ToSlash(rel)) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_states_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_states_test.go new file mode 100644 index 0000000000..249aa7233a --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_states_test.go @@ -0,0 +1,193 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// The layout remote's in-memory state machine, closed as one table: every +// start state crossed with every call, with the error class, HEAD's +// activity after the call, and whether a pending name was committed. +// +// States (what the remote holds against what HEAD says): +// +// idle no session; HEAD idle (the engine has read HEAD) +// open session s held; HEAD snap(s) +// abandoned session s held, the engine's Abort notice taken; HEAD snap(s) +// pending no session, a snapshot name set; HEAD idle +// dead no session, nothing read yet; HEAD snap(d) of this holder (a dead process's) +// cleaning this remote's cleaning tick running; HEAD clean(c) +// +// The other in-memory pieces (visible/ownGen/seen/forceView, cleaning, +// snapErr, lastCommit) are covered by their own tests. The seam's calls +// are the kernel's: Begin opens the cut's session, Abort is the engine's +// notice that it gave a cut up. +func TestLayoutRemote_StateByCallTable(t *testing.T) { + ctx := context.Background() + type outcome struct { + err string // "", "precondition", "busy" + act string // HEAD activity kind after the call + named bool // the pending name is in HEAD after the call + settled string // AbortOpenSession's answer, when the call is it + } + // Abort is the engine's non-blocking notice: it writes nothing, so HEAD + // is what the state left; the next HEAD read ends the session. + // Clean is the cleaning (maintenance) tick: it ends a given-up session + // (abandoned, dead) before it cleans, and is refused while one is held. + calls := []string{"GetHead", "Begin", "Put", "CASHead", "Abort", "Clean", "AbortOpenSession", "CommitPendingSnapshot"} + table := map[string]map[string]outcome{ + "idle": { + "Clean": {act: layout.ActIdle}, + "Abort": {act: layout.ActIdle}, + "GetHead": {act: layout.ActIdle}, "Begin": {act: layout.ActSnap}, "Put": {act: layout.ActSnap}, + "CASHead": {act: layout.ActIdle}, "AbortOpenSession": {act: layout.ActIdle, settled: SessionIdle}, + "CommitPendingSnapshot": {act: layout.ActIdle}, + }, + "open": { + "Clean": {err: "busy", act: layout.ActSnap}, + "Abort": {act: layout.ActSnap}, + "GetHead": {act: layout.ActSnap}, "Begin": {act: layout.ActSnap}, "Put": {act: layout.ActSnap}, + "CASHead": {act: layout.ActIdle}, "AbortOpenSession": {act: layout.ActIdle, settled: SessionAborted}, + "CommitPendingSnapshot": {act: layout.ActSnap}, + }, + "abandoned": { + "Clean": {act: layout.ActIdle}, + "Abort": {act: layout.ActSnap}, + "GetHead": {act: layout.ActIdle}, "Begin": {act: layout.ActSnap}, "Put": {act: layout.ActSnap}, + "CASHead": {act: layout.ActIdle}, "AbortOpenSession": {act: layout.ActIdle, settled: SessionAborted}, + "CommitPendingSnapshot": {act: layout.ActSnap}, + }, + "pending": { + "Clean": {act: layout.ActIdle}, + "Abort": {act: layout.ActIdle}, + "GetHead": {act: layout.ActIdle}, "Begin": {act: layout.ActSnap}, "Put": {act: layout.ActSnap}, + "CASHead": {act: layout.ActIdle, named: true}, "AbortOpenSession": {act: layout.ActIdle, settled: SessionIdle}, + "CommitPendingSnapshot": {act: layout.ActIdle, named: true}, + }, + "cleaning": { + "Clean": {err: "busy", act: layout.ActClean}, + "Abort": {act: layout.ActClean}, + "GetHead": {act: layout.ActClean}, "Begin": {act: layout.ActSnap}, "Put": {act: layout.ActSnap}, + "CASHead": {act: layout.ActIdle}, "AbortOpenSession": {act: layout.ActIdle, settled: SessionIdle}, + "CommitPendingSnapshot": {act: layout.ActClean}, + }, + "dead": { + "Clean": {act: layout.ActIdle}, + "Abort": {act: layout.ActSnap}, + "GetHead": {act: layout.ActIdle}, "Begin": {act: layout.ActSnap}, "Put": {act: layout.ActSnap}, + "CASHead": {err: "precondition", act: layout.ActSnap}, "AbortOpenSession": {act: layout.ActIdle, settled: SessionAborted}, + "CommitPendingSnapshot": {act: layout.ActSnap}, + }, + } + setup := func(t *testing.T, state string) (*layoutHost, *LayoutRemote) { + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + if state != "dead" { + if _, err := r.GetHead(ctx); err != nil { + t.Fatal(err) + } + } + switch state { + case "open": + if _, err := r.Begin(ctx); err != nil { + t.Fatal(err) + } + case "abandoned": + if _, err := r.Begin(ctx); err != nil { + t.Fatal(err) + } + r.Abort() + case "pending": + r.SetSnapshot("p", layout.SnapshotMeta{CreatedNs: 1}) + case "cleaning": + // a cleaning tick that runs until a session's call stops it + // (or the test ends) + release, started, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) + go func() { + defer close(done) + _ = r.Clean(ctx, func(cctx context.Context, _ layout.HolderID, _ string) error { + close(started) + select { + case <-cctx.Done(): + case <-release: + } + return nil + }) + }() + <-started + t.Cleanup(func() { close(release); <-done }) + case "dead": + st, _ := lh.cat.Store(lh.v) + if _, err := layout.RunBegin(ctx, st, lh.me, "s-dead"); err != nil { + t.Fatal(err) + } + } + return lh, r + } + data := block(9) + for state, row := range table { + for _, call := range calls { + want, ok := row[call] + if !ok { + t.Fatalf("table has no cell %s x %s", state, call) + } + t.Run(state+"/"+call, func(t *testing.T) { + lh, r := setup(t, state) + var err error + var settled string + switch call { + case "GetHead": + _, err = r.GetHead(ctx) + case "Begin": + _, err = r.Begin(ctx) + case "Put": + err = r.Put(ctx, r.ChunkKey(3, layout.Sum(data)), data) + case "CASHead": + err = func() error { + _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: r.visible, Epoch: lh.me.Epoch}, storage.ChunkHead{Epoch: lh.me.Epoch, Chunks: map[uint64]storage.ChunkRef{}}) + return err + }() + case "Abort": + r.Abort() + case "Clean": + err = r.Clean(ctx, func(context.Context, layout.HolderID, string) error { return nil }) + case "AbortOpenSession": + settled, err = r.AbortOpenSession(ctx) + case "CommitPendingSnapshot": + err = r.CommitPendingSnapshot(ctx) + } + switch want.err { + case "": + if err != nil { + t.Fatalf("%s x %s: %v", state, call, err) + } + case "precondition": + if !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("%s x %s: %v; want a precondition", state, call, err) + } + case "busy": + if !errors.Is(err, layout.ErrBusy) { + t.Fatalf("%s x %s: %v; want busy", state, call, err) + } + } + h := lh.head() + if h.Activity.Kind != want.act { + t.Fatalf("%s x %s: HEAD %s after the call; want %s", state, call, h.Activity.Kind, want.act) + } + if _, named := h.Snapshots["p"]; named != want.named { + t.Fatalf("%s x %s: pending name in HEAD %t; want %t", state, call, named, want.named) + } + if settled != want.settled { + t.Fatalf("%s x %s: settled %q; want %q", state, call, settled, want.settled) + } + }) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote_test.go b/seaweed-block/core/frontend/chunkstore/layout_remote_test.go new file mode 100644 index 0000000000..32c989fae6 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_remote_test.go @@ -0,0 +1,762 @@ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const lrBlocks, lrChunkBlocks = 64, 8 + +// layoutHost is one host of a layout volume: its catalog, its claimed line, +// and attach() for a local store over a fresh LayoutRemote (as after a +// process start: no session in memory). +type layoutHost struct { + t *testing.T + cat *BCatalog + v VolumeRef + me layout.HolderID + dir string +} + +func newLayoutHost(t *testing.T) *layoutHost { + t.Helper() + ctx := context.Background() + cat, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + v := newRef(t, "v") + if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 8 * 4096}); err != nil { + t.Fatal(err) + } + s, _ := cat.Store(v) + me := layout.HolderID{Epoch: 1, Holder: "a", ClaimID: "k-a"} + if _, err := layout.Start(ctx, s, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "a"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 8 * 4096}, ClaimID: "k-a", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + return &layoutHost{t: t, cat: cat, v: v, me: me, dir: t.TempDir()} +} + +// attach opens (create: a new local store) the store named name over a new +// LayoutRemote. +func (lh *layoutHost) attach(name string, create, fresh bool) (*storage.WALStore, storage.ChunkLayer, *LayoutRemote) { + t := lh.t + t.Helper() + p := filepath.Join(lh.dir, name) + var s *storage.WALStore + var err error + if create { + s, err = storage.CreateWALStoreWithOptions(p, lrBlocks, 4096, storage.WALStoreOptions{ChunkBlocks: lrChunkBlocks}) + } else { + s, err = storage.OpenWALStore(p) + } + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: lrChunkBlocks, Epoch: lh.me.Epoch, Holder: lh.me.Holder, FreshFromHead: fresh}) + if err != nil { + t.Fatal(err) + } + return s, l, r +} + +func (lh *layoutHost) head() layout.Head { + h, _, err := lh.cat.ReadHead(context.Background(), lh.v) + if err != nil { + lh.t.Fatal(err) + } + return h +} + +func block(b byte) []byte { return bytes.Repeat([]byte{b}, 4096) } + +func writeSync(t *testing.T, s *storage.WALStore, w map[uint32][]byte) { + t.Helper() + for lba, d := range w { + if _, err := s.Write(lba, d); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } +} + +// readBack attaches a fresh local store and checks every block reads as want +// (zero elsewhere), fetched lazily from HEAD through the layout. +func (lh *layoutHost) readBack(name string, want map[uint32][]byte) { + t := lh.t + t.Helper() + s, _, _ := lh.attach(name, true, true) + defer s.Close() + zero := make([]byte, 4096) + for lba := uint32(0); lba < lrBlocks; lba++ { + got, err := s.Read(lba) + if err != nil { + t.Fatalf("read back %d: %v", lba, err) + } + exp, ok := want[lba] + if !ok { + exp = zero + } + if !bytes.Equal(got, exp) { + t.Fatalf("block %d = %x...; want %x...", lba, got[:2], exp[:2]) + } + } +} + +// The engine's cut commits through the layout: HEAD is idle at the cut's +// position with the chunks as content-named objects, a named snapshot is +// recorded with its facts, and a fresh host reads everything back. +func TestLayoutRemote_CutCommitsThroughTheKernel(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + want := map[uint32][]byte{0: block(1), 9: block(2), 17: block(3), 63: block(4)} + writeSync(t, s, want) + h1, err := l.Capture(ctx) + if err != nil { + t.Fatalf("capture: %v", err) + } + if h := lh.head(); h.Position != h1 || h.Activity.Kind != layout.ActIdle || h.Current == nil { + t.Fatalf("HEAD after the cut: %+v; want idle at %d with a root", h, h1) + } + want[9] = block(9) + writeSync(t, s, map[uint32][]byte{9: want[9]}) + r.SetSnapshot("daily", layout.SnapshotMeta{CreatedNs: 5, Class: layout.ClassSemantic}) + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("named capture: %v", err) + } + if sn, ok := lh.head().Snapshots["daily"]; !ok || sn.Meta.Class != layout.ClassSemantic || sn.Meta.CreatedNs != 5 { + t.Fatalf("snapshot daily: %+v %t", sn, ok) + } + _ = s.Close() + lh.readBack("b", want) +} + +// A crash inside a session (Begin applied, no commit): the restarted +// process's first call rolls the dead session back; its base names the +// last commit's generation while HEAD is two later with the same root and +// position, and the cut after it uploads everything written since that +// position: the read-back has every acknowledged write. +func TestLayoutRemote_CrashInsideASessionRollsBack(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + want := map[uint32][]byte{0: block(1), 20: block(2)} + writeSync(t, s, want) + if _, err := l.Capture(ctx); err != nil { + t.Fatal(err) + } + committed := lh.head() + // Written after the last commit, then a cut that dies after its Begin. + want[20], want[40] = block(7), block(8) + writeSync(t, s, map[uint32][]byte{20: want[20], 40: want[40]}) + if _, err := r.Begin(ctx); err != nil { + t.Fatal(err) + } + if h := lh.head(); h.Activity.Kind != layout.ActSnap { + t.Fatalf("HEAD after the Begin: %+v", h.Activity) + } + _ = s.Close() // the process dies: its session id dies with it + + s2, l2, _ := lh.attach("a", false, false) + defer s2.Close() + if h := lh.head(); h.Activity.Kind != layout.ActIdle || h.Gen != committed.Gen+2 || *h.Current != *committed.Current || h.Position != committed.Position { + t.Fatalf("HEAD after the restart: gen %d activity %+v; want idle at gen %d, same root and position", h.Gen, h.Activity, committed.Gen+2) + } + if _, err := l2.Capture(ctx); err != nil { + t.Fatalf("cut after the restart: %v", err) + } + _ = s2.Close() + lh.readBack("c", want) +} + +// The engine's keys are layout references: a key that does not name its +// bytes, another volume's key for an upload, and a non-layout key are +// refused before anything is written. +func TestLayoutRemote_KeysNameTheirBytes(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + data := block(3) + good := r.ChunkKey(2, layout.Sum(data)) + other := LayoutKey(layout.Ref{Owner: "x", OwnerID: layout.VolumeID{9}, Chunk: layout.NameChunk(2, data)}) + for name, key := range map[string]string{ + "wrong bytes": r.ChunkKey(2, layout.Sum(block(4))), + "other volume": other, + "not layout key": "chunks/e1/c2/n-1", + } { + if err := r.Put(ctx, key, data); !errors.Is(err, storage.ErrChunkKeyInvalid) { + t.Errorf("put with %s: %v; want ErrChunkKeyInvalid", name, err) + } + } + if h := lh.head(); h.Activity.Kind != layout.ActIdle { + t.Fatalf("a refused put opened a session: %+v", h.Activity) + } + if err := r.Put(ctx, good, data); err != nil { + t.Fatal(err) + } + if got, err := r.Get(ctx, good); err != nil || !bytes.Equal(got, data) { + t.Fatalf("get %s: %v", good, err) + } + back, err := ParseLayoutKey(good) + if err != nil || LayoutKey(back) != good { + t.Fatalf("key round trip: %v", err) + } +} + +// The seam's closure table: every kernel result maps to one engine action. +func TestLayoutRemote_ErrorMap(t *testing.T) { + other := errors.New("connection refused") + for _, c := range []struct { + err error + want error // nil: returned as it is + }{ + {layout.ErrNotHolder, storage.ErrChunkLayerFenced}, + {layout.ErrStaleEpoch, storage.ErrChunkLayerFenced}, + {layout.ErrDetached, storage.ErrChunkLayerFenced}, + {layout.ErrPrecondition, storage.ErrChunkHeadPrecondition}, + {layout.ErrNoSession, storage.ErrChunkHeadPrecondition}, + {layout.ErrVolumeDeleting, storage.ErrChunkHeadDeleted}, + {layout.ErrBusy, storage.ErrChunkRemoteUnavailable}, + {other, storage.ErrChunkRemoteUnavailable}, + {layout.ErrCorrupt, ErrRemoteDamaged}, + {layout.ErrIdentity, ErrRemoteDamaged}, + {layout.ErrMissing, ErrRemoteDamaged}, + {layout.ErrNotPrepared, nil}, + {layout.ErrTooManySnapshots, nil}, + {layout.ErrSnapshotExists, nil}, + } { + got := layoutRemoteErr(c.err) + if !errors.Is(got, c.err) { + t.Errorf("%v: mapped to %v, which no longer wraps it", c.err, got) + } + if c.want != nil && !errors.Is(got, c.want) { + t.Errorf("%v: mapped to %v; want %v", c.err, got, c.want) + } + for _, cls := range []error{storage.ErrChunkLayerFenced, storage.ErrChunkHeadPrecondition, storage.ErrChunkHeadDeleted, storage.ErrChunkRemoteUnavailable, ErrRemoteDamaged} { + if cls != c.want && errors.Is(got, cls) { + t.Errorf("%v: also maps to %v", c.err, cls) + } + } + } + if layoutRemoteErr(nil) != nil { + t.Fatal("nil mapped to an error") + } +} + +// lostReplyStore applies the next HEAD update and then reports an error, +// as a store whose reply was lost. +type lostReplyStore struct { + sessionStore + armed bool +} + +func (s *lostReplyStore) UpdateHead(ctx context.Context, gen uint64, next layout.Head) error { + err := s.sessionStore.UpdateHead(ctx, gen, next) + if err == nil && s.armed && next.Activity.Kind == layout.ActIdle { + s.armed = false + return errors.New("reply lost") + } + return err +} + +// A commit that applied and lost its reply leaves no stale session: the +// engine's next HEAD read settles it, and the next cut commits. +func TestLayoutRemote_ACommitWhoseReplyIsLostDoesNotLivelock(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + lost := &lostReplyStore{sessionStore: r.st, armed: true} + r.st = lost + want := map[uint32][]byte{3: block(3)} + writeSync(t, s, want) + _, _ = l.Capture(ctx) // the commit applied, its reply lost + if lost.armed { + t.Fatal("the fault never fired") + } + want[30] = block(30) + writeSync(t, s, map[uint32][]byte{30: want[30]}) + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("the cut after a lost commit reply: %v", err) + } + if h := lh.head(); h.Activity.Kind != layout.ActIdle { + t.Fatalf("HEAD after the second cut: %+v", h.Activity) + } + _ = s.Close() + lh.readBack("b", want) +} + +// Only the full encoding reaches the layout: any other is refused before a +// commit is written. +func TestLayoutRemote_RefusesOtherEncodings(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + h0, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + data := block(5) + key := r.ChunkKey(0, layout.Sum(data)) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: {Key: key, SHA256: layout.Sum(data), Encoding: "zstd"}}} + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h0.Gen, Epoch: 1}, next); !errors.Is(err, ErrUnsupportedEncoding) { + t.Fatalf("commit of a zstd chunk: %v; want ErrUnsupportedEncoding", err) + } + if h := lh.head(); h.Current != nil { + t.Fatal("a refused encoding committed a root") + } +} + +// A snapshot name the kernel refuses (taken, here) does not stop the cut: +// it commits unnamed and the request gets the typed refusal. +func TestLayoutRemote_ARefusedSnapshotNameStillCommitsTheCut(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{1: block(1)}) + r.SetSnapshot("daily", layout.SnapshotMeta{CreatedNs: 1}) + if _, err := l.Capture(ctx); err != nil || r.TakeSnapshotErr() != nil { + t.Fatal(err) + } + writeSync(t, s, map[uint32][]byte{2: block(2)}) + r.SetSnapshot("daily", layout.SnapshotMeta{CreatedNs: 2}) + h2, err := l.Capture(ctx) + if err != nil { + t.Fatalf("cut with a taken snapshot name: %v", err) + } + if err := r.TakeSnapshotErr(); !errors.Is(err, layout.ErrSnapshotExists) { + t.Fatalf("snapshot refusal: %v; want ErrSnapshotExists", err) + } + if h := lh.head(); h.Position != h2 || h.Snapshots["daily"].Meta.CreatedNs != 1 { + t.Fatalf("HEAD after the refused name: position %d, daily %+v", h.Position, h.Snapshots["daily"]) + } +} + +// A cut while this process's own cleaning is open ends the cleaning and +// commits (never busy); a cleaning left open by a dead process is ended by +// the next start's first call. +func TestLayoutRemote_ACutEndsMyOwnCleaning(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + started := make(chan struct{}) + cleaned := make(chan error, 1) + go func() { + cleaned <- r.Clean(ctx, func(ctx context.Context, _ layout.HolderID, _ string) error { + close(started) + <-ctx.Done() + return ctx.Err() + }) + }() + <-started + writeSync(t, s, map[uint32][]byte{4: block(4)}) + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("cut during my own cleaning: %v", err) + } + if err := <-cleaned; err != nil { + t.Fatalf("the cancelled cleaning: %v", err) + } + // A dead process's cleaning: HEAD clean(c) of mine, nothing in memory. + st, _ := lh.cat.Store(lh.v) + if _, err := layout.RunBeginClean(ctx, st, lh.me, "c-dead"); err != nil { + t.Fatal(err) + } + r2, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + if _, err := r2.GetHead(ctx); err != nil { + t.Fatal(err) + } + if h := lh.head(); h.Activity.Kind != layout.ActIdle { + t.Fatalf("a dead cleaning after the restart's first call: %+v", h.Activity) + } +} + +// failingCreateStore fails object creates while armed: an upload error. +type failingCreateStore struct { + sessionStore + armed bool +} + +func (s *failingCreateStore) Create(ctx context.Context, rel string, data []byte, session string) error { + if s.armed { + return errors.New("volume server unreachable") + } + return s.sessionStore.Create(ctx, rel, data, session) +} + +// A named cut the engine gives up (an upload fails) leaves no name behind: +// the next, unnamed cut commits without it, from a new session. +func TestLayoutRemote_AnAbandonedNamedCutDropsItsName(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + fail := &failingCreateStore{sessionStore: r.st, armed: true} + r.st = fail + writeSync(t, s, map[uint32][]byte{5: block(5)}) + r.SetSnapshot("weekly", layout.SnapshotMeta{CreatedNs: 1}) + if _, err := l.Capture(ctx); err == nil { + t.Fatal("a cut whose upload failed committed") + } + // The failed cut keeps its session for the retry; the snapshot request + // that failed withdraws its name (SnapshotVolume does), so the retry + // names nothing. + r.DropSnapshot() + fail.armed = false + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("the cut after the abandoned one: %v", err) + } + h := lh.head() + if _, named := h.Snapshots["weekly"]; named || h.Activity.Kind != layout.ActIdle { + t.Fatalf("after the abandoned named cut: snapshots %v, activity %+v; want no weekly, idle", h.Snapshots, h.Activity) + } +} + +// My session ended behind this remote's back: the remote drops it, the +// engine re-reads HEAD after one refused cut, and the next cut begins a +// new session and commits (no cut is refused for ever). +func TestLayoutRemote_ASessionLostWhileAliveIsReplaced(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + want := map[uint32][]byte{6: block(6)} + writeSync(t, s, want) + if _, err := r.Begin(ctx); err != nil { + t.Fatal(err) + } + st, _ := lh.cat.Store(lh.v) + if _, err := layout.RunAbort(ctx, st, lh.me, lh.head().Activity.Session); err != nil { + t.Fatal(err) + } + // The abort is a write the engine did not see: its first cut after it + // is a precondition (the engine re-reads HEAD); the next commits. + if _, err := l.Capture(ctx); err != nil && !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("first cut after my session was aborted behind my back: %v", err) + } + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("cut after the re-read: %v", err) + } + if h := lh.head(); h.Activity.Kind != layout.ActIdle || h.Current == nil { + t.Fatalf("HEAD after the cut: %+v", h) + } + _ = s.Close() + lh.readBack("b", want) +} + +// Uploads staged in a session that has since ended (rolled back by this +// remote) are not prepared for the next session's commit: the commit is a +// precondition, the engine's re-read drops what it staged, and the retry +// uploads again and commits. +func TestLayoutRemote_StagedUploadsOfAnEndedSessionAreRedone(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + h0, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + data := block(8) + key := r.ChunkKey(0, layout.Sum(data)) + if err := r.Put(ctx, key, data); err != nil { // staged in session s1 + t.Fatal(err) + } + // s1 ends (the cut was abandoned); a new session opens on the next call. + r.Abort() + next := storage.ChunkHead{Epoch: 1, RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: {Key: key, SHA256: layout.Sum(data), Encoding: "full"}}} + _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h0.Gen, Epoch: 1}, next) + if !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("commit naming an upload of an ended session: %v; want a precondition", err) + } + h1, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if h1.Gen == h0.Gen { + t.Fatal("the engine's re-read sees the same generation: it would keep what it staged") + } + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h1.Gen, Epoch: 1}, next); err != nil { + t.Fatalf("the retry after uploading again: %v", err) + } +} + +// A snapshot name the commit would refuse for its form (too long, here) is +// refused before the commit, and the cut commits unnamed; a malformed +// manifest is never reported as a name refusal. +func TestLayoutRemote_ABadSnapshotNameIsRefusedBeforeTheCommit(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{1: block(1)}) + r.SetSnapshot(strings.Repeat("n", layout.MaxSnapshotNameBytes+1), layout.SnapshotMeta{}) + h, err := l.Capture(ctx) + if err != nil { + t.Fatalf("cut with a too-long snapshot name: %v", err) + } + if err := r.TakeSnapshotErr(); !errors.Is(err, layout.ErrMalformed) { + t.Fatalf("name refusal: %v; want ErrMalformed", err) + } + if hd := lh.head(); hd.Position != h || len(hd.Snapshots) != 0 { + t.Fatalf("HEAD after the refused name: %+v", hd) + } +} + +// Writes of others that leave the image alone (a snapshot delete, a +// retention pass) do not move the engine's view: the next cut commits +// without a precondition and uploads nothing. +func TestLayoutRemote_AForeignSnapshotDeleteDoesNotMoveTheView(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{2: block(2)}) + r.SetSnapshot("old", layout.SnapshotMeta{CreatedNs: 1}) + if _, err := l.Capture(ctx); err != nil { + t.Fatal(err) + } + before, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := lh.cat.DeleteSnapshot(ctx, lh.v, "old"); err != nil { + t.Fatal(err) + } + after, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if after.Gen != before.Gen { + t.Fatalf("a snapshot delete moved the engine's view: gen %d -> %d", before.Gen, after.Gen) + } + writeSync(t, s, map[uint32][]byte{3: block(3)}) + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("cut after a foreign snapshot delete: %v", err) + } +} + +// After an abandoned cut, a cleaning is not refused busy: it takes the +// abandon notice first. +func TestLayoutRemote_CleaningAfterAnAbandonedCut(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + if _, err := r.Begin(ctx); err != nil { + t.Fatal(err) + } + r.Abort() + if err := r.Clean(ctx, func(context.Context, layout.HolderID, string) error { return nil }); err != nil { + t.Fatalf("cleaning after an abandoned cut: %v", err) + } + if h := lh.head(); h.Activity.Kind != layout.ActIdle { + t.Fatalf("HEAD after the cleaning: %+v", h.Activity) + } +} + +// AbortOpenSession settles a stop: an open session (held here, or left by +// a dead process) is rolled back and its pending name dropped; a detached +// HEAD of this holder reports detached; nothing open reports idle. +func TestLayoutRemote_AbortOpenSession(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + if got, err := r.AbortOpenSession(ctx); err != nil || got != SessionIdle { + t.Fatalf("nothing open: %q %v", got, err) + } + r.SetSnapshot("x", layout.SnapshotMeta{}) + if _, err := r.Begin(ctx); err != nil { + t.Fatal(err) + } + if got, err := r.AbortOpenSession(ctx); err != nil || got != SessionAborted || lh.head().Activity.Kind != layout.ActIdle { + t.Fatalf("own open session: %q %v, HEAD %+v", got, err, lh.head().Activity) + } + if _, err := r.GetHead(ctx); err != nil { + t.Fatal(err) + } + if r.pending != nil || r.session != "" { + t.Fatal("the aborted session or its pending name is still held after the next call") + } + // A dead process's session. + st, _ := lh.cat.Store(lh.v) + if _, err := layout.RunBegin(ctx, st, lh.me, "s-dead"); err != nil { + t.Fatal(err) + } + if got, err := r.AbortOpenSession(ctx); err != nil || got != SessionAborted { + t.Fatalf("a dead process's session: %q %v", got, err) + } + // A detached HEAD of this holder. + s, l, _ := lh.attach("a", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{1: block(1)}) + if _, err := l.Capture(ctx); err != nil { + t.Fatal(err) + } + h := lh.head() + if _, err := layout.RunBegin(ctx, st, lh.me, "s-stop"); err != nil { + t.Fatal(err) + } + { + // The stop's final commit: the current image, detached. + m := map[uint64]layout.Ref{} + img, _ := layout.NewReader("/blocks", lh.v.Dir(), st.Fetch) + im, _ := img.Open(ctx, *h.Current) + for _, sh := range im.Shards() { + seg, _, _ := im.Segment(ctx, sh) + for i, ref := range seg.Chunks { + m[i] = ref + } + } + root, segs, _ := layout.Build(m) + rn, rb, _ := layout.NameRoot(root) + for n, b := range segs { + _ = layout.EnsureObject(ctx, st, n.Path(), b, "s-stop") + } + _ = layout.EnsureObject(ctx, st, rn.Path(), rb, "s-stop") + if _, err := layout.RunCommit(ctx, st, st, lh.v.Name, lh.me, layout.CommitRequest{Session: "s-stop", Prev: m, Next: m, Position: h.Position, State: layout.StateDetached}); err != nil { + t.Fatal(err) + } + } + if got, err := r.AbortOpenSession(ctx); err != nil || got != SessionDetached { + t.Fatalf("a detached HEAD: %q %v", got, err) + } +} + +// blockingCommitStore holds the next commit (an idle HEAD update) inside +// its update until released. +type blockingCommitStore struct { + sessionStore + entered, release chan struct{} +} + +func (s *blockingCommitStore) UpdateHead(ctx context.Context, gen uint64, next layout.Head) error { + if next.Activity.Kind == layout.ActIdle && s.entered != nil { + close(s.entered) + s.entered = nil + <-s.release + } + return s.sessionStore.UpdateHead(ctx, gen, next) +} + +// The abort never waits behind the commit it aborts: while a commit is held +// inside its HEAD update, AbortOpenSession completes (aborted), and the +// commit then fails its condition. +func TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, l, r := lh.attach("a", true, true) + defer s.Close() + hold := &blockingCommitStore{sessionStore: r.st, entered: make(chan struct{}), release: make(chan struct{})} + entered := hold.entered + r.st = hold + writeSync(t, s, map[uint32][]byte{7: block(7)}) + cut := make(chan error, 1) + go func() { _, err := l.Capture(ctx); cut <- err }() + <-entered + done := make(chan struct{}) + var got string + var aerr error + go func() { got, aerr = r.AbortOpenSession(ctx); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + close(hold.release) + t.Fatal("AbortOpenSession waited behind the held commit") + } + if aerr != nil || got != SessionAborted { + t.Fatalf("abort during a held commit: %q %v; want aborted", got, aerr) + } + close(hold.release) + if err := <-cut; err == nil { + t.Fatal("the held commit applied after its session was aborted") + } + if h := lh.head(); h.Activity.Kind != layout.ActIdle { + t.Fatalf("HEAD after the abort: %+v", h.Activity) + } +} + +// A HEAD of another holder, epoch or claim id is a fence for the stop's +// settle, never idle (which would let it resume). +func TestLayoutRemote_AbortOpenSessionFencesAForeignHead(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + for name, me := range map[string]layout.HolderID{ + "another holder": {Epoch: 1, Holder: "b", ClaimID: "k-a"}, + "another epoch": {Epoch: 2, Holder: "a", ClaimID: "k-a"}, + "another claim id": {Epoch: 1, Holder: "a", ClaimID: "k-other"}, + } { + r, err := NewLayoutRemote(lh.cat, lh.v, me) + if err != nil { + t.Fatal(err) + } + if got, err := r.AbortOpenSession(ctx); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Errorf("%s: %q %v; want ErrChunkLayerFenced", name, got, err) + } + } +} + +// A layout key has exactly one spelling per reference: a key that does +// not round-trip, or names no volume, is refused. +func TestLayoutRemote_KeysAreCanonical(t *testing.T) { + data := block(1) + id := layout.VolumeID{0xab, 0xcd} + good := LayoutKey(layout.Ref{Owner: "v", OwnerID: id, Chunk: layout.NameChunk(7, data)}) + ref, err := ParseLayoutKey(good) + if err != nil || LayoutKey(ref) != good { + t.Fatalf("canonical key %q: %+v %v", good, ref, err) + } + upper := "layout:v:" + strings.ToUpper(id.String()) + ":" + layout.NameChunk(7, data).String() + padded := strings.Replace(good, ":7-", ":07-", 1) + zero := LayoutKey(layout.Ref{Owner: "v", Chunk: layout.NameChunk(7, data)}) + noOwner := "layout::" + id.String() + ":" + layout.NameChunk(7, data).String() + for name, k := range map[string]string{"uppercase id": upper, "padded index": padded, "zero owner id": zero, "empty owner": noOwner} { + if k == good { + t.Fatalf("%s: the fixture did not change the key", name) + } + if _, err := ParseLayoutKey(k); !errors.Is(err, storage.ErrChunkKeyInvalid) { + t.Errorf("%s %q: %v; want ErrChunkKeyInvalid", name, k, err) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_restore_read_test.go b/seaweed-block/core/frontend/chunkstore/layout_restore_read_test.go new file mode 100644 index 0000000000..e93e7ca991 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_restore_read_test.go @@ -0,0 +1,90 @@ +package chunkstore + +import ( + "context" + "path" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// The restore read path through the engine: the source writes and takes a +// named snapshot; a restore creates the target from it; a fresh target host +// reads every block, fetched lazily through its keys from the source's pool. +// The target then writes and cuts: its HEAD names its own chunk for what it +// changed and the source's chunks for the rest, it reads back its own +// image, and the source still reads back its snapshot image unchanged. +func TestLayoutRemote_RestoreTargetReadsItsSource(t *testing.T) { + ctx := context.Background() + src := newLayoutHost(t) + s, l, r := src.attach("src", true, true) + want := map[uint32][]byte{0: block(1), 9: block(2), 17: block(3), 63: block(4)} + writeSync(t, s, want) + r.SetSnapshot("daily", layout.SnapshotMeta{CreatedNs: 1, Class: layout.ClassSemantic}) + if _, err := l.Capture(ctx); err != nil { + t.Fatalf("source capture: %v", err) + } + _ = s.Close() + + tv := newRef(t, "t") + if _, err := src.cat.Restore(ctx, src.v, "daily", tv); err != nil { + t.Fatalf("restore: %v", err) + } + ts, err := src.cat.Store(tv) + if err != nil { + t.Fatal(err) + } + tme := layout.HolderID{Epoch: 1, Holder: "b", ClaimID: "k-b"} + if _, err := layout.Start(ctx, ts, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "b"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: lrBlocks * 4096, BlockSize: 4096, ChunkBytes: lrChunkBlocks * 4096}, ClaimID: "k-b", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatalf("start the target: %v", err) + } + tgt := &layoutHost{t: t, cat: src.cat, v: tv, me: tme, dir: t.TempDir()} + + // Every block of the target is the source's snapshot, read from the + // source's pool through the target's keys. + tgt.readBack("t-read", want) + + // The target writes one block of chunk 1 and cuts. + s2, l2, _ := tgt.attach("t-write", true, true) + changed := map[uint32][]byte{} + for k, v := range want { + changed[k] = v + } + changed[9] = block(9) + writeSync(t, s2, map[uint32][]byte{9: changed[9]}) + if _, err := l2.Capture(ctx); err != nil { + t.Fatalf("target capture: %v", err) + } + _ = s2.Close() + + _, tr, err := src.cat.open(tv) + if err != nil { + t.Fatal(err) + } + img, err := tr.Open(ctx, *tgt.head().Current) + if err != nil { + t.Fatal(err) + } + for idx, owner := range map[uint64]layout.VolumeID{0: src.v.ID, 1: tv.ID, 2: src.v.ID, 7: src.v.ID} { + c, err := img.Chunk(ctx, idx) + if err != nil || c.Ref.OwnerID != owner { + t.Fatalf("target chunk %d: owner %s (%v); want %s", idx, c.Ref.OwnerID, err, owner) + } + } + tgt.readBack("t-after", changed) + src.readBack("src-after", want) + + // A chunk the target names in the source's pool that is gone is an + // error on a fresh target host, never zeros. + c0, err := img.Chunk(ctx, 0) + if err != nil { + t.Fatal(err) + } + delete(src.cat.f.(*fakeFiler).entries, path.Join("/blocks", src.v.Dir(), c0.Ref.Chunk.Path())) + s3, _, _ := tgt.attach("t-gone", true, true) + defer s3.Close() + if got, err := s3.Read(0); err == nil || !strings.Contains(err.Error(), "object missing") { + t.Fatalf("block 0 with its source chunk gone: %x... %v; want the missing-object error", got[:min(2, len(got))], err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go b/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go new file mode 100644 index 0000000000..747537e0a6 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go @@ -0,0 +1,35 @@ +package chunkstore + +import ( + "go/ast" + "go/parser" + "go/token" + "reflect" + "testing" +) + +func TestLayoutRemoteSessionFieldSites(t *testing.T) { + f, err := parser.ParseFile(token.NewFileSet(), "layout_remote.go", nil, 0) + if err != nil { + t.Fatal(err) + } + fields := map[string]int{} + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + if s, ok := n.(*ast.SelectorExpr); ok && s.Sel.Name == "session" { + fields[fn.Name.Name]++ + } + + return true + }) + } + // Begin returns the session it opened; CASHead's third read checks that + // it survived a concurrent operator HEAD write before retrying. + if !reflect.DeepEqual(fields, map[string]int{"openSessionLocked": 2, "rollBackLocked": 1, "Begin": 1, "Put": 1, "CASHead": 3, "CommitPendingSnapshot": 2, "writeRootLocked": 1, "Clean": 1, "syncSessionLocked": 3, "takeAbandonLocked": 1}) { + t.Fatal("session field sites changed; enumerate and probe them", fields) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_store.go b/seaweed-block/core/frontend/chunkstore/layout_store.go new file mode 100644 index 0000000000..49467bb4b6 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_store.go @@ -0,0 +1,337 @@ +package chunkstore + +import ( + "context" + "errors" + "fmt" + "path" + "strconv" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +const ( + layoutGen = "swb.layout.gen" + layoutVolume = "swb.layout.volume" + layoutSession = "swb.layout.session" + layoutMark = "swb.layout.mark" + layoutKind = "swb.layout.kind" +) + +// ErrLegacyStore refuses the removed key/intent format rather than converting it. +var ErrLegacyStore = errors.New("chunkstore: legacy store format; recreate the volume") + +// LayoutStore maps the kernel's single-entry writes to ordinary filer files. +// Objects carry their immutable bytes as file chunks; metadata updates preserve +// those chunks, and deletion delegates their reclamation to the filer. +type LayoutStore struct { + f Filer + b Blobs + root string + id layout.VolumeID +} + +func NewLayoutStore(f Filer, b Blobs, root string, id layout.VolumeID) (*LayoutStore, error) { + if f == nil || b == nil || id.IsZero() || !path.IsAbs(root) || path.Clean(root) != root || root == "/" { + return nil, errors.New("chunkstore: layout store needs filer, blobs, a clean volume root and volume id") + } + return &LayoutStore{f: f, b: b, root: root, id: id}, nil +} + +var _ layout.HeadStore = (*LayoutStore)(nil) +var _ layout.ObjectStore = (*LayoutStore)(nil) + +func (s *LayoutStore) ReadHead(ctx context.Context) (layout.Head, bool, error) { + e, err := s.f.LookupEntry(ctx, s.root, layout.HeadName) + if errors.Is(err, ErrNotFound) { + return layout.Head{}, false, nil + } + if err != nil { + return layout.Head{}, false, err + } + h, err := DecodeLayoutHeadEntry(e, s.id) + return h, err == nil, err +} + +// DecodeLayoutHeadEntry validates the inline entry as one observation: its +// generation and volume attributes must describe the canonical HEAD content. +// Both filer RPC and HTTP metadata readers use this boundary. +func DecodeLayoutHeadEntry(e *filerpb.Entry, id layout.VolumeID) (layout.Head, error) { + if e == nil || e.IsDirectory { + return layout.Head{}, fmt.Errorf("%w: HEAD is not a file", layout.ErrCorrupt) + } + if len(e.Content) > layout.MaxHeadBytes { + return layout.Head{}, layout.ErrHeadTooLarge + } + if string(e.Extended[layoutKind]) != "head" { + return layout.Head{}, ErrLegacyStore + } + if id.IsZero() || string(e.Extended[layoutVolume]) != id.String() { + return layout.Head{}, layout.ErrIdentity + } + gen, err := strconv.ParseUint(string(e.Extended[layoutGen]), 10, 64) + if err != nil || gen == 0 || strconv.FormatUint(gen, 10) != string(e.Extended[layoutGen]) || len(e.Chunks) != 0 { + return layout.Head{}, fmt.Errorf("%w: invalid HEAD entry", layout.ErrCorrupt) + } + return layout.DecodeHead(e.Content, gen, id) +} + +func (s *LayoutStore) UpdateHead(ctx context.Context, expectedGen uint64, next layout.Head) error { + if next.VolumeID != s.id { + return layout.ErrIdentity + } + if expectedGen == ^uint64(0) { + return errors.New("chunkstore: HEAD generation exhausted") + } + raw, err := next.Encode() + if err != nil { + return err + } + e := layoutEntry(layout.HeadName, raw) + e.Extended = map[string][]byte{layoutKind: []byte("head"), layoutGen: []byte(strconv.FormatUint(expectedGen+1, 10)), layoutVolume: []byte(s.id.String())} + if expectedGen == 0 { + err = s.f.CreateEntry(ctx, s.root, e, true) + } else { + err = s.f.UpdateEntry(ctx, s.root, e, map[string][]byte{layoutGen: []byte(strconv.FormatUint(expectedGen, 10)), layoutVolume: []byte(s.id.String())}) + } + return layoutError(err) +} + +// Fetch reads a normal filer file, including a source volume's file reached by +// a restore root. The layout Reader validates the referenced volume identity. +func (s *LayoutStore) Fetch(ctx context.Context, p string) ([]byte, bool, error) { + if !path.IsAbs(p) || path.Clean(p) != p || !strings.HasPrefix(p, path.Dir(s.root)+"/") { + return nil, false, errors.New("chunkstore: object path outside the store base") + } + e, err := s.f.LookupEntry(ctx, path.Dir(p), path.Base(p)) + if errors.Is(err, ErrNotFound) { + return nil, false, nil + } + if err != nil { + return nil, false, err + } + if e.IsDirectory { + return nil, false, fmt.Errorf("%w: %s is a directory", layout.ErrCorrupt, p) + } + if len(e.Chunks) == 0 { + return append([]byte(nil), e.Content...), true, nil + } + if len(e.Content) != 0 || len(e.Chunks) != 1 || e.Chunks[0].Offset != 0 || e.Chunks[0].FileId == "" { + return nil, false, fmt.Errorf("%w: invalid file chunks for %s", layout.ErrCorrupt, p) + } + raw, err := s.b.Get(ctx, e.Chunks[0].FileId) + if err != nil { + return nil, false, err + } + if uint64(len(raw)) != e.Chunks[0].Size || e.GetAttributes().GetFileSize() != uint64(len(raw)) { + return nil, false, fmt.Errorf("%w: short file %s", layout.ErrCorrupt, p) + } + return raw, true, nil +} + +func (s *LayoutStore) object(rel string) (string, string, error) { + if rel == "" || path.IsAbs(rel) || path.Clean(rel) != rel || strings.Contains(rel, "\\") { + return "", "", layout.ErrMalformed + } + parts := strings.Split(rel, "/") + valid := false + switch { + case len(parts) == 3 && parts[0] == layout.PoolDir: + n, err := layout.ParseChunkName(parts[2]) + valid = err == nil && n.Path() == rel + case len(parts) == 2 && parts[0] == layout.SegDir: + n, err := layout.ParseSegName(parts[1]) + valid = err == nil && n.Path() == rel + case len(parts) == 2 && parts[0] == layout.RootDir: + n, err := layout.ParseRootName(parts[1]) + valid = err == nil && n.Path() == rel + } + if !valid { + return "", "", layout.ErrMalformed + } + p := path.Join(s.root, rel) + return path.Dir(p), path.Base(p), nil +} + +// ListChunkCandidates reads one bounded page of a pool shard, in filer name +// order. These are candidates only: RemoveUnreachable must read their tags and +// then validate HEAD before marking or deleting any of them. A concurrent new +// file missed by a page is left for the next cleaning pass. +func (s *LayoutStore) ListChunkCandidates(ctx context.Context, shard uint64, startAfter string, limit uint32) ([]layout.ChunkName, error) { + if limit == 0 { + return nil, fmt.Errorf("%w: a pool page needs a positive limit", layout.ErrMalformed) + } + if startAfter != "" { + n, err := layout.ParseChunkName(startAfter) + if err != nil || layout.Shard(n.Index) != shard { + return nil, fmt.Errorf("%w: invalid pool cursor %q", layout.ErrMalformed, startAfter) + } + } + dir := path.Join(s.root, layout.PoolDir, strconv.FormatUint(shard, 10)) + entries, err := s.f.ListEntries(ctx, dir, "", startAfter, limit) + if err != nil { + return nil, err + } + if uint64(len(entries)) > uint64(limit) { + return nil, fmt.Errorf("%w: oversized pool page", layout.ErrCorrupt) + } + var out []layout.ChunkName + for _, e := range entries { + if e == nil { + return nil, fmt.Errorf("%w: nil pool entry", layout.ErrCorrupt) + } + n, err := layout.ParseChunkName(e.Name) + if err != nil || e.IsDirectory || layout.Shard(n.Index) != shard || e.Name <= startAfter { + return nil, fmt.Errorf("%w: invalid pool entry %q", layout.ErrCorrupt, e.Name) + } + out = append(out, n) + startAfter = e.Name + } + return out, nil +} + +func (s *LayoutStore) Stat(ctx context.Context, rel string) (layout.ObjectMeta, bool, error) { + dir, name, err := s.object(rel) + if err != nil { + return layout.ObjectMeta{}, false, err + } + e, err := s.f.LookupEntry(ctx, dir, name) + if errors.Is(err, ErrNotFound) { + return layout.ObjectMeta{}, false, nil + } + if err != nil { + return layout.ObjectMeta{}, false, err + } + id, err := layout.ParseVolumeID(string(e.Extended[layoutVolume])) + if err != nil || id != s.id { + return layout.ObjectMeta{}, false, layout.ErrIdentity + } + if e.IsDirectory || string(e.Extended[layoutKind]) != "object" || len(e.Extended[layoutSession]) == 0 { + return layout.ObjectMeta{}, false, layout.ErrCorrupt + } + return layout.ObjectMeta{Volume: id, Session: string(e.Extended[layoutSession]), Mark: string(e.Extended[layoutMark])}, true, nil +} + +func (s *LayoutStore) Create(ctx context.Context, rel string, raw []byte, session string) error { + dir, name, err := s.object(rel) + if err != nil { + return err + } + if session == "" { + return errors.New("chunkstore: object needs a writer session") + } + // All object names end in their bytes' SHA-256; do not create a name + // for bytes it does not identify. + if !strings.HasSuffix(name, layout.Sum(raw).String()) { + return layout.ErrCorrupt + } + fid, err := s.b.Put(ctx, raw) + if err != nil { + return err + } + if fid == "" { + return errors.New("chunkstore: empty uploaded file id") + } + e := layoutEntry(name, nil) + e.Attributes.FileSize = uint64(len(raw)) + e.Chunks = []*filerpb.FileChunk{{FileId: fid, Offset: 0, Size: uint64(len(raw))}} + e.Extended = map[string][]byte{layoutKind: []byte("object"), layoutVolume: []byte(s.id.String()), layoutSession: []byte(session), layoutMark: []byte("")} + err = s.f.CreateEntry(ctx, dir, e, true) + if errors.Is(err, ErrExists) { + // Exclusive refusal proves this new fid was not linked. Unknown + // outcomes retain it: the entry may already reference its data. + if d, ok := s.b.(interface { + DeleteBlob(context.Context, string) error + }); ok { + _ = d.DeleteBlob(ctx, fid) + } + return layout.ErrExists + } + return err +} + +func objectExpected(meta layout.ObjectMeta) map[string][]byte { + return map[string][]byte{layoutVolume: []byte(meta.Volume.String()), layoutSession: []byte(meta.Session), layoutMark: []byte(meta.Mark)} +} + +func (s *LayoutStore) changeMeta(ctx context.Context, rel string, expect layout.ObjectMeta, session, mark string) error { + if expect.Volume != s.id { + return layout.ErrIdentity + } + dir, name, err := s.object(rel) + if err != nil { + return err + } + e, err := s.f.LookupEntry(ctx, dir, name) + if err != nil { + return layoutError(err) + } + if !extendedMatch(e, objectExpected(expect)) || string(e.Extended[layoutKind]) != "object" { + return layout.ErrPrecondition + } + e.Extended[layoutSession] = []byte(session) + e.Extended[layoutMark] = []byte(mark) + // Preserve the original FileChunks: an UpdateEntry dropping them + // would tell the filer to delete the object's immutable data. + return layoutError(s.f.UpdateEntry(ctx, dir, e, objectExpected(expect))) +} + +func (s *LayoutStore) Reuse(ctx context.Context, rel string, expect layout.ObjectMeta, session string) error { + if session == "" { + return errors.New("chunkstore: reuse needs a session") + } + return s.changeMeta(ctx, rel, expect, session, "") +} + +func (s *LayoutStore) Mark(ctx context.Context, rel string, expect layout.ObjectMeta, mark string) error { + if mark == "" { + return layout.ErrPrecondition + } + return s.changeMeta(ctx, rel, expect, expect.Session, mark) +} + +func (s *LayoutStore) deleteObject(ctx context.Context, rel string, expected map[string][]byte) error { + dir, name, err := s.object(rel) + if err != nil { + return err + } + err = s.f.DeleteEntry(ctx, dir, name, expected) + if errors.Is(err, ErrNotFound) { + return nil + } + if errors.Is(err, ErrPrecondition) { + if _, lookupErr := s.f.LookupEntry(ctx, dir, name); errors.Is(lookupErr, ErrNotFound) { + return nil + } + } + return layoutError(err) +} + +func (s *LayoutStore) DeleteMarked(ctx context.Context, rel, mark string) error { + if mark == "" { + return layout.ErrPrecondition + } + return s.deleteObject(ctx, rel, map[string][]byte{layoutVolume: []byte(s.id.String()), layoutMark: []byte(mark)}) +} + +func (s *LayoutStore) DeleteOfVolume(ctx context.Context, rel string, id layout.VolumeID) error { + if id != s.id { + return layout.ErrIdentity + } + return s.deleteObject(ctx, rel, map[string][]byte{layoutVolume: []byte(id.String())}) +} + +func layoutEntry(name string, raw []byte) *filerpb.Entry { + now := time.Now().Unix() + return &filerpb.Entry{Name: name, Content: raw, Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(raw)), FileMode: 0644, Mtime: now, Crtime: now}} +} + +func layoutError(err error) error { + if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrExists) || errors.Is(err, ErrNotFound) { + return fmt.Errorf("%w: %v", layout.ErrPrecondition, err) + } + return err +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_store_test.go b/seaweed-block/core/frontend/chunkstore/layout_store_test.go new file mode 100644 index 0000000000..77a9599eee --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_store_test.go @@ -0,0 +1,439 @@ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "path" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +func layoutStoreFixture(t *testing.T) (*LayoutStore, *fakeFiler, *fakeBlobs) { + t.Helper() + f, b := newFakeFiler(), newFakeBlobs() + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + s, err := NewLayoutStore(f, b, "/blocks/v", id) + if err != nil { + t.Fatal(err) + } + return s, f, b +} + +func TestLayoutStoreMissingHEADRefusesStart(t *testing.T) { + s, f, _ := layoutStoreFixture(t) + ctx := context.Background() + if _, found, err := s.ReadHead(ctx); found || err != nil { + t.Fatal("missing HEAD did not remain absent", found, err) + } + if _, err := layout.Start(ctx, s, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "root", Fresh: true, CanStartFrom: anyStart}); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatal("missing HEAD must not start", err) + } + if len(f.written) != 0 { + t.Fatal("Start recreated a missing HEAD") + } +} + +func TestLayoutStoreObjectsAreFilerFiles(t *testing.T) { + s, f, b := layoutStoreFixture(t) + ctx := context.Background() + raw := bytes.Repeat([]byte("new"), 100) + n := layout.NameChunk(10000, raw) + if err := layout.EnsureObject(ctx, s, n.Path(), raw, "writer"); err != nil { + t.Fatal(err) + } + e, err := f.LookupEntry(ctx, "/blocks/v/pool/1", n.String()) + if err != nil { + t.Fatal(err) + } + if len(e.Content) != 0 || len(e.Chunks) != 1 || e.Chunks[0].Offset != 0 || e.Chunks[0].Size != 300 || e.Attributes.FileSize != 300 { + t.Fatalf("not an ordinary complete filer file: %+v", e) + } + got, found, err := s.Fetch(ctx, path.Join(s.root, n.Path())) + if err != nil || !found || !bytes.Equal(got, raw) { + t.Fatalf("readback %q %t %v", got, found, err) + } + puts, _, _ := b.counts() + if err := layout.EnsureObject(ctx, s, n.Path(), raw, "writer"); err != nil { + t.Fatal(err) + } + after, _, _ := b.counts() + if after != puts { + t.Fatal("same-session object was uploaded again") + } + if err := s.Create(ctx, n.Path(), []byte("wrong bytes"), "writer"); !errors.Is(err, layout.ErrCorrupt) { + t.Fatalf("wrong content name: %v", err) + } +} + +func TestLayoutStoreListsOnePoolPageAtATime(t *testing.T) { + s, _, _ := layoutStoreFixture(t) + ctx := context.Background() + var want []layout.ChunkName + for _, idx := range []uint64{2, 3, 4, 10000} { + n := layout.NameChunk(idx, []byte("bytes")) + if err := s.Create(ctx, n.Path(), []byte("bytes"), "writer"); err != nil { + t.Fatal(err) + } + if layout.Shard(idx) == 0 { + want = append(want, n) + } + } + after := "" + for _, n := range want { + got, err := s.ListChunkCandidates(ctx, 0, after, 1) + if err != nil || len(got) != 1 || got[0] != n { + t.Fatalf("page after %q: %v %v; want %v", after, got, err, n) + } + after = n.String() + } + if got, err := s.ListChunkCandidates(ctx, 0, after, 1); err != nil || len(got) != 0 { + t.Fatal("page crossed into the next shard", got, err) + } + if _, err := s.ListChunkCandidates(ctx, 0, "", 0); !errors.Is(err, layout.ErrMalformed) { + t.Fatal("unbounded page accepted", err) + } + for _, cursor := range []string{"../HEAD", layout.NameChunk(10000, []byte("bytes")).String()} { + if _, err := s.ListChunkCandidates(ctx, 0, cursor, 1); !errors.Is(err, layout.ErrMalformed) { + t.Fatalf("unsafe cursor %q: %v", cursor, err) + } + } +} + +type layoutListFiler struct { + Filer + entries []*filerpb.Entry + err error +} + +func (f layoutListFiler) ListEntries(context.Context, string, string, string, uint32) ([]*filerpb.Entry, error) { + return f.entries, f.err +} + +func TestLayoutStoreListErrorsAreNotAnEmptyPool(t *testing.T) { + s, f, _ := layoutStoreFixture(t) + ctx := context.Background() + n := layout.NameChunk(1, []byte("bytes")) + unreachable := errors.New("filer unreachable") + for _, tc := range []struct { + name string + entries []*filerpb.Entry + err error + want error + }{ + {"transport", nil, unreachable, unreachable}, + {"wrong shard", []*filerpb.Entry{{Name: layout.NameChunk(10000, nil).String()}}, nil, layout.ErrCorrupt}, + {"directory", []*filerpb.Entry{{Name: n.String(), IsDirectory: true}}, nil, layout.ErrCorrupt}, + {"noncanonical", []*filerpb.Entry{{Name: "garbage"}}, nil, layout.ErrCorrupt}, + {"nil entry", []*filerpb.Entry{nil}, nil, layout.ErrCorrupt}, + {"repeated cursor", []*filerpb.Entry{{Name: n.String()}}, nil, layout.ErrCorrupt}, + } { + t.Run(tc.name, func(t *testing.T) { + s.f = layoutListFiler{Filer: f, entries: tc.entries, err: tc.err} + after := "" + if tc.name == "repeated cursor" { + after = n.String() + } + got, err := s.ListChunkCandidates(ctx, 0, after, 10) + if !errors.Is(err, tc.want) || len(got) != 0 { + t.Fatalf("got %v %v; want no candidates and %v", got, err, tc.want) + } + }) + } +} + +func TestLayoutStoreLateCleanCannotDeleteReusedFile(t *testing.T) { + s, _, _ := layoutStoreFixture(t) + ctx := context.Background() + raw := []byte("keep this image") + n := layout.NameChunk(4, raw) + if err := layout.EnsureObject(ctx, s, n.Path(), raw, "snapshot-a"); err != nil { + t.Fatal(err) + } + plan, ok, err := s.Stat(ctx, n.Path()) + if err != nil || !ok { + t.Fatal(plan, ok, err) + } + if err := s.Mark(ctx, n.Path(), plan, "clean-a"); err != nil { + t.Fatal(err) + } + if err := layout.EnsureObject(ctx, s, n.Path(), raw, "snapshot-b"); err != nil { + t.Fatal(err) + } + if err := s.DeleteMarked(ctx, n.Path(), "clean-a"); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("late delete: %v", err) + } + if err := s.Mark(ctx, n.Path(), plan, "clean-a"); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("late mark: %v", err) + } + meta, _, err := s.Stat(ctx, n.Path()) + if err != nil || meta.Session != "snapshot-b" || meta.Mark != "" { + t.Fatal(meta, err) + } + got, found, err := s.Fetch(ctx, path.Join(s.root, n.Path())) + if err != nil || !found || !bytes.Equal(got, raw) { + t.Fatal("reuse lost file data", found, err) + } + if err := s.Mark(ctx, n.Path(), meta, "clean-b"); err != nil { + t.Fatal(err) + } + if err := s.DeleteMarked(ctx, n.Path(), "clean-b"); err != nil { + t.Fatal(err) + } + if err := s.DeleteMarked(ctx, n.Path(), "clean-b"); err != nil { + t.Fatal("missing delete must replay", err) + } +} + +func TestLayoutStoreHEADGenerationAndVolumeIdentity(t *testing.T) { + s, f, _ := layoutStoreFixture(t) + ctx := context.Background() + h := layout.Head{VolumeID: s.id, Epoch: 1, Holder: "server/r", ClaimID: "local-root", State: layout.StateLive, Activity: layout.Activity{Kind: layout.ActIdle}} + if err := s.UpdateHead(ctx, 0, h); err != nil { + t.Fatal(err) + } + read, found, err := s.ReadHead(ctx) + if err != nil || !found || read.Gen != 1 || read.ClaimID != "local-root" { + t.Fatal(read, found, err) + } + me := layout.HolderID{Epoch: 1, Holder: "server/r", ClaimID: "local-root"} + if _, err := layout.RunBegin(ctx, s, me, "snap-a"); err != nil { + t.Fatal(err) + } + if err := s.UpdateHead(ctx, 1, h); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("stale HEAD replaced session: %v", err) + } + read, _, err = s.ReadHead(ctx) + if err != nil || read.Gen != 2 || read.Activity.Session != "snap-a" { + t.Fatal(read, err) + } + f.failUpdateAfterApply = func(string) error { return errors.New("reply lost") } + if _, err := layout.RunAbort(ctx, s, me, "snap-a"); err == nil { + t.Fatal("unknown write was reported successful") + } + f.failUpdateAfterApply = nil + read, err = layout.RunAbort(ctx, s, me, "snap-a") + if err != nil || read.Gen != 3 || read.Activity.Kind != layout.ActIdle { + t.Fatal("lost reply did not settle on replay", read, err) + } + id, _ := layout.NewVolumeID() + other, err := NewLayoutStore(f, s.b, s.root, id) + if err != nil { + t.Fatal(err) + } + if _, _, err := other.ReadHead(ctx); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("wrong volume accepted HEAD: %v", err) + } + h.VolumeID = id + if err := other.UpdateHead(ctx, 3, h); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("old generation crossed volume identity: %v", err) + } +} + +func TestLayoutStoreRefusesLegacyHEADAndUnsafePaths(t *testing.T) { + s, f, _ := layoutStoreFixture(t) + ctx := context.Background() + if err := f.CreateEntry(ctx, s.root, &filerpb.Entry{Name: "HEAD", Content: []byte(`{"format":1,"epoch":1}`)}, true); err != nil { + t.Fatal(err) + } + if _, _, err := s.ReadHead(ctx); !errors.Is(err, ErrLegacyStore) { + t.Fatalf("legacy format needs recreate refusal: %v", err) + } + for _, rel := range []string{"../pool/0/x", "/pool/0/x", "keys/old", "intents/old", "pool/01/0-bad", "root/UPPER"} { + if _, _, err := s.Stat(ctx, rel); !errors.Is(err, layout.ErrMalformed) { + t.Fatalf("path %q: %v", rel, err) + } + } + if _, _, err := s.Fetch(ctx, "/outside/VOLUME"); err == nil { + t.Fatal("read escaped the store base") + } +} + +func TestLayoutStoreRecreatedVolumeRefusesOldDelete(t *testing.T) { + s, f, b := layoutStoreFixture(t) + ctx := context.Background() + raw := []byte("same content in a new volume") + n := layout.NameChunk(1, raw) + if err := s.Create(ctx, n.Path(), raw, "old"); err != nil { + t.Fatal(err) + } + if err := s.DeleteOfVolume(ctx, n.Path(), s.id); err != nil { + t.Fatal(err) + } + id, _ := layout.NewVolumeID() + next, err := NewLayoutStore(f, b, s.root, id) + if err != nil { + t.Fatal(err) + } + if err := next.Create(ctx, n.Path(), raw, "new"); err != nil { + t.Fatal(err) + } + if err := s.DeleteOfVolume(ctx, n.Path(), s.id); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("old volume deleted its replacement: %v", err) + } + got, found, err := next.Fetch(ctx, path.Join(next.root, n.Path())) + if err != nil || !found || !bytes.Equal(got, raw) { + t.Fatal("new volume image lost", found, err) + } +} + +func TestLayoutStoreDeleteNeverRemovesControlRecords(t *testing.T) { + s, f, _ := layoutStoreFixture(t) + ctx := context.Background() + for _, name := range []string{"HEAD", "VOLUME"} { + if err := f.CreateEntry(ctx, s.root, &filerpb.Entry{Name: name, Content: []byte("keep")}, true); err != nil { + t.Fatal(err) + } + } + for _, rel := range []string{"HEAD", "VOLUME", ".", "pool", "pool/0", "seg", "root", "../other/HEAD"} { + if err := s.DeleteMarked(ctx, rel, "clean"); !errors.Is(err, layout.ErrMalformed) { + t.Fatalf("marked deletion of %q: %v", rel, err) + } + if err := s.DeleteOfVolume(ctx, rel, s.id); !errors.Is(err, layout.ErrMalformed) { + t.Fatalf("volume deletion of %q: %v", rel, err) + } + } + for _, name := range []string{"HEAD", "VOLUME"} { + got, err := f.LookupEntry(ctx, s.root, name) + if err != nil || string(got.Content) != "keep" { + t.Fatal("control record changed", name, err) + } + } +} + +// The first remover dies after Mark. The next cleaning must replace that +// mark, and the dead remover's delayed delete must not match the replacement. +type abandonedMarkStore struct { + *LayoutStore + t *testing.T + oldDeleteRefused bool +} + +func (s *abandonedMarkStore) DeleteMarked(ctx context.Context, rel, mark string) error { + if err := s.LayoutStore.DeleteMarked(ctx, rel, "dead-clean"); !errors.Is(err, layout.ErrPrecondition) { + s.t.Fatalf("old delete after re-mark: %v", err) + } + s.oldDeleteRefused = true + return s.LayoutStore.DeleteMarked(ctx, rel, mark) +} + +func TestLayoutStoreCleaningReclaimsAnAbandonedMark(t *testing.T) { + s, _, _ := layoutStoreFixture(t) + ctx := context.Background() + if _, err := layout.CreateVolume(ctx, s, layout.Volume{ID: s.id, Name: "v", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}); err != nil { + t.Fatal(err) + } + h, _, err := s.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + h.Epoch, h.Holder, h.ClaimID = 1, "server/r", "root" + h.Activity = layout.Activity{Kind: layout.ActClean, Session: "next-clean"} + if err := s.UpdateHead(ctx, h.Gen, h); err != nil { + t.Fatal(err) + } + raw := []byte("unreachable") + n := layout.NameChunk(4, raw) + if err := s.Create(ctx, n.Path(), raw, "writer"); err != nil { + t.Fatal(err) + } + meta, _, err := s.Stat(ctx, n.Path()) + if err != nil { + t.Fatal(err) + } + if err := s.Mark(ctx, n.Path(), meta, "dead-clean"); err != nil { + t.Fatal(err) + } + r, err := layout.NewReader("/blocks", "v", s.Fetch) + if err != nil { + t.Fatal(err) + } + os := &abandonedMarkStore{LayoutStore: s, t: t} + removed, err := layout.RemoveUnreachable(ctx, s, r, os, layout.HolderID{Epoch: 1, Holder: "server/r", ClaimID: "root"}, "next-clean", 0, []layout.ChunkName{n}) + if err != nil || len(removed) != 1 || removed[0] != n || !os.oldDeleteRefused { + t.Fatalf("next cleaning: removed=%v old_delete_refused=%v err=%v", removed, os.oldDeleteRefused, err) + } + if _, found, err := s.Stat(ctx, n.Path()); err != nil || found { + t.Fatalf("orphan retained: %v %v", found, err) + } +} + +type layoutCleanupBlobs struct { + *fakeBlobs + deleted []string + deleteErr error +} + +func (b *layoutCleanupBlobs) DeleteBlob(_ context.Context, fid string) error { + b.deleted = append(b.deleted, fid) + if b.deleteErr != nil { + return b.deleteErr + } + b.mu.Lock() + defer b.mu.Unlock() + delete(b.data, fid) + return nil +} + +func TestLayoutStoreCreateExistsReclaimsOnlyItsUnusedUpload(t *testing.T) { + for _, failedCleanup := range []bool{false, true} { + t.Run(map[bool]string{false: "reclaimed", true: "cleanup unavailable"}[failedCleanup], func(t *testing.T) { + s, _, base := layoutStoreFixture(t) + b := &layoutCleanupBlobs{fakeBlobs: base} + s.b = b + ctx := context.Background() + raw := []byte("referenced bytes") + n := layout.NameChunk(3, raw) + if err := s.Create(ctx, n.Path(), raw, "winner"); err != nil { + t.Fatal(err) + } + if failedCleanup { + b.deleteErr = errors.New("volume server unavailable") + } + if err := s.Create(ctx, n.Path(), raw, "loser"); !errors.Is(err, layout.ErrExists) { + t.Fatal(err) + } + if len(b.deleted) != 1 { + t.Fatalf("unused upload cleanup calls: %v", b.deleted) + } + _, _, stored := b.counts() + want := 1 + if failedCleanup { + want = 2 + } + if stored != want { + t.Fatalf("stored blobs=%d, want %d", stored, want) + } + got, found, err := s.Fetch(ctx, path.Join(s.root, n.Path())) + if err != nil || !found || !bytes.Equal(got, raw) { + t.Fatalf("winner lost: %q %v %v", got, found, err) + } + }) + } +} + +func TestLayoutStoreCreateUnknownOutcomeKeepsItsUpload(t *testing.T) { + s, f, base := layoutStoreFixture(t) + b := &layoutCleanupBlobs{fakeBlobs: base} + s.b = b + unknown := errors.New("create reply lost") + f.failCreateAfterApply = func(string) error { return unknown } + raw := []byte("applied bytes") + n := layout.NameChunk(3, raw) + ctx := context.Background() + if err := s.Create(ctx, n.Path(), raw, "writer"); !errors.Is(err, unknown) { + t.Fatal(err) + } + if len(b.deleted) != 0 { + t.Fatalf("unknown upload deleted: %v", b.deleted) + } + got, found, err := s.Fetch(ctx, path.Join(s.root, n.Path())) + if err != nil || !found || !bytes.Equal(got, raw) { + t.Fatalf("applied data lost: %q %v %v", got, found, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_verify.go b/seaweed-block/core/frontend/chunkstore/layout_verify.go new file mode 100644 index 0000000000..6abc7b16d2 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_verify.go @@ -0,0 +1,52 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "strings" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// verifyListPage is the page size of one directory listing. +const verifyListPage = 1000 + +// List returns the entry names of directory p under the store base, all +// pages, in name order. A missing directory lists as empty. +func (s *LayoutStore) List(ctx context.Context, p string) ([]string, error) { + if !path.IsAbs(p) || path.Clean(p) != p || !strings.HasPrefix(p, path.Dir(s.root)+"/") { + return nil, errors.New("chunkstore: list path outside the store base") + } + var out []string + after := "" + for { + page, err := s.f.ListEntries(ctx, p, "", after, verifyListPage) + if err != nil { + return nil, err + } + for _, e := range page { + out = append(out, e.Name) + } + if len(page) < verifyListPage { + return out, nil + } + after = page[len(page)-1].Name + } +} + +// VerifyLayout runs layout.Verify for vol under base through this adapter's +// Fetch and List (read-only; neither uses the volume id, which the pass +// reads from VOLUME itself). f must also serve blobs, as the SWFS client does. +func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.VerifyOptions) (layout.VerifyResult, error) { + b, ok := f.(Blobs) + if !ok { + return layout.VerifyResult{}, errors.New("chunkstore: verify needs a filer that also serves blobs") + } + if !path.IsAbs(base) || path.Clean(base) != base || base == "/" { + return layout.VerifyResult{}, errors.New("chunkstore: verify needs a clean absolute chunk base") + } + s := &LayoutStore{f: f, b: b, root: path.Join(base, vol)} + opts.List = s.List + return layout.Verify(ctx, base, vol, s.Fetch, opts) +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_verify_test.go b/seaweed-block/core/frontend/chunkstore/layout_verify_test.go new file mode 100644 index 0000000000..bdb9868d29 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_verify_test.go @@ -0,0 +1,150 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "fmt" + "path" + "sort" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "google.golang.org/protobuf/proto" +) + +type filerBlobs struct { + *fakeFiler + *fakeBlobs +} + +func putFile(t *testing.T, f *fakeFiler, p string, b []byte) { + t.Helper() + if err := f.CreateEntry(context.Background(), path.Dir(p), &filerpb.Entry{Name: path.Base(p), Content: b}, true); err != nil { + t.Fatal(err) + } +} + +func putDir(t *testing.T, f *fakeFiler, p string) { + t.Helper() + if err := f.CreateEntry(context.Background(), path.Dir(p), &filerpb.Entry{Name: path.Base(p), IsDirectory: true}, false); err != nil { + t.Fatal(err) + } +} + +// a layout volume "v" under /blocks: VOLUME, HEAD, one root naming chunks 0 and 5 +func verifyFixtureVolume(t *testing.T) (filerBlobs, layout.VolumeID) { + f, b := newFakeFiler(), newFakeBlobs() + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + vb, err := layout.Volume{ID: id, Name: "v", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}.Encode() + if err != nil { + t.Fatal(err) + } + putFile(t, f, "/blocks/v/"+layout.VolumeName, vb) + manifest := map[uint64]layout.Ref{} + putDir(t, f, "/blocks/v/pool/0") + for _, i := range []uint64{0, 5} { + d := []byte(strings.Repeat(string(rune('a'+i)), 64)) + c := layout.NameChunk(i, d) + putFile(t, f, path.Join("/blocks/v", c.Path()), d) + manifest[i] = layout.Ref{Owner: "v", OwnerID: id, Chunk: c} + } + root, segs, err := layout.Build(manifest) + if err != nil { + t.Fatal(err) + } + for n, sb := range segs { + putFile(t, f, path.Join("/blocks/v", n.Path()), sb) + } + rn, rb, err := layout.NameRoot(root) + if err != nil { + t.Fatal(err) + } + putFile(t, f, path.Join("/blocks/v", rn.Path()), rb) + hb, err := layout.Head{VolumeID: id, Epoch: 1, Holder: "s/r", ClaimID: "c", Activity: layout.Activity{Kind: layout.ActIdle}, Current: &rn}.Encode() + if err != nil { + t.Fatal(err) + } + putFile(t, f, "/blocks/v/"+layout.HeadName, hb) + return filerBlobs{f, b}, id +} + +func TestVerifyLayoutThroughTheAdapter(t *testing.T) { + fb, _ := verifyFixtureVolume(t) + ctx := context.Background() + before := snapshotStore(fb) + r, err := VerifyLayout(ctx, fb, "/blocks", "v", layout.VerifyOptions{Depth: layout.DepthFull, Orphans: true}) + if err != nil || !r.Complete || len(r.Findings) != 0 || r.Chunks != 2 || !r.OrphansChecked { + t.Fatalf("clean: %+v %v", r, err) + } + if after := snapshotStore(fb); after != before { + t.Fatalf("verify changed the store:\nbefore %s\nafter %s", before, after) + } + extra := layout.NameChunk(9, []byte("zz")) + putFile(t, fb.fakeFiler, path.Join("/blocks/v", extra.Path()), []byte("zz")) + c0 := layout.NameChunk(0, []byte(strings.Repeat("a", 64))) + delete(fb.fakeFiler.entries, path.Join("/blocks/v", c0.Path())) + r, err = VerifyLayout(ctx, fb, "/blocks", "v", layout.VerifyOptions{Orphans: true}) + if err != nil { + t.Fatal(err) + } + got := map[string]string{} + for _, f := range r.Findings { + got[f.Path] = f.Class + } + if got["v/"+c0.Path()] != layout.FindMissing || got["v/"+extra.Path()] != layout.FindOrphan || len(got) != 2 { + t.Fatalf("findings: %+v", r.Findings) + } +} + +func TestLayoutStoreListPagesAndStaysInBase(t *testing.T) { + fb, id := verifyFixtureVolume(t) + s, err := NewLayoutStore(fb.fakeFiler, fb.fakeBlobs, "/blocks/v", id) + if err != nil { + t.Fatal(err) + } + for i := 0; i < verifyListPage+3; i++ { + putFile(t, fb.fakeFiler, path.Join("/blocks/v/seg", strings.Repeat("x", 4)+string(rune('A'+i%26))+string(rune('a'+i/26%26))+string(rune('a'+i/676))), []byte("s")) + } + names, err := s.List(context.Background(), "/blocks/v/seg") + if err != nil { + t.Fatal(err) + } + segs := 0 + for n := range fb.fakeFiler.entries { + if path.Dir(n) == "/blocks/v/seg" { + segs++ + } + } + if len(names) != segs || segs <= verifyListPage { + t.Fatalf("listed %d of %d entries (page %d)", len(names), segs, verifyListPage) + } + if _, err := s.List(context.Background(), "/elsewhere"); err == nil { + t.Fatal("a path outside the store base must be refused") + } +} + +func TestVerifyLayoutNeedsBlobs(t *testing.T) { + if _, err := VerifyLayout(context.Background(), newFakeFiler(), "/blocks", "v", layout.VerifyOptions{}); err == nil { + t.Fatal("a filer without blobs must be refused") + } +} + +// snapshotStore is every filer entry (path and bytes) and the blob counters +// except reads, as one comparable string. +func snapshotStore(fb filerBlobs) string { + fb.fakeFiler.mu.Lock() + var keys []string + for p, e := range fb.fakeFiler.entries { + raw, _ := proto.Marshal(e) + keys = append(keys, fmt.Sprintf("%s=%x", p, sha256.Sum256(raw))) + } + fb.fakeFiler.mu.Unlock() + sort.Strings(keys) + puts, _, stored := fb.fakeBlobs.counts() + return fmt.Sprintf("puts=%d stored=%d %s", puts, stored, strings.Join(keys, ",")) +} diff --git a/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go b/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go deleted file mode 100644 index 5df831bae3..0000000000 --- a/seaweed-block/core/frontend/chunkstore/legacy_head_fixture_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package chunkstore - -import ( - "encoding/hex" - "encoding/json" - "strconv" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Only old-reader fixtures bypass the production format-1 data-write refusal. -func legacyHeadFixture(t testing.TB, h storage.ChunkHead) *filerpb.Entry { - t.Helper() - doc := headDoc{Format: 1, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State, Chunks: map[uint64]refDoc{}} - for idx, ref := range h.Chunks { - doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} - } - body, err := json.Marshal(doc) - if err != nil { - t.Fatal(err) - } - return &filerpb.Entry{Name: headName, Content: body, Extended: map[string][]byte{extKind: []byte(kindChunkHead), extGen: []byte(strconv.FormatUint(h.Gen, 10)), extEpoch: []byte(strconv.FormatUint(h.Epoch, 10)), extHolder: []byte(h.Holder)}} -} diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go deleted file mode 100644 index ee525f2213..0000000000 --- a/seaweed-block/core/frontend/chunkstore/manifest.go +++ /dev/null @@ -1,255 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "crypto/rand" - "crypto/sha256" - "encoding/json" - "errors" - "fmt" - "io" - "path" - "reflect" - "strings" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// One segment spans a fixed logical GiB. This is a format constant, not a knob. -const manifestSegmentBytes uint64 = 1 << 30 -const maxManifestBytes = 64 << 20 - -type segmentDoc struct { - Format int `json:"format"` - Range uint64 `json:"range"` - ChunkBytes uint64 `json:"chunk_bytes"` - Owner string `json:"owner"` - Chunks map[uint64]storage.ChunkRef `json:"chunks"` -} - -func qualifyManifestKey(owner, key string) string { - if strings.HasPrefix(key, "@") { - return key - } - return "@" + owner + "/" + key -} - -func manifestCount(h storage.ChunkHead) int { - if h.Segments != nil { - return h.ManifestChunkCount - } - return len(h.Chunks) -} - -func validateRoot(h storage.ChunkHead) error { - if h.ChunkBytes < 4096 || h.ChunkBytes > manifestSegmentBytes || manifestSegmentBytes%h.ChunkBytes != 0 || h.ManifestChunkCount < 0 { - return errors.New("chunkstore: invalid manifest geometry/count") - } - count := 0 - for group, ref := range h.Segments { - if (ref.SegFormat != 1 && ref.SegFormat != 2) || ref.MaxBirthLSN > h.RemoteLSN { - return errors.New("chunkstore: invalid segment version/birth maximum") - } - if CheckVolumeID(ref.Owner) != nil || storage.ValidChunkKey(ref.Key) != nil || ref.Count <= 0 || uint64(ref.Count) > manifestSegmentBytes/h.ChunkBytes || group > ^uint64(0)/(manifestSegmentBytes/h.ChunkBytes) { - return errors.New("chunkstore: invalid segment reference") - } - count += ref.Count - } - if h.State == storage.ChunkHeadAborted && len(h.Segments) != 0 { - return errors.New("chunkstore: aborted HEAD contains segments") - } - if count != h.ManifestChunkCount { - return errors.New("chunkstore: manifest count mismatch") - } - return nil -} - -// PrepareManifest never changes generation/epoch or publishes the root. All -// segment keys are protected before their Put; the cut owns returned intents. -func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.ChunkHead, chunkBytes uint64) (storage.ChunkHead, []string, error) { - next.ChunkBytes = chunkBytes - next.ManifestChunkCount = len(next.Chunks) - next.Segments = map[uint64]storage.ChunkSegment{} - if chunkBytes < 4096 || chunkBytes > manifestSegmentBytes || manifestSegmentBytes%chunkBytes != 0 { - return next, nil, errors.New("chunkstore: invalid segment geometry") - } - per := manifestSegmentBytes / chunkBytes - owner := path.Base(r.root) - groups := map[uint64]map[uint64]storage.ChunkRef{} - canonical := make(map[uint64]storage.ChunkRef, len(next.Chunks)) - for idx, ref := range next.Chunks { - if ref.Encoding == "" { - ref.Encoding, ref.BirthLSN = "full", next.RemoteLSN - } - if ref.Encoding != "full" || ref.BirthLSN > next.RemoteLSN { - return next, nil, errors.New("chunkstore: invalid chunk encoding/birth") - } - ref.Key = qualifyManifestKey(owner, ref.Key) - canonical[idx] = ref - group := idx / per - if groups[group] == nil { - groups[group] = map[uint64]storage.ChunkRef{} - } - groups[group][idx] = ref - } - next.Chunks = canonical - type upload struct { - key string - data []byte - } - var uploads []upload - // Partition the base once, rather than scanning every base chunk for each - // segment group. Keep the same qualified-key comparison for segment reuse. - baseGroups := map[uint64]map[uint64]storage.ChunkRef{} - for idx, ref := range base.Chunks { - if ref.Encoding == "" { - ref.Encoding, ref.BirthLSN = "full", base.RemoteLSN - } - group := idx / per - if baseGroups[group] == nil { - baseGroups[group] = map[uint64]storage.ChunkRef{} - } - ref.Key = qualifyManifestKey(owner, ref.Key) - baseGroups[group][idx] = ref - } - for group, chunks := range groups { - old := baseGroups[group] - if previous, ok := base.Segments[group]; ok && base.ChunkBytes == chunkBytes && reflect.DeepEqual(chunks, old) { - // Legacy groups keep a conservative upper bound until rewritten. - if previous.SegFormat == 0 { - previous.SegFormat, previous.MaxBirthLSN = 1, base.RemoteLSN - } - next.Segments[group] = previous - continue - } - body, maxBirth, err := encodeSegmentV2(group, chunkBytes, owner, chunks) - if err != nil { - return next, nil, err - } - if len(body) > maxManifestBytes { - return next, nil, errors.New("chunkstore: manifest too large") - } - nonce := make([]byte, 16) - if _, err := rand.Read(nonce); err != nil { - return next, nil, err - } - key := fmt.Sprintf("seg/%x", nonce) - next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks), SegFormat: 2, MaxBirthLSN: maxBirth} - uploads = append(uploads, upload{key, body}) - } - if err := validateRoot(next); err != nil { - return next, nil, err - } - if len(uploads) == 0 { - return next, nil, nil - } - keys := make([]string, len(uploads)) - for i, u := range uploads { - keys[i] = u.key - } - id, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: base.Gen, Epoch: next.Epoch, Holder: next.Holder, Keys: keys}) - if err != nil { - return next, nil, err - } - ids := []string{id} - for _, u := range uploads { - if err := r.putObject(ctx, u.key, u.data, "segment"); err != nil { - return next, ids, err - } - } - return next, ids, nil -} - -func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead) (storage.ChunkHead, error) { - if h.Segments == nil { - return h, nil - } - if err := validateRoot(h); err != nil { - return h, err - } - h.Chunks = map[uint64]storage.ChunkRef{} - for group, ref := range h.Segments { - body, err := r.Get(ctx, ref.Key) - if err != nil { - return h, fmt.Errorf("chunkstore: read published segment: %w", err) - } - if len(body) > maxManifestBytes || sha256.Sum256(body) != ref.SHA256 { - return h, errors.New("chunkstore: segment hash/size mismatch") - } - doc, err := decodeSegment(body, ref, h.RemoteLSN) - if err != nil { - return h, err - } - if doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count { - return h, errors.New("chunkstore: invalid segment contents") - } - for idx, cr := range doc.Chunks { - if idx/(manifestSegmentBytes/h.ChunkBytes) != group || storage.ValidChunkKey(cr.Key) != nil { - return h, errors.New("chunkstore: segment index/key invalid") - } - cr.Key = qualifyManifestKey(ref.Owner, cr.Key) - h.Chunks[idx] = cr - } - } - return h, nil -} - -// Reject duplicate object keys instead of accepting a last-wins manifest. -func decodeManifestJSON(body []byte, out any) error { - if len(body) > maxManifestBytes { - return errors.New("chunkstore: manifest exceeds byte bound") - } - d := json.NewDecoder(bytes.NewReader(body)) - var value func(int) error - value = func(depth int) error { - if depth > 8 { - return errors.New("chunkstore: manifest nesting exceeds bound") - } - tok, err := d.Token() - if err != nil { - return err - } - delim, ok := tok.(json.Delim) - if !ok { - return nil - } - switch delim { - case '{': - keys := map[string]bool{} - for d.More() { - t, err := d.Token() - if err != nil { - return err - } - k, ok := t.(string) - if !ok || keys[k] { - return errors.New("chunkstore: duplicate manifest key") - } - keys[k] = true - if err := value(depth + 1); err != nil { - return err - } - } - _, err = d.Token() - return err - case '[': - for d.More() { - if err := value(depth + 1); err != nil { - return err - } - } - _, err = d.Token() - return err - default: - return errors.New("chunkstore: invalid manifest delimiter") - } - } - if err := value(0); err != nil { - return err - } - if _, err := d.Token(); err != io.EOF { - return errors.New("chunkstore: trailing manifest bytes") - } - return json.Unmarshal(body, out) -} diff --git a/seaweed-block/core/frontend/chunkstore/manifest_format.go b/seaweed-block/core/frontend/chunkstore/manifest_format.go deleted file mode 100644 index bd5f852035..0000000000 --- a/seaweed-block/core/frontend/chunkstore/manifest_format.go +++ /dev/null @@ -1,105 +0,0 @@ -package chunkstore - -import ( - "bytes" - "encoding/hex" - "encoding/json" - "errors" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -type segmentChunkV2Doc struct { - Key string `json:"key"` - // SHA256 covers stored object bytes, before any encoding is decoded. - SHA256 string `json:"sha256"` - Encoding string `json:"enc"` - BirthLSN *uint64 `json:"birth_lsn"` -} - -type segmentV2Doc struct { - Format int `json:"format"` - Range uint64 `json:"range"` - ChunkBytes uint64 `json:"chunk_bytes"` - Owner string `json:"owner"` - MaxBirthLSN *uint64 `json:"max_birth_lsn"` - Chunks map[uint64]segmentChunkV2Doc `json:"chunks"` -} - -type legacyChunkRefDoc struct { - Key string - SHA256 [32]byte -} - -type legacySegmentDoc struct { - Format int `json:"format"` - Range uint64 `json:"range"` - ChunkBytes uint64 `json:"chunk_bytes"` - Owner string `json:"owner"` - Chunks map[uint64]legacyChunkRefDoc `json:"chunks"` -} - -func encodeSegmentV2(group, chunkBytes uint64, owner string, chunks map[uint64]storage.ChunkRef) ([]byte, uint64, error) { - doc := segmentV2Doc{Format: 2, Range: group, ChunkBytes: chunkBytes, Owner: owner, Chunks: map[uint64]segmentChunkV2Doc{}} - var maxBirth uint64 - for idx, ref := range chunks { - birth := ref.BirthLSN - doc.Chunks[idx] = segmentChunkV2Doc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:]), Encoding: ref.Encoding, BirthLSN: &birth} - maxBirth = max(maxBirth, birth) - } - doc.MaxBirthLSN = &maxBirth - body, err := json.Marshal(doc) - return body, maxBirth, err -} - -func decodeSegment(body []byte, ref storage.ChunkSegment, remoteLSN uint64) (segmentDoc, error) { - var discriminator struct { - Format int `json:"format"` - } - if err := decodeManifestJSON(body, &discriminator); err != nil { - return segmentDoc{}, err - } - if discriminator.Format != ref.SegFormat { - return segmentDoc{}, errors.New("chunkstore: segment format/reference mismatch") - } - d := json.NewDecoder(bytes.NewReader(body)) - d.DisallowUnknownFields() - result := segmentDoc{Chunks: map[uint64]storage.ChunkRef{}} - switch discriminator.Format { - case 1: - var doc legacySegmentDoc - if err := d.Decode(&doc); err != nil { - return result, err - } - result.Format, result.Range, result.ChunkBytes, result.Owner = doc.Format, doc.Range, doc.ChunkBytes, doc.Owner - for idx, cr := range doc.Chunks { - result.Chunks[idx] = storage.ChunkRef{Key: cr.Key, SHA256: cr.SHA256, Encoding: "full", BirthLSN: ref.MaxBirthLSN} - } - case 2: - var doc segmentV2Doc - if err := d.Decode(&doc); err != nil { - return result, err - } - if doc.MaxBirthLSN == nil || *doc.MaxBirthLSN != ref.MaxBirthLSN || *doc.MaxBirthLSN > remoteLSN { - return result, errors.New("chunkstore: segment birth maximum mismatch") - } - result.Format, result.Range, result.ChunkBytes, result.Owner = doc.Format, doc.Range, doc.ChunkBytes, doc.Owner - var maxBirth uint64 - for idx, cr := range doc.Chunks { - sum, err := hex.DecodeString(cr.SHA256) - if err != nil || len(sum) != 32 || cr.Encoding != "full" || cr.BirthLSN == nil || *cr.BirthLSN > remoteLSN { - return result, errors.New("chunkstore: invalid segment chunk encoding/hash/birth") - } - v := storage.ChunkRef{Key: cr.Key, Encoding: cr.Encoding, BirthLSN: *cr.BirthLSN} - copy(v.SHA256[:], sum) - result.Chunks[idx] = v - maxBirth = max(maxBirth, v.BirthLSN) - } - if maxBirth != *doc.MaxBirthLSN { - return result, errors.New("chunkstore: incorrect segment birth maximum") - } - default: - return result, errors.New("chunkstore: unsupported segment format") - } - return result, nil -} diff --git a/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go b/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go deleted file mode 100644 index a7fa099313..0000000000 --- a/seaweed-block/core/frontend/chunkstore/manifest_perf_test.go +++ /dev/null @@ -1,187 +0,0 @@ -//go:build manifest_perf - -package chunkstore - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/binary" - "fmt" - "os" - "path" - "path/filepath" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// File-backed proxy: every immutable object is written and fsynced. Metadata -// RPCs use the deterministic filer model; results exclude network/guest fsync. -type manifestFiles struct{ dir string } - -func (b manifestFiles) Put(ctx context.Context, data []byte) (string, error) { - if err := ctx.Err(); err != nil { - return "", err - } - f, err := os.CreateTemp(b.dir, "blob-") - if err != nil { - return "", err - } - if _, err = f.Write(data); err == nil { - err = f.Sync() - } - cerr := f.Close() - if err == nil { - err = cerr - } - return filepath.Base(f.Name()), err -} -func (b manifestFiles) Get(ctx context.Context, key string) ([]byte, error) { - if err := ctx.Err(); err != nil { - return nil, err - } - return os.ReadFile(filepath.Join(b.dir, key)) -} - -func TestManifestPerf_64DirtyChunks(t *testing.T) { - for rep := 0; rep < 3; rep++ { - order := []int{1, 8} - if rep%2 == 1 { - order = []int{8, 1} - } - for _, parallel := range order { - dir := t.TempDir() - f := newFakeFiler() - b := manifestFiles{dir} - r, err := NewChunkRemote(f, b, "/chunks/v1") - if err != nil { - t.Fatal(err) - } - s, err := storage.CreateWALStore(filepath.Join(dir, "store"), 64*1024, 4096) - if err != nil { - t.Fatal(err) - } - if _, err = s.Recover(); err != nil { - t.Fatal(err) - } - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 1024, Epoch: 1, Holder: "h1", FreshFromHead: true, UploadConcurrency: parallel}) - if err != nil { - t.Fatal(err) - } - for i := 0; i < 64; i++ { - if _, err = s.Write(uint32(i*1024), bytes.Repeat([]byte{byte(i + 1)}, 4096)); err != nil { - t.Fatal(err) - } - } - start := time.Now() - if _, err = s.Sync(); err != nil { - t.Fatal(err) - } - syncTime := time.Since(start) - start = time.Now() - if _, err = l.Capture(context.Background()); err != nil { - t.Fatal(err) - } - cutTime := time.Since(start) - t.Logf("PERF dirty64 rep=%d parallel=%d chunk_bytes=4194304 upload_bytes=268435456 sync_ms=%.3f cut_ms=%.3f", rep, parallel, float64(syncTime.Microseconds())/1000, float64(cutTime.Microseconds())/1000) - if err = s.Close(); err != nil { - t.Fatal(err) - } - } - } -} - -func TestManifestPerf_Written10GiBSnapshotFork(t *testing.T) { - ctx := context.Background() - f := newFakeFiler() - c := newCat(t, f) - b := manifestFiles{t.TempDir()} - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v1", IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - if _, err := c.EnsureVolume(ctx, "v1", Geometry{NumBlocks: 10 * 1024 * 1024 * 1024 / 4096, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { - t.Fatal(err) - } - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - h, _ := r.GetHead(ctx) - next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} - keys := make([]string, 2560) - for i := range keys { - keys[i] = fmt.Sprintf("data/%d", i) - } - intent, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: h.Gen, Epoch: 1, Holder: "h1", Keys: keys}) - if err != nil { - t.Fatal(err) - } - data := bytes.Repeat([]byte{0xa5}, 4<<20) - start := time.Now() - for i, key := range keys { - binary.LittleEndian.PutUint64(data, uint64(i)) - if err := r.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - next.Chunks[uint64(i)] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} - } - gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next) - if err != nil { - t.Fatal(err) - } - next.Gen = gen - if err = r.DeleteIntent(ctx, intent); err != nil { - t.Fatal(err) - } - t.Logf("PERF materialized_bytes=10737418240 chunks=2560 upload_ms=%.3f", float64(time.Since(start).Microseconds())/1000) - for _, format := range []string{"flat", "segmented"} { - if format == "segmented" { - prepared, ids, err := r.PrepareManifest(ctx, next, next, 4<<20) - if err != nil { - t.Fatal(err) - } - gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: next.Gen, Epoch: next.Epoch}, prepared) - if err != nil { - t.Fatal(err) - } - prepared.Gen = gen - next = prepared - for _, id := range ids { - if err = r.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - } - entry, err := headEntry(next) - if err != nil { - t.Fatal(err) - } - segmentBytes := 0 - for _, ref := range next.Segments { - body, err := r.Get(ctx, ref.Key) - if err != nil { - t.Fatal(err) - } - segmentBytes += len(body) - } - for rep := 0; rep < 3; rep++ { - name := fmt.Sprintf("%s-%d", format, rep) - start := time.Now() - snap, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: name}, next) - if err != nil { - t.Fatal(err) - } - snapTime := time.Since(start) - target := "fork-" + name - if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: target, IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - start = time.Now() - if _, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: name, Target: target, RequestID: target}); err != nil { - t.Fatal(err) - } - forkTime := time.Since(start) - t.Logf("PERF written10GiB format=%s rep=%d head_bytes=%d total_segment_bytes=%d snapshot_entry_bytes=%d snapshot_ms=%.3f fork_ms=%.3f", format, rep, len(entry.Content), segmentBytes, snap.ManifestBytes, float64(snapTime.Microseconds())/1000, float64(forkTime.Microseconds())/1000) - } - } -} diff --git a/seaweed-block/core/frontend/chunkstore/manifest_review_test.go b/seaweed-block/core/frontend/chunkstore/manifest_review_test.go deleted file mode 100644 index a107b81bfb..0000000000 --- a/seaweed-block/core/frontend/chunkstore/manifest_review_test.go +++ /dev/null @@ -1,237 +0,0 @@ -package chunkstore - -import ( - "context" - "encoding/json" - "path" - "strings" - "testing" - "time" - "unicode" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -type manifestFilerBlobs struct { - Filer - Blobs -} - -func TestManifest_MixedRepresentationRefusesReadAndWholeGC(t *testing.T) { - for _, format := range []int{1, 2} { - t.Run(string(rune('0'+format)), func(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := publishSegmented(t, f, b) - if err := r.Put(ctx, "eligible-orphan", []byte("keep on mark error")); err != nil { - t.Fatal(err) - } - if _, err := g.Run(ctx); err != nil { - t.Fatal(err) - } - *now = now.Add(2 * time.Hour) - e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) - if err != nil { - t.Fatal(err) - } - var doc map[string]json.RawMessage - if err = json.Unmarshal(e.Content, &doc); err != nil { - t.Fatal(err) - } - if format == 1 { - doc["format"] = json.RawMessage("1") - } else { - doc["chunks"] = json.RawMessage("{}") - } - e.Content, err = json.Marshal(doc) - if err != nil { - t.Fatal(err) - } - if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { - t.Fatal(err) - } - if h, err := r.GetHead(ctx); err == nil { - t.Errorf("mixed root returned readable image (possibly zeros): %+v", h) - } - if h, _, err := c.ReadHead(ctx, "v1"); err == nil { - t.Errorf("catalog accepted mixed root: %+v", h) - } - _, _, before := b.counts() - for _, apply := range []bool{false, true} { - if _, err := g.run(ctx, apply); err == nil { - t.Errorf("mixed root accepted by GC apply=%v", apply) - } - } - _, _, after := b.counts() - if before != after { - t.Fatal("failed mark deleted objects") - } - }) - } -} - -func TestManifest_UsageCountsOwnedClippedChunksAndForkHolders(t *testing.T) { - ctx := context.Background() - f := newFakeFiler() - b := gcBlobs{newFakeBlobs()} - c, err := NewCatalog(manifestFilerBlobs{f, b}, catBase) - if err != nil { - t.Fatal(err) - } - for _, vol := range []string{"v1", "v2"} { - if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - } - if _, err = c.EnsureVolume(ctx, "v1", Geometry{NumBlocks: 10, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } - r, h := publishSegmented(t, f, b) - if _, err = c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s", RequestID: "snapshot"}, h); err != nil { - t.Fatal(err) - } - u, err := c.Usage(ctx, "v1") - if err != nil { - t.Fatal(err) - } - if u.LiveChunks != 2 || u.LiveBytes != 40960 || len(u.Snapshots) != 1 || u.Snapshots[0].Chunks != 2 || u.Snapshots[0].ExclusiveBytes != 0 { - t.Fatalf("segmented clipped usage: %+v", u) - } - segmentBytes := uint64(0) - for _, ref := range h.Segments { - body, e := r.Get(ctx, ref.Key) - if e != nil { - t.Fatal(e) - } - segmentBytes += uint64(len(body)) - } - if u.ManifestBindings != 1 || u.ManifestBytes != segmentBytes || u.StoredBytes != 40960+segmentBytes || u.StoredUpperBound { - t.Fatalf("manifest bytes must not be charged as a full data chunk: %+v", u) - } - if _, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s", Target: "v2", RequestID: "fork"}); err != nil { - t.Fatal(err) - } - if _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN}); err != nil { - t.Fatal(err) - } - u, err = c.Usage(ctx, "v1") - if err != nil { - t.Fatal(err) - } - if u.LiveChunks != 0 || u.Snapshots[0].Chunks != 2 || u.Snapshots[0].ExclusiveBytes != 0 { - t.Fatalf("foreign fork owner omitted: %+v", u) - } - fork, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) - fh, err := fork.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if _, err = fork.CASHead(ctx, storage.ChunkHeadVersion{Gen: fh.Gen, Epoch: fh.Epoch}, storage.ChunkHead{RemoteLSN: fh.RemoteLSN}); err != nil { - t.Fatal(err) - } - u, err = c.Usage(ctx, "v1") - if err != nil || u.Snapshots[0].ExclusiveBytes != 40960 { - t.Fatalf("snapshot exclusivity must use clipped owner bytes: %+v %v", u, err) - } -} - -func TestManifest_RejectsFieldAliases(t *testing.T) { - for _, field := range []string{`"segments":null`, `"Segments":null`, `"CHUNK_BYTES":0`, `"chunk_count":0`} { - body := []byte(`{"format":1,"gen":1,"epoch":1,"holder":"h","chunks":{},` + field + `}`) - if _, err := DecodeHeadDocument("mixed", body); err == nil { - t.Errorf("format1 accepted residual field %s", field) - } - } - for _, field := range []string{`"chunks":{}`, `"Chunks":null`} { - body := []byte(`{"format":2,"gen":1,"epoch":1,"holder":"h","chunk_bytes":32768,"chunk_count":0,"segments":{},` + field + `}`) - if _, err := DecodeHeadDocument("mixed", body); err == nil { - t.Errorf("format2 accepted residual field %s", field) - } - } -} - -func TestManifest_FormatSpecificFoldedFields(t *testing.T) { - for _, tc := range []struct { - format int - name string - }{{1, "segments"}, {1, "chunk_bytes"}, {1, "chunk_count"}, {2, "chunks"}} { - variants := map[string]bool{tc.name: true, strings.ToUpper(tc.name): true} - original := []rune(tc.name) - for i, r := range original { - for folded := unicode.SimpleFold(r); folded != r; folded = unicode.SimpleFold(folded) { - key := append([]rune(nil), original...) - key[i] = folded - variants[string(key)] = true - } - } - for key := range variants { - encoded, _ := json.Marshal(key) - suffix := string(encoded) + `:null` - root := `{"format":1,"gen":1,"epoch":1,"holder":"h",` + suffix + `}` - if tc.format == 2 { - root = `{"format":2,"gen":1,"epoch":1,"holder":"h","chunk_bytes":32768,"segments":{},` + suffix + `}` - } - if _, err := DecodeHeadDocument("folded", []byte(root)); err == nil { - t.Errorf("format%d accepted folded residual %s", tc.format, key) - } - } - } - for _, root := range []string{ - `{"format":1,"gen":1,"epoch":1,"holder":"h","\u017fegments":null}`, - `{"format":2,"gen":1,"epoch":1,"holder":"h","chunk_bytes":32768,"segments":{},"chun\u212as":null}`, - } { - if _, err := DecodeHeadDocument("escaped", []byte(root)); err == nil { - t.Errorf("accepted escaped mixed root: %s", root) - } - } -} - -func TestManifest_LongSDiscriminatorCorruptionRefusesReadAndGC(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, _ := publishSegmented(t, f, b) - if err := r.Put(ctx, "orphan", []byte("do not delete after bad mark")); err != nil { - t.Fatal(err) - } - if _, err := g.Run(ctx); err != nil { - t.Fatal(err) - } - *now = now.Add(2 * time.Hour) - e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) - if err != nil { - t.Fatal(err) - } - var fields map[string]json.RawMessage - if err = json.Unmarshal(e.Content, &fields); err != nil { - t.Fatal(err) - } - fields["format"] = json.RawMessage("1") - fields["\u017fegments"] = fields["segments"] - delete(fields, "segments") - delete(fields, "chunk_bytes") - delete(fields, "chunk_count") - e.Content, err = json.Marshal(fields) - if err != nil { - t.Fatal(err) - } - if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { - t.Fatal(err) - } - if h, err := r.GetHead(ctx); err == nil { - t.Errorf("Unicode mixed root became readable empty image: %+v", h) - } - if h, _, err := c.ReadHead(ctx, "v1"); err == nil { - t.Errorf("catalog accepted Unicode mixed root: %+v", h) - } - _, _, before := b.counts() - for _, apply := range []bool{false, true} { - if _, err := g.run(ctx, apply); err == nil { - t.Errorf("Unicode mixed root accepted by GC apply=%v", apply) - } - } - _, _, after := b.counts() - if before != after { - t.Fatal("Unicode mixed root allowed partial delete") - } -} diff --git a/seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go b/seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go deleted file mode 100644 index dd093d6c84..0000000000 --- a/seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package chunkstore - -import ( - "context" - "fmt" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Metadata-only scaling probe: one chunk per 1-GiB segment, all unchanged. -// No volume data allocation or remote I/O is included. Report ns/op and allocs; -// the old per-group scan visits groups*groups base references. -func BenchmarkPrepareManifestUnchangedGroups(b *testing.B) { - for _, n := range []int{256, 1024, 4096} { - b.Run(fmt.Sprint(n), func(b *testing.B) { - r, err := NewChunkRemote(newFakeFiler(), newFakeBlobs(), "/chunks/v1") - if err != nil { - b.Fatal(err) - } - base := storage.ChunkHead{Chunks: map[uint64]storage.ChunkRef{}, Segments: map[uint64]storage.ChunkSegment{}, ChunkBytes: 1 << 30, ManifestChunkCount: n} - for i := 0; i < n; i++ { - base.Chunks[uint64(i)] = storage.ChunkRef{Key: fmt.Sprintf("@v1/chunk/%d", i)} - base.Segments[uint64(i)] = storage.ChunkSegment{Key: fmt.Sprintf("@v1/seg/%d", i), Owner: "v1", Count: 1} - } - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - next, ids, err := r.PrepareManifest(context.Background(), base, base, 1<<30) - if err != nil || len(ids) != 0 || len(next.Segments) != n { - b.Fatalf("unchanged segment reuse: %v, intents=%v", err, ids) - } - } - }) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/manifest_test.go b/seaweed-block/core/frontend/chunkstore/manifest_test.go deleted file mode 100644 index fa0309f434..0000000000 --- a/seaweed-block/core/frontend/chunkstore/manifest_test.go +++ /dev/null @@ -1,313 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/json" - "fmt" - "path" - "path/filepath" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func TestManifest_CapturePublishesSegmentRoot(t *testing.T) { - f, b, _, _, _ := gcFixture(t) - ctx := context.Background() - r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err != nil { - t.Fatal(err) - } - p := filepath.Join(t.TempDir(), "volume") - s, err := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8}) - if err != nil { - t.Fatal(err) - } - defer s.Close() - if _, err = s.Recover(); err != nil { - t.Fatal(err) - } - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true}) - if err != nil { - t.Fatal(err) - } - want := bytes.Repeat([]byte{0x61}, 4096) - if _, err = s.Write(0, want); err != nil { - t.Fatal(err) - } - if _, err = l.Capture(ctx); err != nil { - t.Fatal(err) - } - e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName) - if err != nil { - t.Fatal(err) - } - var doc struct { - Format int `json:"format"` - Chunks map[string]any `json:"chunks"` - Segments map[string]any `json:"segments"` - } - if err = json.Unmarshal(e.Content, &doc); err != nil { - t.Fatal(err) - } - if doc.Format != 3 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 { - t.Fatalf("cut did not publish a small segmented root: %s", e.Content) - } - h, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - data, err := r.Get(ctx, h.Chunks[0].Key) - if err != nil || !bytes.Equal(data[:4096], want) { - t.Fatalf("resolved cut bytes: %v", err) - } -} - -func publishSegmented(t *testing.T, f *fakeFiler, b gcBlobs) (*ChunkRemote, storage.ChunkHead) { - t.Helper() - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41), 1: chunkBytes(0x42)}) - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - next, ids, err := r.PrepareManifest(context.Background(), h, h, 32768) - if err != nil { - t.Fatal(err) - } - gen, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next) - if err != nil { - t.Fatal(err) - } - next.Gen = gen - for _, id := range ids { - if err = r.DeleteIntent(context.Background(), id); err != nil { - t.Fatal(err) - } - } - return r, next -} - -func TestManifest_ForkAfterParentSnapshotDelete(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - r, h := publishSegmented(t, f, b) - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { - t.Fatal(err) - } - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { - t.Fatal(err) - } - fork, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) - fh, err := fork.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if len(fh.Segments) != 1 || len(fh.Chunks) != 2 { - t.Fatalf("fork lost root/children: %+v", fh) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN}); err != nil { - t.Fatal(err) - } - for i := 0; i < 3; i++ { - if _, err := g.Run(ctx); err != nil { - t.Fatal(err) - } - *now = now.Add(2 * time.Hour) - } - fh, err = fork.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - for idx, ref := range fh.Chunks { - got, err := fork.Get(ctx, ref.Key) - if err != nil || !bytes.Equal(got, chunkBytes(byte(0x41+idx))) { - t.Fatalf("fork lost shared chunk %d after parent delete: %v", idx, err) - } - } -} - -func TestManifest_GCReadsPublishedSegments(t *testing.T) { - f, b, _, g, _ := gcFixture(t) - publishSegmented(t, f, b) - out, err := g.Preview(context.Background()) - if err != nil || len(out.Roots) == 0 { - t.Fatalf("GC cannot trace published segment: %+v %v", out, err) - } -} - -func TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot(t *testing.T) { - f, b, _, _, _ := gcFixture(t) - ctx := context.Background() - r, h := publishSegmented(t, f, b) - // A second logical GiB uses a different immutable range; no local 1GiB - // allocation is needed to exercise remote manifest publication. - per := manifestSegmentBytes / h.ChunkBytes - key := "second-range" - data := chunkBytes(0x77) - if err := r.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - h.Chunks[per] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} - next, ids, err := r.PrepareManifest(ctx, h, h, h.ChunkBytes) - if err != nil { - t.Fatal(err) - } - if next.Segments[0] != h.Segments[0] { - t.Fatal("unchanged range rewritten") - } - // Simulate death after immutable upload, with no CAS or cleanup. - old, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if len(old.Chunks) != 2 || len(old.Segments) != 1 { - t.Fatal("unpublished segment changed old root") - } - intents, err := r.ListIntents(ctx) - if err != nil || len(intents) != len(ids) { - t.Fatalf("uploaded segment unprotected: %v", err) - } - for _, ref := range old.Chunks { - if _, err := r.Get(ctx, ref.Key); err != nil { - t.Fatal(err) - } - } - gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: old.Gen, Epoch: old.Epoch}, next) - if err != nil || gen != old.Gen+1 { - t.Fatalf("normal CAS semantics: %d %v", gen, err) - } - - published, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - changed := published - changed.Chunks = make(map[uint64]storage.ChunkRef, len(published.Chunks)) - for idx, ref := range published.Chunks { - changed.Chunks[idx] = ref - } - if err = r.Put(ctx, "changed-range-zero", data); err != nil { - t.Fatal(err) - } - changed.Chunks[0] = storage.ChunkRef{Key: "changed-range-zero", SHA256: sha256.Sum256(data)} - rewritten, _, err := r.PrepareManifest(ctx, published, changed, published.ChunkBytes) - if err != nil { - t.Fatal(err) - } - if rewritten.Segments[0] == published.Segments[0] || rewritten.Segments[1] != published.Segments[1] { - t.Fatal("cut must rewrite only the changed range") - } -} - -func TestManifest_UnreadablePublishedSegmentRefusesWholeGC(t *testing.T) { - for _, apply := range []bool{false, true} { - t.Run(fmt.Sprint(apply), func(t *testing.T) { - f, b, _, g, now := gcFixture(t) - ctx := context.Background() - r, h := publishSegmented(t, f, b) - if err := r.Put(ctx, "unreachable", []byte("orphan")); err != nil { - t.Fatal(err) - } - if _, err := g.Run(ctx); err != nil { - t.Fatal(err) - } - *now = now.Add(2 * time.Hour) - var ref storage.ChunkSegment - for _, v := range h.Segments { - ref = v - break - } - dir, name, err := r.keyLocation(ref.Key) - if err != nil { - t.Fatal(err) - } - entry, err := f.LookupEntry(ctx, dir, name) - if err != nil { - t.Fatal(err) - } - b.mu.Lock() - b.data[string(entry.Extended[extFid])] = []byte("corrupted segment") - before := len(b.data) - b.mu.Unlock() - if _, err := g.run(ctx, apply); err == nil { - t.Fatal("unreadable published segment accepted") - } - b.mu.Lock() - after := len(b.data) - b.mu.Unlock() - if before != after { - t.Fatal("failed mark partially deleted data") - } - }) - } -} - -func TestManifest_CopyIntentProtectsChildrenWithoutHead(t *testing.T) { - f, b, _, g, now := gcFixture(t) - ctx := context.Background() - r, h := publishSegmented(t, f, b) - if _, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: h.Gen, Epoch: h.Epoch, Holder: "snapshot:v1/unpublished/attempt", Keys: headKeys(h), Segments: h.Segments, ChunkBytes: h.ChunkBytes}); err != nil { - t.Fatal(err) - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN}); err != nil { - t.Fatal(err) - } - for i := 0; i < 3; i++ { - if out, err := g.Run(ctx); err != nil || out.Reclaimed != 0 { - t.Fatalf("copy intent lost transitive children: %+v %v", out, err) - } - *now = now.Add(2 * time.Hour) - } - for _, ref := range h.Chunks { - if _, err := r.Get(ctx, ref.Key); err != nil { - t.Fatal(err) - } - } -} - -func TestManifest_NoopFlatUpgradeUsesOneNormalGeneration(t *testing.T) { - f, b, _, _, _ := gcFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - old, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - p := filepath.Join(t.TempDir(), "store") - s, err := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8}) - if err != nil { - t.Fatal(err) - } - defer s.Close() - if _, err = s.Recover(); err != nil { - t.Fatal(err) - } - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true}) - if err != nil { - t.Fatal(err) - } - if _, err = l.Capture(ctx); err != nil { - t.Fatal(err) - } - h, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if h.Segments == nil || h.Gen != old.Gen+1 || h.Epoch != 1 || h.RemoteLSN != old.RemoteLSN { - t.Fatalf("upgrade changed normal-cut lineage: old=%+v new=%+v", old, h) - } - if _, err = l.Capture(ctx); err != nil { - t.Fatal(err) - } - again, err := r.GetHead(ctx) - if err != nil || again.Gen != h.Gen || again.Epoch != h.Epoch { - t.Fatalf("second no-op advanced lineage: %+v %v", again, err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go b/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go deleted file mode 100644 index 8a9887873b..0000000000 --- a/seaweed-block/core/frontend/chunkstore/manifest_upgrade.go +++ /dev/null @@ -1,80 +0,0 @@ -package chunkstore - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func (c *Catalog) prepareLegacyHead(ctx context.Context, root string, base, next storage.ChunkHead, geo Geometry) (storage.ChunkHead, []string, error) { - if next.Segments != nil || len(next.Chunks) == 0 { - return next, nil, nil - } - if c.blobs == nil { - return next, nil, errors.New("chunkstore: legacy data upgrade needs blob storage") - } - r, err := NewChunkRemote(c.f, c.blobs, root) - if err != nil { - return next, nil, err - } - return r.PrepareManifest(ctx, base, next, uint64(geo.BlockSize)*uint64(geo.ChunkBlocks)) -} -func (c *Catalog) dropManifestIntents(ctx context.Context, root string, ids []string) { - for _, id := range ids { - c.dropIntent(ctx, root, id) - } -} - -// Fork identity is a persisted protocol. Old snapshots keep the pre-format-3 -// canonical encoding even when their next publication upgrades the manifest. -func snapshotHeadDigest(h storage.ChunkHead, embedded json.RawMessage) (string, error) { - var version struct { - Format int `json:"format"` - } - if err := json.Unmarshal(embedded, &version); err != nil { - return "", err - } - if version.Format == 3 { - return headDigest(h) - } - type oldHead struct { - Segments map[uint64]legacySegmentRefDoc `json:"segments,omitempty"` - ChunkBytes uint64 `json:"chunk_bytes,omitempty"` - ChunkCount int `json:"chunk_count,omitempty"` - Format int `json:"format"` - Gen uint64 `json:"gen"` - Epoch uint64 `json:"epoch"` - Holder string `json:"holder"` - RemoteLSN uint64 `json:"remote_lsn"` - Chunks map[uint64]refDoc `json:"chunks,omitempty"` - State string `json:"state,omitempty"` - DetachedBy *detachedByDoc `json:"detachedBy,omitempty"` - } - d := oldHead{Format: version.Format, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State} - if h.DetachedBy != nil { - d.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen} - } - if version.Format == 2 { - d.Segments = map[uint64]legacySegmentRefDoc{} - d.ChunkBytes = h.ChunkBytes - d.ChunkCount = h.ManifestChunkCount - for idx, ref := range h.Segments { - d.Segments[idx] = legacySegmentRefDoc{Key: ref.Key, SHA256: ref.SHA256, Owner: ref.Owner, Count: ref.Count} - } - } else { - d.Chunks = map[uint64]refDoc{} - for idx, ref := range h.Chunks { - d.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} - } - } - body, err := json.Marshal(d) - if err != nil { - return "", err - } - sum := sha256.Sum256(body) - return hex.EncodeToString(sum[:]), nil -} diff --git a/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go b/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go deleted file mode 100644 index 25acbb33d0..0000000000 --- a/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// ReclaimKey is GC's step for one own key: the binding is tombstoned and -// kept, the needle deleted; repeating it is a no-op; a qualified key is -// refused. -func TestChunkRemote_ReclaimKey(t *testing.T) { - f, b := newFakeFiler(), newFakeBlobs() - r, err := NewChunkRemote(f, b, catBase+"/v1") - if err != nil { - t.Fatal(err) - } - ctx := context.Background() - if err := r.Put(ctx, "k1", []byte("payload")); err != nil { - t.Fatal(err) - } - fid := r.fids["k1"] - if err := r.ReclaimKey(ctx, "k1", gcBlobs{b}); err != nil { - t.Fatal(err) - } - e, err := f.LookupEntry(ctx, r.keyDir(), "k1") - if err != nil { - t.Fatalf("binding removed: %v", err) - } - if string(e.Extended[extGCDeleted]) != "done" || string(e.Extended[extFid]) != fid { - t.Fatalf("binding after reclaim: %q fid %q; want done, same fid", e.Extended[extGCDeleted], e.Extended[extFid]) - } - if _, err := b.Get(ctx, fid); err == nil { - t.Fatal("needle still readable after reclaim") - } - if err := r.ReclaimKey(ctx, "k1", gcBlobs{b}); err != nil { - t.Fatalf("repeated reclaim: %v", err) - } - if err := r.Put(ctx, "k1", []byte("again")); !errors.Is(err, storage.ErrChunkKeyExists) { - t.Fatalf("rebinding a reclaimed key: %v", err) - } - if err := r.ReclaimKey(ctx, "@v0/k1", gcBlobs{b}); err == nil { - t.Fatal("reclaim of an owner-qualified key accepted") - } -} diff --git a/seaweed-block/core/frontend/chunkstore/remote.go b/seaweed-block/core/frontend/chunkstore/remote.go index cd8e87f18a..f588d3e397 100644 --- a/seaweed-block/core/frontend/chunkstore/remote.go +++ b/seaweed-block/core/frontend/chunkstore/remote.go @@ -28,7 +28,7 @@ type Filer interface { // dir whose names start with prefix and sort after startAfter, in name // order. A directory that does not exist lists as empty. ListEntries(ctx context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) - // DeleteEntry removes dir/name without deleting any data, and only if + // DeleteEntry removes dir/name and lets the filer reclaim its data, only if // every expected extended key still holds the given value; otherwise // ErrPrecondition (also when the entry is missing and expected is not // empty). An unconditional delete of a missing entry succeeds. diff --git a/seaweed-block/core/frontend/chunkstore/restore.go b/seaweed-block/core/frontend/chunkstore/restore.go deleted file mode 100644 index 22a12d1f83..0000000000 --- a/seaweed-block/core/frontend/chunkstore/restore.go +++ /dev/null @@ -1,163 +0,0 @@ -package chunkstore - -import ( - "context" - "encoding/json" - "errors" - "path" - "strings" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// restoreIndependentName is the write-once entry that ends a restore's -// lineage: written only when the restored volume's HEAD holds no qualified -// ref, so from then on nothing of the volume reaches its source's chunks. -const ( - restoreIndependentName = "RESTORE-INDEPENDENT" - kindRestoreIndependent = "chunkrestoreindependent" -) - -// Restore error codes. -const ( - // CodeNotRestore: the volume was not made by Restore. - CodeNotRestore = "not_restore" - // CodeRestoreIncomplete: HEAD still holds qualified refs (or no HEAD). - CodeRestoreIncomplete = "restore_incomplete" -) - -// RestoreIndependence is the content of restoreIndependentName. -type RestoreIndependence struct { - Format int `json:"format"` - VolumeID string `json:"volume_id"` - HeadGen uint64 `json:"head_gen"` - MarkedNs int64 `json:"marked_ns"` -} - -// ForeignRefs counts the refs of vol's HEAD h that name ANOTHER volume's -// chunks or segments: a "@/" key whose owner is not vol. A resolved -// HEAD writes every chunk key in owner-qualified form, vol's own included, -// so a bare "@" prefix does not make a ref foreign; an unqualified key is -// always vol's own. -func ForeignRefs(h storage.ChunkHead, vol string) int { - foreign := func(key string) bool { - if !strings.HasPrefix(key, "@") { - return false - } - owner, _, ok := strings.Cut(key[1:], "/") - return !ok || owner != vol - } - n := 0 - for _, ref := range h.Chunks { - if foreign(ref.Key) { - n++ - } - } - for _, seg := range h.Segments { - if foreign(seg.Key) { - n++ - } - } - return n -} - -// MarkIndependent records that restored volume vol no longer depends on its -// source: refused unless vol was made by Restore and its current HEAD holds -// no qualified ref. Write-once: an existing marker is a replay (ok). -func (c *Catalog) MarkIndependent(ctx context.Context, vol string) (RestoreIndependence, error) { - root, err := c.volRoot(vol) - if err != nil { - return RestoreIndependence{}, err - } - if m, ok, err := c.ReadIndependence(ctx, vol); err != nil || ok { - return m, err - } - v, ok, err := c.ReadVolume(ctx, vol) - if err != nil { - return RestoreIndependence{}, err - } - if !ok || v.Origin != OriginRestore { - return RestoreIndependence{}, catErr(CodeNotRestore, false, nil, "volume %s was not made by restore", vol) - } - h, has, err := c.ReadHead(ctx, vol) - if err != nil { - return RestoreIndependence{}, err - } - if !has || h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { - return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s has no live HEAD", vol) - } - q, err := c.foreignRefsOf(ctx, vol, h) - if err != nil { - return RestoreIndependence{}, err - } - if q > 0 { - return RestoreIndependence{}, catErr(CodeRestoreIncomplete, false, nil, "volume %s: HEAD gen %d still holds %d refs to another volume", vol, h.Gen, q) - } - m := RestoreIndependence{Format: volumeFormat, VolumeID: vol, HeadGen: h.Gen, MarkedNs: c.now().UnixNano()} - body, err := json.Marshal(m) - if err != nil { - return RestoreIndependence{}, err - } - now := time.Now().Unix() - e := &filerpb.Entry{ - Name: restoreIndependentName, - Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"}, - Extended: map[string][]byte{extKind: []byte(kindRestoreIndependent)}, - Content: body, - } - if err := c.f.CreateEntry(ctx, root, e, true); err != nil { - if !errors.Is(err, ErrExists) { - return RestoreIndependence{}, remoteErr(err, "create %s of %s", restoreIndependentName, vol) - } - m, ok, err := c.ReadIndependence(ctx, vol) - if err == nil && !ok { - err = remoteErr(nil, "re-read %s of %s", restoreIndependentName, vol) - } - return m, err - } - return m, nil -} - -// ReadIndependence returns vol's independence marker; ok is false when the -// restore has not ended (or vol is not a restore). -func (c *Catalog) ReadIndependence(ctx context.Context, vol string) (RestoreIndependence, bool, error) { - root, err := c.volRoot(vol) - if err != nil { - return RestoreIndependence{}, false, err - } - e, err := c.f.LookupEntry(ctx, root, restoreIndependentName) - if errors.Is(err, ErrNotFound) { - return RestoreIndependence{}, false, nil - } - if err != nil { - return RestoreIndependence{}, false, remoteErr(err, "read %s of %s", restoreIndependentName, vol) - } - if k := string(e.Extended[extKind]); k != kindRestoreIndependent { - return RestoreIndependence{}, false, remoteErr(nil, "%s of %s: kind %q", restoreIndependentName, vol, k) - } - var m RestoreIndependence - if err := json.Unmarshal(e.GetContent(), &m); err != nil || m.VolumeID != vol { - return RestoreIndependence{}, false, remoteErr(err, "decode %s of %s", restoreIndependentName, vol) - } - return m, true, nil -} - -// foreignRefsOf counts the refs to other volumes in image h of vol, resolved: -// the manifest segments name chunk refs too, so every segment key and every -// chunk ref inside is checked, as GC and usage resolve it. -func (c *Catalog) foreignRefsOf(ctx context.Context, vol string, h storage.ChunkHead) (int, error) { - if c.blobs == nil { - return 0, errors.New("chunkstore: restore independence needs the segment reader") - } - r, err := NewChunkRemote(c.f, c.blobs, path.Join(c.base, vol)) - if err != nil { - return 0, err - } - resolved, err := r.resolveManifest(ctx, h) - if err != nil { - return 0, remoteErr(err, "resolve gen %d of %s", h.Gen, vol) - } - return ForeignRefs(resolved, vol), nil -} diff --git a/seaweed-block/core/frontend/chunkstore/restore_lsn_test.go b/seaweed-block/core/frontend/chunkstore/restore_lsn_test.go deleted file mode 100644 index 16946ad401..0000000000 --- a/seaweed-block/core/frontend/chunkstore/restore_lsn_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package chunkstore - -import ( - "context" - "reflect" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func TestHEADRefusesLSNRegressionAcrossMove(t *testing.T) { - ctx := context.Background() - r := newTestRemote(t, newFakeFiler(), newFakeBlobs()) - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, head(1, "old", 42, nil)); err != nil { - t.Fatal(err) - } - before, _ := r.GetHead(ctx) - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(2, "new", 41, nil)); !isPrecondition(err) { - t.Fatalf("regressing takeover accepted: %v", err) - } - after, _ := r.GetHead(ctx) - if !reflect.DeepEqual(before, after) { - t.Fatal("refused HEAD changed") - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(2, "new", 42, nil)); err != nil { - t.Fatal(err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go deleted file mode 100644 index bcda46abf0..0000000000 --- a/seaweed-block/core/frontend/chunkstore/restore_test.go +++ /dev/null @@ -1,392 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "crypto/sha256" - "errors" - "fmt" - "path" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// restoreFixture: v1 with snapshot s1, restored into v2. -func restoreFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) { - t.Helper() - f, b, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil { - t.Fatal(err) - } - return f, b, c, h -} - -// ownAll re-uploads every qualified chunk of vol under vol's own keys and -// publishes a HEAD with no qualified ref (what the restore's batch cuts do). -func ownAll(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) storage.ChunkHead { - t.Helper() - ctx := context.Background() - r, err := NewChunkRemote(f, b, catBase+"/"+vol) - if err != nil { - t.Fatal(err) - } - h, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - // The batch cut's result in one step: every chunk under a fresh own key - // (chunks/e2/...), a new manifest, one HEAD CAS, intents dropped. - next := storage.ChunkHead{Epoch: 1, Holder: "h2", RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}} - for idx, ref := range h.Chunks { - data, err := r.Get(ctx, ref.Key) - if err != nil { - t.Fatal(err) - } - key := fmt.Sprintf("chunks/e2/c%d/k", idx) - if err := r.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} - } - next, intents, err := r.PrepareManifest(ctx, h, next, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) - if err != nil { - t.Fatal(err) - } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { - t.Fatal(err) - } - for _, id := range intents { - if err := r.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - got, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - return got -} - -// allQualified reports whether every chunk ref and segment key of h names another volume. -func allQualified(h storage.ChunkHead) bool { - for _, ref := range h.Chunks { - if !strings.HasPrefix(ref.Key, "@") { - return false - } - } - for _, seg := range h.Segments { - if !strings.HasPrefix(seg.Key, "@") { - return false - } - } - return len(h.Chunks) > 0 -} - -func TestRestore_RecordsOriginForkRecordAndQualifiedHead(t *testing.T) { - f, b, c, h := restoreFixture(t) - ctx := context.Background() - v, ok, err := c.ReadVolume(ctx, "v2") - if err != nil || !ok || v.Origin != OriginRestore || v.Fork == nil || v.Fork.Source != "v1" || v.Parent == nil { - t.Fatalf("restored VOLUME %+v ok=%v err=%v: want Origin restore with a fork record and Parent", v, ok, err) - } - r2, _ := NewChunkRemote(f, b, catBase+"/v2") - h2, _ := r2.GetHead(ctx) - if !allQualified(h2) || len(h2.Chunks) != len(h.Chunks) { - t.Fatalf("restored HEAD %v: want all %d chunk refs (and segments) qualified", h2.Chunks, len(h.Chunks)) - } - if _, err := c.EnsureVolume(ctx, "v2", v.Geometry); err != nil { - t.Fatalf("a restored volume attaches like a fork: %v", err) - } -} - -func TestRestore_ReplayAndOriginMismatchRefused(t *testing.T) { - _, _, c, _ := restoreFixture(t) - ctx := context.Background() - if r, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil || !r.Replayed { - t.Fatalf("restore replay: %+v %v", r, err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("a fork onto a restored volume with the same request id must be refused: %v", err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); err != nil { - t.Fatal(err) - } - if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("a restore onto a fork volume with the same request id must be refused: %v", err) - } -} - -func TestRestore_MarkIndependentOnlyWithoutQualifiedRefs(t *testing.T) { - f, b, c, _ := restoreFixture(t) - ctx := context.Background() - if _, err := c.MarkIndependent(ctx, "v2"); CodeOf(err) != CodeRestoreIncomplete { - t.Fatalf("marker while HEAD holds qualified refs: %v, want %s", err, CodeRestoreIncomplete) - } - if _, ok, err := c.ReadIndependence(ctx, "v2"); err != nil || ok { - t.Fatalf("no marker may exist after a refused mark: ok=%v err=%v", ok, err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "f1"}); err != nil { - t.Fatal(err) - } - if _, err := c.MarkIndependent(ctx, "v3"); CodeOf(err) != CodeNotRestore { - t.Fatalf("marker on a fork: %v, want %s", err, CodeNotRestore) - } - h := ownAll(t, f, b, "v2") - if ForeignRefs(h, "v2") != 0 { - t.Fatalf("fixture: %d foreign refs left", ForeignRefs(h, "v2")) - } - m, err := c.MarkIndependent(ctx, "v2") - if err != nil || m.HeadGen != h.Gen || m.VolumeID != "v2" { - t.Fatalf("marker: %+v %v (HEAD gen %d)", m, err, h.Gen) - } - if again, err := c.MarkIndependent(ctx, "v2"); err != nil || again != m { - t.Fatalf("marker is write-once (a replay returns it): %+v %v", again, err) - } - if got, ok, err := c.ReadIndependence(ctx, "v2"); err != nil || !ok || got != m { - t.Fatalf("read marker: %+v %v %v", got, ok, err) - } -} - -// Deleting the source mid-restore is a normal state for every reader of T's fork record. -func TestRestore_SourceGoneIsNormal(t *testing.T) { - f, b, c, _ := restoreFixture(t) - ctx := context.Background() - r2, _ := NewChunkRemote(f, b, catBase+"/v2") - h2, _ := r2.GetHead(ctx) - before := map[uint64][]byte{} - for idx, ref := range h2.Chunks { - data, err := r2.Get(ctx, ref.Key) - if err != nil { - t.Fatal(err) - } - before[idx] = data - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatalf("after T has its HEAD the source snapshot may go: %v", err) - } - detachHead(t, f, b, "v1") - if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { - t.Fatalf("delete the source volume: %v", err) - } - v, _, _ := c.ReadVolume(ctx, "v2") - if _, err := c.EnsureVolume(ctx, "v2", v.Geometry); err != nil { - t.Fatalf("attach of a restore whose source is gone must be normal: %v", err) - } - if r, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs1"}); err != nil || !r.Replayed { - t.Fatalf("replay of a restore whose source is gone: %+v %v", r, err) - } - for idx, ref := range h2.Chunks { - data, err := r2.Get(ctx, ref.Key) - if err != nil || sha256.Sum256(data) != sha256.Sum256(before[idx]) || sha256.Sum256(data) != ref.SHA256 { - t.Fatalf("chunk %d unreadable or changed after the source was deleted: %v", idx, err) - } - } - h := ownAll(t, f, b, "v2") - if _, err := c.MarkIndependent(ctx, "v2"); err != nil { - t.Fatalf("the restore finishes with its source gone: %v (HEAD gen %d)", err, h.Gen) - } -} - -// Load-bearing (the claim ends at the first HEAD): after the restore's HEAD exists, the -// source snapshot and the source volume may both go; GC must keep every chunk T's HEAD names (qualified -// refs resolve to the owner's bindings) until T's own batch cuts replace them. -func TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x31), 3: chunkBytes(0x33)}) - if _, e := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); e != nil { - t.Fatal(e) - } - if e := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); e != nil { - t.Fatal(e) - } - if _, e := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs"}); e != nil { - t.Fatal(e) - } - if _, e := c.DeleteSnapshot(ctx, "v1", "s1"); e != nil { - t.Fatalf("retention/delete may retire S once T has a HEAD: %v", e) - } - detachHead(t, f, b.fakeBlobs, "v1") - if _, e := c.DeleteVolume(ctx, "v1", nil); e != nil { - t.Fatalf("delete the source volume: %v", e) - } - r2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) - h2, e := r2.GetHead(ctx) - if e != nil { - t.Fatal(e) - } - for i := 0; i < 3; i++ { - if _, e := g.Run(ctx); e != nil { - t.Fatalf("gc: %v", e) - } - *now = now.Add(2 * time.Hour) - } - want := map[uint64][]byte{0: chunkBytes(0x31), 3: chunkBytes(0x33)} - for idx, ref := range h2.Chunks { - got, e := r2.Get(ctx, ref.Key) - if e != nil || !bytes.Equal(got, want[idx]) { - t.Fatalf("restored chunk %d lost after S and V were deleted and GC ran: %v", idx, e) - } - } -} - -// A restore whose HEAD is absent or an aborted tombstone never attaches, like a fork. -func TestRestore_WithoutLiveHeadNeverAttaches(t *testing.T) { - f, _, c, _ := catalogFixture(t) - ctx := context.Background() - v := VolumeInfo{Format: volumeFormat, VolumeID: "v9", Geometry: catGeo, Origin: OriginRestore, CreatedNs: 1, - Parent: &Parent{VolumeID: "v1", Snapshot: "s1", Gen: 1}, Fork: &ForkRecord{RequestID: "rq", Source: "v1", Snapshot: "s1"}} - e, err := volumeEntry(v, "rq") - if err != nil { - t.Fatal(err) - } - if err := f.CreateEntry(ctx, catBase+"/v9", e, true); err != nil { - t.Fatal(err) - } - if _, err := c.EnsureVolume(ctx, "v9", catGeo); CodeOf(err) != CodeForkIncomplete { - t.Fatalf("restore without a HEAD attached: %v, want %s", err, CodeForkIncomplete) - } - if _, err := c.AbortFork(ctx, "v9"); err != nil { - t.Fatalf("abort the unpublished restore (sweep): %v", err) - } - if _, err := c.EnsureVolume(ctx, "v9", catGeo); CodeOf(err) != CodeForkIncomplete { - t.Fatalf("restore with an aborted HEAD attached: %v, want %s", err, CodeForkIncomplete) - } - if _, err := c.MarkIndependent(ctx, "v9"); CodeOf(err) != CodeRestoreIncomplete { - t.Fatalf("marker on an aborted restore: %v, want %s", err, CodeRestoreIncomplete) - } -} - -// Snapshots of a restore are refused until it is independent. -func TestRestore_SnapshotsRefusedUntilIndependent(t *testing.T) { - f, b, c, _ := restoreFixture(t) - ctx := context.Background() - r2, _ := NewChunkRemote(f, b, catBase+"/v2") - h2, _ := r2.GetHead(ctx) - if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "early", RequestID: "e"}, h2); CodeOf(err) != CodeRestoreIncomplete { - t.Fatalf("snapshot of a restore in progress: %v, want %s", err, CodeRestoreIncomplete) - } - if _, ok, err := c.SnapshotReplay(ctx, "v2", SnapshotRequest{Name: "early", RequestID: "e"}); err != nil || ok { - t.Fatalf("a refused snapshot must leave nothing: ok=%v err=%v", ok, err) - } - h := ownAll(t, f, b, "v2") - if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "late", RequestID: "l"}, h); CodeOf(err) != CodeRestoreIncomplete { - t.Fatalf("own chunks but no marker yet: %v, want %s", err, CodeRestoreIncomplete) - } - if _, err := c.MarkIndependent(ctx, "v2"); err != nil { - t.Fatal(err) - } - s, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "late", RequestID: "l"}, h) - if err != nil { - t.Fatalf("snapshot after the marker: %v", err) - } - if ForeignRefs(s.Head(), "v2") != 0 { - t.Fatalf("a snapshot of an independent restore names %d foreign refs", ForeignRefs(s.Head(), "v2")) - } -} - -// hangingDeleteFiler blocks DeleteEntry until its ctx ends (or the test -// releases it). It reports whether that ctx carried a deadline and was live on -// entry, then how it ended. -type hangingDeleteFiler struct { - Filer - entered chan deleteEntry - ended chan error - release chan struct{} -} - -type deleteEntry struct { - hadDeadline bool - errAtEntry error -} - -func (h hangingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { - _, ok := ctx.Deadline() - h.entered <- deleteEntry{hadDeadline: ok, errAtEntry: ctx.Err()} - select { - case <-ctx.Done(): - h.ended <- ctx.Err() - return ctx.Err() - case <-h.release: - return errors.New("released by the test") - } -} - -// dropIntent outlives a cancelled caller, but one unresponsive delete must still be bounded. -func TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled(t *testing.T) { - old := dropIntentTimeout - dropIntentTimeout = 50 * time.Millisecond - t.Cleanup(func() { dropIntentTimeout = old }) - h := hangingDeleteFiler{Filer: newFakeFiler(), entered: make(chan deleteEntry, 1), ended: make(chan error, 1), release: make(chan struct{})} - c := &Catalog{f: h} - ctx, cancel := context.WithCancel(context.Background()) - cancel() - done := make(chan struct{}) - t.Cleanup(func() { // an unbounded delete (the failing case) is released and joined - close(h.release) - select { - case <-done: - case <-time.After(5 * time.Second): - t.Error("cleanup: dropIntent did not return") - } - }) - go func() { c.dropIntent(ctx, "/vols/v1", "op-1"); close(done) }() - select { - case e := <-h.entered: - if e.errAtEntry != nil { - t.Fatalf("the intent delete inherited the caller's cancellation: %v", e.errAtEntry) - } - if !e.hadDeadline { - t.Fatal("the intent delete ran without any deadline") - } - case <-time.After(5 * time.Second): - t.Fatal("dropIntent never reached the filer") - } - select { - case err := <-h.ended: - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("the intent delete ended with %v, want its own deadline (context.DeadlineExceeded)", err) - } - case <-time.After(5 * time.Second): - t.Fatal("the intent delete never ended: it is unbounded") - } - select { - case <-done: - case <-time.After(5 * time.Second): - t.Fatal("dropIntent did not return: the delete is unbounded") - } -} - -// A cut image saved before the marker still names the source's chunks: the -// marker must not let it become a snapshot. -func TestRestore_SnapshotOfAStalePreIndependenceImageRefused(t *testing.T) { - f, b, c, _ := restoreFixture(t) - ctx := context.Background() - r2, _ := NewChunkRemote(f, b, catBase+"/v2") - stale, _ := r2.GetHead(ctx) - h := ownAll(t, f, b, "v2") - if _, err := c.MarkIndependent(ctx, "v2"); err != nil { - t.Fatal(err) - } - req := SnapshotRequest{Name: "stale", RequestID: "s"} - if _, err := c.CreateSnapshot(ctx, "v2", req, stale); CodeOf(err) != CodeRestoreIncomplete { - t.Fatalf("stale foreign image after the marker: %v, want %s", err, CodeRestoreIncomplete) - } - if _, ok, err := c.SnapshotReplay(ctx, "v2", req); err != nil || ok { - t.Fatalf("a refused snapshot must leave nothing: ok=%v err=%v", ok, err) - } - if list, _, err := c.ListSnapshots(ctx, "v2", ListOptions{}); err != nil || len(list) != 0 { - t.Fatalf("snapshots after the refusal: %v %v", list, err) - } - if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "own", RequestID: "o"}, h); err != nil { - t.Fatalf("the own image must still be accepted: %v", err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/retain/retain.go b/seaweed-block/core/frontend/chunkstore/retain/retain.go new file mode 100644 index 0000000000..ce6bf0e314 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/retain/retain.go @@ -0,0 +1,176 @@ +// Package retain chooses which snapshots a retention policy deletes. It +// only selects names: the delete is the layout's snapshot transition for +// the automatic caller, which refuses a pinned snapshot or one a restore +// target depends on. Times are wall clock and decide policy only. +package retain + +import ( + "errors" + "fmt" + "sort" + "strconv" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// The retention classes and the schedule label. +const ( + + // LabelScheduleKeep, on a scheduled snapshot, is how many scheduled + // snapshots its schedule keeps (a decimal count). + LabelScheduleKeep = "swb.schedule.keep" + // DefaultScheduleKeep is the count kept when the newest scheduled + // snapshot carries no valid LabelScheduleKeep. + DefaultScheduleKeep = 7 + + DefaultKeepNewest = 10 + DefaultKeepYounger = time.Hour +) + +// ErrInvalidPolicy refuses a negative count or duration. +var ErrInvalidPolicy = errors.New("retain: invalid policy") + +// Policy is a volume's snapshot retention policy. +type Policy struct { + KeepNewest int `json:"keepNewest"` // keep the newest N unpinned snapshots + KeepYoungerNs int64 `json:"keepYoungerNs"` // keep every snapshot younger than this (ns) + KeepHourly int `json:"keepHourly"` // keep the newest snapshot of each of the last N hours + KeepDaily int `json:"keepDaily"` // keep the newest snapshot of each of the last N days + KeepWeekly int `json:"keepWeekly"` // keep the newest snapshot of each of the last N weeks +} + +// DefaultPolicy is the policy of a volume that never set one. +func DefaultPolicy() Policy { + return Policy{KeepNewest: DefaultKeepNewest, KeepYoungerNs: int64(DefaultKeepYounger)} +} + +// Validate refuses negative counts and durations. +func (p Policy) Validate() error { + if p.KeepNewest < 0 || p.KeepYoungerNs < 0 || p.KeepHourly < 0 || p.KeepDaily < 0 || p.KeepWeekly < 0 { + return fmt.Errorf("%w: %+v: counts and durations must not be negative", ErrInvalidPolicy, p) + } + return nil +} + +// Snapshot is one named snapshot as retention sees it. +type Snapshot struct { + Name string + CreatedNs int64 + Class string + ExpiresNs int64 + Labels map[string]string +} + +// Decision is one snapshot's fate under a policy. +type Decision struct { + Name string `json:"name"` + CreatedNs int64 `json:"createdNs"` + Class string `json:"class"` + Pinned bool `json:"pinned"` + Keep bool `json:"keep"` + Reasons []string `json:"reasons"` // why it is kept; "expired" when it goes +} + +// The reasons a snapshot is kept. +const ( + keepNewest = "newest" + keepPinned = "pinned" + keepYoung = "younger_than_policy" + keepHourly = "hourly" + keepDaily = "daily" + keepWeekly = "weekly" + keepScheduled = "scheduled_newest" + reasonExpired = "expired" +) + +// Plan decides, from one listing, which snapshots policy keeps at now. +// Unpinned snapshots are ranked newest first; equal creation times rank by +// name, so the plan is deterministic. +func Plan(p Policy, snaps []Snapshot, now time.Time) []Decision { + ordered := append([]Snapshot(nil), snaps...) + sort.SliceStable(ordered, func(i, j int) bool { + if ordered[i].CreatedNs != ordered[j].CreatedNs { + return ordered[i].CreatedNs > ordered[j].CreatedNs + } + return ordered[i].Name < ordered[j].Name + }) + nowNs := now.UnixNano() + out := make([]Decision, len(ordered)) + unpinned, scheduled := 0, 0 + scheduleKeep := -1 // read from the newest scheduled snapshot + windows := map[string]bool{} + for i, s := range ordered { + // pinned at now exactly as the kernel judges it (the delete refuses the same snapshots) + pinned := layout.SnapshotMeta{Class: s.Class, ExpiresNs: s.ExpiresNs}.PinnedAt(nowNs) + d := Decision{Name: s.Name, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: pinned} + if s.Class == layout.ClassScheduled { + // Every scheduled snapshot, pinned or not, is planned here and + // ranked among its class; a pinned one is also kept by its pin. + if scheduleKeep < 0 { + scheduleKeep = scheduleKeepOf(s) + } + if pinned { + d.Reasons = append(d.Reasons, keepPinned) + } + if scheduled < scheduleKeep { + d.Reasons = append(d.Reasons, keepScheduled) + } + scheduled++ + d.Keep = len(d.Reasons) > 0 + if !d.Keep { + d.Reasons = []string{reasonExpired} + } + out[i] = d + continue + } + if pinned { + d.Reasons = append(d.Reasons, keepPinned) + } else { + if unpinned < p.KeepNewest { + d.Reasons = append(d.Reasons, keepNewest) + } + unpinned++ + } + age := time.Duration(nowNs - s.CreatedNs) + if age < time.Duration(p.KeepYoungerNs) { + d.Reasons = append(d.Reasons, keepYoung) + } + for _, lk := range []struct { + reason string + period time.Duration + count int + }{ + {keepHourly, time.Hour, p.KeepHourly}, + {keepDaily, 24 * time.Hour, p.KeepDaily}, + {keepWeekly, 7 * 24 * time.Hour, p.KeepWeekly}, + } { + if lk.count <= 0 || age < 0 { + continue + } + k := int64(age / lk.period) // the rolling window holding this age + if k >= int64(lk.count) { + continue + } + key := fmt.Sprintf("%s/%d", lk.reason, k) + if !windows[key] { // ordered newest first: the first seen is the window's newest + windows[key] = true + d.Reasons = append(d.Reasons, lk.reason) + } + } + d.Keep = len(d.Reasons) > 0 + if !d.Keep { + d.Reasons = []string{reasonExpired} + } + out[i] = d + } + return out +} + +// scheduleKeepOf is the count a scheduled snapshot's schedule keeps. +func scheduleKeepOf(s Snapshot) int { + if n, err := strconv.Atoi(s.Labels[LabelScheduleKeep]); err == nil && n > 0 { + return n + } + return DefaultScheduleKeep +} diff --git a/seaweed-block/core/frontend/chunkstore/retain/retain_test.go b/seaweed-block/core/frontend/chunkstore/retain/retain_test.go new file mode 100644 index 0000000000..9a74cd486f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/retain/retain_test.go @@ -0,0 +1,178 @@ +package retain + +import ( + "fmt" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +var retBase = time.Unix(1_000_000, 0) + +func snapAt(name string, at time.Time, class string, expiresAt time.Time, labels map[string]string) Snapshot { + s := Snapshot{Name: name, CreatedNs: at.UnixNano(), Class: class, Labels: labels} + if !expiresAt.IsZero() { + s.ExpiresNs = expiresAt.UnixNano() + } + return s +} + +func kept(ds []Decision) map[string][]string { + out := map[string][]string{} + for _, d := range ds { + if d.Keep { + out[d.Name] = d.Reasons + } + } + return out +} + +func noYoung() Policy { return Policy{KeepNewest: 10} } + +// Newest N unpinned are kept; equal creation times rank by name. +func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { + now := retBase.Add(48 * time.Hour) + var snaps []Snapshot + for i := 0; i < 15; i++ { + snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), retBase.Add(time.Duration(i)*time.Minute), layout.ClassSemantic, time.Time{}, nil)) + } + k := kept(Plan(noYoung(), snaps, now)) + if len(k) != 10 { + t.Fatalf("kept %d, want 10: %v", len(k), k) + } + for i := 5; i < 15; i++ { + if _, ok := k[fmt.Sprintf("s%02d", i)]; !ok { + t.Fatalf("newest s%02d not kept: %v", i, k) + } + } + tie := []Snapshot{snapAt("b", retBase, "", time.Time{}, nil), snapAt("a", retBase, "", time.Time{}, nil)} + if k := kept(Plan(Policy{KeepNewest: 1}, tie, now)); len(k) != 1 || k["a"] == nil { + t.Fatalf("tie: kept %v, want only a (name order)", k) + } +} + +// Pinned exactly as the kernel judges it (layout.SnapshotMeta.PinnedAt, the +// rule its automatic delete refuses by): class pinned always, any other +// class only before its ExpiresNs. Never expired by count or age while +// pinned. Semantic and labeled snapshots are not exempt. +func TestPlanRetention_PinnedSemanticAndLabels(t *testing.T) { + now := retBase.Add(48 * time.Hour) + snaps := []Snapshot{ + snapAt("pinned-old", retBase, layout.ClassPinned, time.Time{}, nil), + snapAt("pinned-by-expiry", retBase, "", now.Add(time.Hour), nil), + snapAt("pinned-class-expiry-passed", retBase, layout.ClassPinned, now.Add(-time.Second), nil), + snapAt("expiry-passed", retBase, "", now.Add(-time.Second), nil), + snapAt("semantic-old", retBase, layout.ClassSemantic, time.Time{}, nil), + snapAt("labeled-old", retBase, "", time.Time{}, map[string]string{"agent.step": "npm-ci"}), + } + k := kept(Plan(Policy{}, snaps, now)) + if len(k) != 3 || k["pinned-old"] == nil || k["pinned-by-expiry"] == nil || k["pinned-class-expiry-passed"] == nil { + t.Fatalf("kept %v; want exactly pinned-old, pinned-by-expiry and pinned-class-expiry-passed", k) + } +} + +// Younger than T is kept beyond N; a creation time in the future (clock +// skew) counts as young. +func TestPlanRetention_YoungAndClockSkew(t *testing.T) { + now := retBase.Add(48 * time.Hour) + p := Policy{KeepNewest: 0, KeepYoungerNs: int64(time.Hour)} + snaps := []Snapshot{ + snapAt("young", now.Add(-30*time.Minute), layout.ClassSemantic, time.Time{}, nil), + snapAt("future", now.Add(10*time.Minute), layout.ClassSemantic, time.Time{}, nil), + snapAt("old", now.Add(-2*time.Hour), layout.ClassSemantic, time.Time{}, nil), + } + k := kept(Plan(p, snaps, now)) + if len(k) != 2 || k["young"] == nil || k["future"] == nil { + t.Fatalf("kept %v; want young and future", k) + } +} + +// Log-spaced keeps: the newest snapshot of each of the last H hours. +func TestPlanRetention_HourlyBuckets(t *testing.T) { + now := retBase.Add(48*time.Hour + 59*time.Minute) // late in an hour + var snaps []Snapshot + for i := 0; i < 12; i++ { // every 30 min over the last 6 hours + snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), now.Add(-time.Duration(i)*30*time.Minute), layout.ClassSemantic, time.Time{}, nil)) + } + k := kept(Plan(Policy{KeepHourly: 3}, snaps, now)) + if len(k) != 3 { + t.Fatalf("kept %d, want 3 (one per hour for the last 3 hours): %v", len(k), k) + } + for _, reasons := range k { + if len(reasons) != 1 || reasons[0] != keepHourly { + t.Fatalf("reasons %v; want hourly", reasons) + } + } +} + +// An agent that checkpoints every step stays bounded: one semantic +// snapshot a minute for a day keeps at most N + T/step + hourly buckets. +func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) { + p := Policy{KeepNewest: DefaultKeepNewest, KeepYoungerNs: int64(DefaultKeepYounger), KeepHourly: 24} + start := retBase + var snaps []Snapshot + for i := 0; i < 24*60; i++ { + snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), layout.ClassSemantic, time.Time{}, map[string]string{"agent.step": fmt.Sprint(i)})) + } + now := start.Add(24 * time.Hour) + bound := p.KeepNewest + int(DefaultKeepYounger/time.Minute) + p.KeepHourly + if k := kept(Plan(p, snaps, now)); len(k) > bound { + t.Fatalf("kept %d of %d step checkpoints; want at most %d", len(k), len(snaps), bound) + } + // The bound holds however long the agent runs. + for i := 24 * 60; i < 7*24*60; i++ { + snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), layout.ClassSemantic, time.Time{}, nil)) + } + if k := kept(Plan(p, snaps, start.Add(7*24*time.Hour))); len(k) > bound { + t.Fatalf("after a week: kept %d; want at most %d", len(k), bound) + } +} + +// Scheduled snapshots form their own class: retention keeps the newest K +// of them, K from the newest one's LabelScheduleKeep, and they neither +// count against KeepNewest nor get the age keeps; other snapshots are +// planned as before. +func TestPlanRetention_ScheduledClassKeepsItsOwnNewest(t *testing.T) { + now := retBase.Add(30 * 24 * time.Hour) + keep3 := map[string]string{LabelScheduleKeep: "3"} + var snaps []Snapshot + for d := 0; d < 6; d++ { // one scheduled snapshot a day, the newest first at now-1h + snaps = append(snaps, snapAt(fmt.Sprintf("sched-%d", d), now.Add(-time.Hour-time.Duration(d)*24*time.Hour), layout.ClassScheduled, time.Time{}, keep3)) + } + snaps = append(snaps, + snapAt("manual-new", now.Add(-2*time.Hour), "", time.Time{}, nil), + snapAt("manual-old", now.Add(-20*24*time.Hour), "", time.Time{}, nil)) + k := kept(Plan(Policy{KeepNewest: 2, KeepYoungerNs: int64(30 * 24 * time.Hour)}, snaps, now)) + for _, name := range []string{"sched-0", "sched-1", "sched-2", "manual-new", "manual-old"} { + if k[name] == nil { + t.Fatalf("kept %v; %s missing", k, name) + } + } + if len(k) != 5 { + t.Fatalf("kept %v; want the 3 newest scheduled and both manual (KeepNewest 2 is theirs alone)", k) + } + // Without a valid label the default count applies. + snaps[0].Labels = nil + if k := kept(Plan(Policy{}, snaps[:6], now)); len(k) != 6 { + t.Fatalf("kept %v with no label on the newest; want min(6, DefaultScheduleKeep)", k) + } +} + +// A pinned scheduled snapshot stays in its class: it is kept by its pin, +// ranks among the scheduled ones (its label sets K when it is the newest), +// and takes no log-spaced window from a manual snapshot. +func TestPlanRetention_PinnedScheduledStaysInItsClass(t *testing.T) { + now := retBase.Add(30 * 24 * time.Hour) + newest := snapAt("sched-pinned", now.Add(-10*time.Minute), layout.ClassScheduled, now.Add(24*time.Hour), map[string]string{LabelScheduleKeep: "2"}) + snaps := []Snapshot{ + newest, + snapAt("sched-1", now.Add(-24*time.Hour), layout.ClassScheduled, time.Time{}, map[string]string{LabelScheduleKeep: "9"}), + snapAt("sched-2", now.Add(-48*time.Hour), layout.ClassScheduled, time.Time{}, map[string]string{LabelScheduleKeep: "9"}), + snapAt("manual", now.Add(-20*time.Minute), "", time.Time{}, nil), // same hourly window as the pinned scheduled one + } + k := kept(Plan(Policy{KeepHourly: 1}, snaps, now)) + if len(k) != 3 || k["sched-pinned"] == nil || k["sched-1"] == nil || k["manual"] == nil { + t.Fatalf("kept %v; want sched-pinned (pin, K=2 from its label), sched-1 (second newest scheduled) and manual (its hourly window)", k) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/retain_b.go b/seaweed-block/core/frontend/chunkstore/retain_b.go new file mode 100644 index 0000000000..c67150eb0f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/retain_b.go @@ -0,0 +1,153 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "strconv" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain" +) + +// retentionName is the per-volume RETENTION entry beside VOLUME: the +// operator's retention policy, changed by one conditional update, read +// only by retain. Absent is the default policy. +const retentionName = "RETENTION" + +// ReadRetention returns the volume's policy and the entry's generation (0 +// and the default policy when it was never set). +func (s *LayoutStore) ReadRetention(ctx context.Context) (retain.Policy, uint64, error) { + e, err := s.f.LookupEntry(ctx, s.root, retentionName) + if errors.Is(err, ErrNotFound) { + return retain.DefaultPolicy(), 0, nil + } + if err != nil { + return retain.Policy{}, 0, err + } + gen, err := strconv.ParseUint(string(e.Extended[layoutGen]), 10, 64) + if err != nil || gen == 0 || string(e.Extended[layoutVolume]) != s.id.String() { + return retain.Policy{}, 0, fmt.Errorf("%w: invalid RETENTION entry", layout.ErrCorrupt) + } + var p retain.Policy + dec := json.NewDecoder(bytes.NewReader(e.Content)) + dec.DisallowUnknownFields() + if err := dec.Decode(&p); err != nil { + return retain.Policy{}, 0, fmt.Errorf("%w: RETENTION: %v", layout.ErrCorrupt, err) + } + return p, gen, p.Validate() +} + +// WriteRetention replaces the policy if the entry is still at +// expectedGen (0: not yet set); layout.ErrPrecondition otherwise. +func (s *LayoutStore) WriteRetention(ctx context.Context, expectedGen uint64, p retain.Policy) error { + if err := p.Validate(); err != nil { + return err + } + raw, err := json.Marshal(p) + if err != nil { + return err + } + e := layoutEntry(retentionName, raw) + e.Extended = map[string][]byte{layoutKind: []byte("retention"), layoutGen: []byte(strconv.FormatUint(expectedGen+1, 10)), layoutVolume: []byte(s.id.String())} + if expectedGen == 0 { + err = s.f.CreateEntry(ctx, s.root, e, true) + if errors.Is(err, ErrExists) { + return layout.ErrPrecondition + } + return err + } + err = s.f.UpdateEntry(ctx, s.root, e, map[string][]byte{layoutGen: []byte(strconv.FormatUint(expectedGen, 10)), layoutVolume: []byte(s.id.String())}) + if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { + return layout.ErrPrecondition + } + return err +} + +// SetRetention stores the volume's policy (replacing whatever is there, +// conditional on the generation it read). +func (c *BCatalog) SetRetention(ctx context.Context, v VolumeRef, p retain.Policy) error { + s, err := c.Store(v) + if err != nil { + return err + } + if _, found, err := s.ReadHead(ctx); err != nil { + return err + } else if !found { + return layout.ErrHeadAbsent + } + _, gen, err := s.ReadRetention(ctx) + if err != nil && !errors.Is(err, retain.ErrInvalidPolicy) { + return err + } + return s.WriteRetention(ctx, gen, p) +} + +// ReadRetention returns the volume's policy (the default when never set). +func (c *BCatalog) ReadRetention(ctx context.Context, v VolumeRef) (retain.Policy, error) { + s, err := c.Store(v) + if err != nil { + return retain.Policy{}, err + } + p, _, err := s.ReadRetention(ctx) + return p, err +} + +// RetainResult is a retention pass: every decision, and what it deleted. +type RetainResult struct { + Policy retain.Policy `json:"policy"` + Decisions []retain.Decision `json:"decisions"` + Deleted []string `json:"deleted"` + // Refused are names the plan would delete that the snapshot delete + // refused: pinned on HEAD, or a restore target depends on them. + Refused []string `json:"refused,omitempty"` + DryRun bool `json:"dryRun,omitempty"` +} + +// Retain applies the volume's policy at now: it plans over HEAD's +// snapshots and deletes each expired one by the automatic snapshot delete, +// which refuses a pinned snapshot or one with dependents. The policy is +// advisory: a change made during a pass applies from the next one. +func (c *BCatalog) Retain(ctx context.Context, v VolumeRef, now time.Time, dryRun bool) (RetainResult, error) { + s, err := c.Store(v) + if err != nil { + return RetainResult{}, err + } + h, found, err := s.ReadHead(ctx) + if err != nil { + return RetainResult{}, err + } + if !found { + return RetainResult{}, layout.ErrHeadAbsent + } + p, _, err := s.ReadRetention(ctx) + if err != nil { + return RetainResult{}, err + } + snaps := make([]retain.Snapshot, 0, len(h.Snapshots)) + for n, sn := range h.Snapshots { + snaps = append(snaps, retain.Snapshot{Name: n, CreatedNs: sn.Meta.CreatedNs, Class: sn.Meta.Class, ExpiresNs: sn.Meta.ExpiresNs, Labels: sn.Meta.Labels}) + } + res := RetainResult{Policy: p, Decisions: retain.Plan(p, snaps, now), Deleted: []string{}, DryRun: dryRun} + for _, d := range res.Decisions { + if d.Keep { + continue + } + if dryRun { + res.Deleted = append(res.Deleted, d.Name) + continue + } + if _, err := layout.RunRetireSnapshot(ctx, s, d.Name, now.UnixNano()); err != nil { + if errors.Is(err, layout.ErrPinned) || errors.Is(err, layout.ErrHasDependents) { + res.Refused = append(res.Refused, d.Name) + continue + } + return res, err + } + res.Deleted = append(res.Deleted, d.Name) + } + return res, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/retain_b_test.go b/seaweed-block/core/frontend/chunkstore/retain_b_test.go new file mode 100644 index 0000000000..35a0e7e9a1 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/retain_b_test.go @@ -0,0 +1,163 @@ +package chunkstore + +import ( + "context" + "errors" + "sort" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain" +) + +// snapshotWithMeta names v's current image again as snapshot name with +// the given retention facts (a snapshot transaction with no new chunks). +func snapshotWithMeta(t *testing.T, c *BCatalog, v VolumeRef, name string, meta layout.SnapshotMeta, session string, position uint64) { + t.Helper() + ctx := context.Background() + s, _, err := c.open(v) + if err != nil { + t.Fatal(err) + } + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + h, _, _ := s.ReadHead(ctx) + r, _ := layout.NewReader(c.base, v.Dir(), s.Fetch) + img, err := r.Open(ctx, *h.Current) + if err != nil { + t.Fatal(err) + } + ref, _, _ := img.Resolve(ctx, 1) + m := map[uint64]layout.Ref{1: ref} + if _, err := layout.RunBegin(ctx, s, me, session); err != nil { + t.Fatal(err) + } + root, segs, _ := layout.Build(m) + rn, rb, _ := layout.NameRoot(root) + objs := map[string][]byte{rn.Path(): rb} + for n, b := range segs { + objs[n.Path()] = b + } + for rel, b := range objs { + if err := layout.EnsureObject(ctx, s, rel, b, session); err != nil { + t.Fatal(err) + } + } + if _, err := layout.RunCommit(ctx, s, s, v.Name, me, layout.CommitRequest{Session: session, Prev: m, Next: m, Position: position, Snapshot: name, Meta: meta}); err != nil { + t.Fatal(err) + } +} + +func names(ns []string) string { + out := append([]string(nil), ns...) + sort.Strings(out) + return strings.Join(out, ",") +} + +// Retention on the layout keeps the old behaviour: the policy from the +// volume's RETENTION entry (default when absent) over HEAD's snapshot +// facts; pinned and unexpired snapshots kept; the scheduled class ranked +// by its own keep label; a snapshot a restore target depends on refused by +// the delete and reported; --dry-run writes nothing. +func TestBCatalog_RetainKeepsTheOldBehaviour(t *testing.T) { + ctx := context.Background() + c, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + v := newRef(t, "v") + if _, err := c.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + commitSnapshot(t, c, v, []byte("data"), "") + now := time.Unix(10_000_000, 0) + at := func(h int) int64 { return now.Add(-time.Duration(h) * time.Hour).UnixNano() } + facts := []struct { + name string + meta layout.SnapshotMeta + }{ + {"a1", layout.SnapshotMeta{CreatedNs: at(1), Class: layout.ClassSemantic}}, + {"a2", layout.SnapshotMeta{CreatedNs: at(2), Class: layout.ClassSemantic}}, + {"a3", layout.SnapshotMeta{CreatedNs: at(3), Class: layout.ClassSemantic}}, + {"a4", layout.SnapshotMeta{CreatedNs: at(4), Class: layout.ClassSemantic}}, + {"pin", layout.SnapshotMeta{CreatedNs: at(30), Class: layout.ClassPinned}}, + {"hold", layout.SnapshotMeta{CreatedNs: at(31), ExpiresNs: now.Add(time.Hour).UnixNano()}}, + {"lapsed", layout.SnapshotMeta{CreatedNs: at(32), ExpiresNs: now.Add(-time.Hour).UnixNano()}}, + {"s1", layout.SnapshotMeta{CreatedNs: at(5), Class: layout.ClassScheduled, Labels: map[string]string{retain.LabelScheduleKeep: "1"}}}, + {"s2", layout.SnapshotMeta{CreatedNs: at(6), Class: layout.ClassScheduled}}, + } + for i, f := range facts { + snapshotWithMeta(t, c, v, f.name, f.meta, "m"+f.name, uint64(i+2)) + } + if p, err := c.ReadRetention(ctx, v); err != nil || p != retain.DefaultPolicy() { + t.Fatalf("policy never set: %+v %v; want the default", p, err) + } + if err := c.SetRetention(ctx, v, retain.Policy{KeepNewest: 2}); err != nil { + t.Fatal(err) + } + // a4 is restored from: the plan expires it, the delete refuses it. + if _, err := c.Restore(ctx, v, "a4", newRef(t, "t")); err != nil { + t.Fatal(err) + } + dry, err := c.Retain(ctx, v, now, true) + if err != nil { + t.Fatal(err) + } + want := "a3,a4,lapsed,s2" + if names(dry.Deleted) != want { + t.Fatalf("dry run would delete %s; want %s (decisions %+v)", names(dry.Deleted), want, dry.Decisions) + } + if h, _, _ := c.ReadHead(ctx, v); len(h.Snapshots) != len(facts) { + t.Fatalf("a dry run deleted: %d snapshots left", len(h.Snapshots)) + } + got, err := c.Retain(ctx, v, now, false) + if err != nil { + t.Fatal(err) + } + if names(got.Deleted) != "a3,lapsed,s2" || names(got.Refused) != "a4" { + t.Fatalf("retain deleted %s refused %s; want a3,lapsed,s2 and a4", names(got.Deleted), names(got.Refused)) + } + h, _, _ := c.ReadHead(ctx, v) + var left []string + for n := range h.Snapshots { + left = append(left, n) + } + if names(left) != "a1,a2,a4,hold,pin,s1" { + t.Fatalf("left %s", names(left)) + } +} + +// The policy write is conditional on the generation read: of two writers +// that read the same generation, the second is refused. +func TestBCatalog_RetentionPolicyIsConditional(t *testing.T) { + ctx := context.Background() + c, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + v := newRef(t, "v") + if _, err := c.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + s, _ := c.Store(v) + _, gen, err := s.ReadRetention(ctx) + if err != nil || gen != 0 { + t.Fatalf("unset policy: gen %d %v", gen, err) + } + if err := s.WriteRetention(ctx, gen, retain.Policy{KeepNewest: 3}); err != nil { + t.Fatal(err) + } + if err := s.WriteRetention(ctx, gen, retain.Policy{KeepNewest: 4}); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("a second writer at the same generation: %v; want ErrPrecondition", err) + } + if p, gen2, err := s.ReadRetention(ctx); err != nil || p.KeepNewest != 3 || gen2 != 1 { + t.Fatalf("policy %+v gen %d %v", p, gen2, err) + } + if err := s.WriteRetention(ctx, 1, retain.Policy{KeepNewest: -1}); !errors.Is(err, retain.ErrInvalidPolicy) { + t.Fatalf("negative policy: %v", err) + } + if err := c.SetRetention(ctx, newRef(t, "never"), retain.DefaultPolicy()); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("policy of a volume never created: %v", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go deleted file mode 100644 index 1d18b6298e..0000000000 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ /dev/null @@ -1,533 +0,0 @@ -package chunkstore - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "path" - "sort" - "strconv" - "time" - - "google.golang.org/protobuf/proto" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" -) - -// Snapshot retention. -// -// A snapshot has a class, stored with it: -// - "semantic": an automatic checkpoint (e.g. an agent's per-step -// checkpoint). Governed by count, age and the log-spaced keeps. -// - "pinned": an explicit keep. It is never expired by count or age, -// only by its own ExpiresAtNs or an explicit delete. A snapshot with -// ExpiresAtNs set is pinned whatever its class. -// - "scheduled": a scheduled snapshot. Retention keeps the newest K of -// this class, where K is the LabelScheduleKeep of the newest one -// (DefaultScheduleKeep when absent). -// They are not counted against KeepNewest, and the age and log-spaced -// keeps do not apply to them, so other snapshots are unaffected. -// - "" (snapshots made before classes existed): treated as unpinned. -// -// The policy is stored on the VOLUME entry. Retain keeps -// -// newest KeepNewest unpinned -// + every pinned snapshot not yet past its ExpiresAtNs -// + every snapshot younger than KeepYounger (a creation time in the -// future, from clock skew, counts as young) -// + the log-spaced keeps (below) -// -// and deletes every other snapshot. A pinned snapshot past its ExpiresAtNs -// is treated as unpinned. GC reclaims the chunks. -// -// Log-spaced keeps use rolling windows anchored at now: window k of a -// period P holds the snapshots whose age is in [k*P, (k+1)*P). For -// KeepHourly = H, the newest snapshot of each of windows 0..H-1 is kept -// (likewise daily and weekly). So at 10:30 with KeepHourly = 1 only the -// newest snapshot of 09:30..10:30 is kept, not one per clock hour. -// -// Deletion is bound to the exact attempt planned (review of #142): the -// attempt's own entry is marked deleting conditionally, and the name -// record is removed only while it still names that attempt, so a -// same-name replacement made after planning is never touched. -// -// Forks and restores do not hold their parent (INV-SNAP-DELETE-ANY-ORDER-001). -// A snapshot is deleted by retention or DeleteSnapshot whatever forks read -// it: a fork reads the parent after taking its deadline start and publishes -// its HEAD only before readAt + deadline, and GC keeps a deleted attempt -// rooted for its grace, which exceeds deadline + clock skew + CAS apply -// bound (NewCollector). A fork that reads after the delete mark gets -// snapshot_deleting or snapshot_not_found, also on a retry. A claims -// xattr left by an older version is ignored. -// -// A pass stopped after a mark (e.g. a lost response) leaves the attempt -// deleting with its name still held; the next pass (and its dry run) lists -// it and frees the name. - -const ( - SnapshotClassSemantic = "semantic" - SnapshotClassPinned = "pinned" - SnapshotClassScheduled = "scheduled" - - // LabelScheduleKeep, on a scheduled snapshot, is how many scheduled - // snapshots its schedule keeps (a decimal count). - LabelScheduleKeep = "swb.schedule.keep" - // DefaultScheduleKeep is the count kept when the newest scheduled - // snapshot carries no valid LabelScheduleKeep. - DefaultScheduleKeep = 7 - - CodeInvalidClass = "invalid_class" - CodeInvalidPolicy = "invalid_policy" - - DefaultKeepNewest = 10 - DefaultKeepYounger = time.Hour - - extRetention = "retention" - extRetentionRev = "retention_rev" -) - -// ValidateSnapshotClass refuses a class other than "", "semantic", -// "pinned" and "scheduled" (invalid_class). -func ValidateSnapshotClass(class string) error { - switch class { - case "", SnapshotClassSemantic, SnapshotClassPinned, SnapshotClassScheduled: - return nil - } - return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q, %q or %q", class, SnapshotClassSemantic, SnapshotClassPinned, SnapshotClassScheduled) -} - -// Pinned reports whether the snapshot is an explicit keep. -func (s SnapshotInfo) Pinned() bool { - return s.Class == SnapshotClassPinned || s.ExpiresAtNs > 0 -} - -// RetentionPolicy is a volume's snapshot retention policy. -type RetentionPolicy struct { - KeepNewest int `json:"keepNewest"` // keep the newest N unpinned snapshots - KeepYoungerNs int64 `json:"keepYoungerNs"` // keep every snapshot younger than this (ns) - KeepHourly int `json:"keepHourly"` // keep the newest snapshot of each of the last N hours - KeepDaily int `json:"keepDaily"` // keep the newest snapshot of each of the last N days - KeepWeekly int `json:"keepWeekly"` // keep the newest snapshot of each of the last N weeks -} - -// DefaultRetentionPolicy is the policy of a volume that never set one. -func DefaultRetentionPolicy() RetentionPolicy { - return RetentionPolicy{KeepNewest: DefaultKeepNewest, KeepYoungerNs: int64(DefaultKeepYounger)} -} - -func (p RetentionPolicy) validate() error { - if p.KeepNewest < 0 || p.KeepYoungerNs < 0 || p.KeepHourly < 0 || p.KeepDaily < 0 || p.KeepWeekly < 0 { - return catErr(CodeInvalidPolicy, false, nil, "retention policy %+v: counts and durations must not be negative", p) - } - return nil -} - -// ReadRetentionPolicy returns vol's policy; set is false (and the policy -// is DefaultRetentionPolicy) when none was ever set. -func (c *Catalog) ReadRetentionPolicy(ctx context.Context, vol string) (RetentionPolicy, bool, error) { - e, _, err := c.volumeEntry(ctx, vol) - if err != nil { - return RetentionPolicy{}, false, err - } - return decodeRetention(e) -} - -func decodeRetention(e *filerpb.Entry) (RetentionPolicy, bool, error) { - raw := e.Extended[extRetention] - if len(raw) == 0 { - return DefaultRetentionPolicy(), false, nil - } - var p RetentionPolicy - if err := json.Unmarshal(raw, &p); err != nil { - return RetentionPolicy{}, false, catErr(CodeInvalidPolicy, false, err, "stored retention policy is unreadable") - } - return p, true, nil -} - -// volumeEntry reads vol's VOLUME entry; a volume without one is -// not_chunk_volume. -func (c *Catalog) volumeEntry(ctx context.Context, vol string) (*filerpb.Entry, string, error) { - root, err := c.volRoot(vol) - if err != nil { - return nil, "", err - } - e, err := c.f.LookupEntry(ctx, root, volumeName) - if errors.Is(err, ErrNotFound) { - return nil, "", catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol) - } - if err != nil { - return nil, "", remoteErr(err, "read VOLUME of %s", vol) - } - return e, root, nil -} - -// SetRetentionPolicy stores p on vol's VOLUME entry. Only the policy's -// extended attributes change; the volume document is untouched. The update -// is conditional on the policy revision read, so of two concurrent setters -// one wins and the other gets a retryable remote error. -func (c *Catalog) SetRetentionPolicy(ctx context.Context, vol string, p RetentionPolicy) error { - if err := p.validate(); err != nil { - return err - } - e, root, err := c.volumeEntry(ctx, vol) - if err != nil { - return err - } - rev := string(e.Extended[extRetentionRev]) - n, _ := strconv.ParseUint(rev, 10, 64) - body, err := json.Marshal(p) - if err != nil { - return err - } - next := proto.Clone(e).(*filerpb.Entry) - if next.Extended == nil { - next.Extended = map[string][]byte{} - } - next.Extended[extRetention] = body - next.Extended[extRetentionRev] = []byte(strconv.FormatUint(n+1, 10)) - if err := c.f.UpdateEntry(ctx, root, next, map[string][]byte{extRetentionRev: []byte(rev)}); err != nil { - return remoteErr(err, "set the retention policy of %s", vol) - } - return nil -} - -// RetentionDecision is one snapshot's fate under a policy. -type RetentionDecision struct { - Name string `json:"name"` - Attempt string `json:"attempt"` - CreatedNs int64 `json:"createdNs"` - Class string `json:"class"` - Pinned bool `json:"pinned"` - Keep bool `json:"keep"` - Reasons []string `json:"reasons"` // why it is kept; "expired" when it goes -} - -// The reasons a snapshot is kept. -const ( - keepNewest = "newest" - keepPinned = "pinned" - keepYoung = "younger_than_policy" - keepHourly = "hourly" - keepDaily = "daily" - keepWeekly = "weekly" - keepScheduled = "scheduled_newest" - reasonExpired = "expired" -) - -// planRetention decides, from one listing, which snapshots policy keeps at -// now. Unpinned snapshots -// are ranked newest first; equal creation times rank by name, so the plan -// is deterministic. -func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []RetentionDecision { - ordered := append([]SnapshotInfo(nil), snaps...) - sort.SliceStable(ordered, func(i, j int) bool { - if ordered[i].CreatedNs != ordered[j].CreatedNs { - return ordered[i].CreatedNs > ordered[j].CreatedNs - } - return ordered[i].Name < ordered[j].Name - }) - nowNs := now.UnixNano() - out := make([]RetentionDecision, len(ordered)) - unpinned, scheduled := 0, 0 - scheduleKeep := -1 // read from the newest scheduled snapshot - windows := map[string]bool{} - for i, s := range ordered { - pinned := s.Pinned() && (s.ExpiresAtNs == 0 || nowNs < s.ExpiresAtNs) - d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: pinned} - if s.Class == SnapshotClassScheduled { - // Every scheduled snapshot, pinned or not, is planned here and - // ranked among its class; a pinned one is also kept by its pin. - if scheduleKeep < 0 { - scheduleKeep = scheduleKeepOf(s) - } - if pinned { - d.Reasons = append(d.Reasons, keepPinned) - } - if scheduled < scheduleKeep { - d.Reasons = append(d.Reasons, keepScheduled) - } - scheduled++ - d.Keep = len(d.Reasons) > 0 - if !d.Keep { - d.Reasons = []string{reasonExpired} - } - out[i] = d - continue - } - if pinned { - d.Reasons = append(d.Reasons, keepPinned) - } else { - if unpinned < p.KeepNewest { - d.Reasons = append(d.Reasons, keepNewest) - } - unpinned++ - } - age := time.Duration(nowNs - s.CreatedNs) - if age < time.Duration(p.KeepYoungerNs) { - d.Reasons = append(d.Reasons, keepYoung) - } - for _, lk := range []struct { - reason string - period time.Duration - count int - }{ - {keepHourly, time.Hour, p.KeepHourly}, - {keepDaily, 24 * time.Hour, p.KeepDaily}, - {keepWeekly, 7 * 24 * time.Hour, p.KeepWeekly}, - } { - if lk.count <= 0 || age < 0 { - continue - } - k := int64(age / lk.period) // the rolling window holding this age - if k >= int64(lk.count) { - continue - } - key := fmt.Sprintf("%s/%d", lk.reason, k) - if !windows[key] { // ordered newest first: the first seen is the window's newest - windows[key] = true - d.Reasons = append(d.Reasons, lk.reason) - } - } - d.Keep = len(d.Reasons) > 0 - if !d.Keep { - d.Reasons = []string{reasonExpired} - } - out[i] = d - } - return out -} - -// scheduleKeepOf is the count a scheduled snapshot's schedule keeps. -func scheduleKeepOf(s SnapshotInfo) int { - if n, err := strconv.Atoi(s.Labels[LabelScheduleKeep]); err == nil && n > 0 { - return n - } - return DefaultScheduleKeep -} - -// RetentionFailure is the deletion that stopped a Retain pass. -type RetentionFailure struct { - Name string `json:"name"` - Attempt string `json:"attempt"` - Code string `json:"code"` - Message string `json:"message"` - // Uncertain is set when the failing call was a mutation whose outcome - // is unknown (e.g. the response was lost): the snapshot may or may - // not be marked deleting. It is false when the pass failed before - // changing anything for this snapshot. - Uncertain bool `json:"uncertain"` -} - -// RetentionResult is the outcome of one Retain pass. -type RetentionResult struct { - VolumeID string `json:"volumeID"` - Policy RetentionPolicy `json:"policy"` - PolicySet bool `json:"policySet"` - DryRun bool `json:"dryRun"` - Decisions []RetentionDecision `json:"decisions"` - Deleted []string `json:"deleted"` // confirmed deleted (empty on a dry run) - Replaced []string `json:"replaced"` // planned, but the name now holds another attempt: left alone - Failed *RetentionFailure `json:"failed,omitempty"` - // NotAttempted lists the expired snapshots not reached because the - // pass stopped at Failed. - NotAttempted []string `json:"notAttempted"` - Kept int `json:"kept"` - Expired int `json:"expired"` -} - -// Retain applies vol's retention policy at the catalog clock's now. A dry -// run plans and writes nothing. Otherwise each expired snapshot's planned -// attempt is deleted (deleteRetainedAttempt). The first failure stops the -// pass; the result then still reports every confirmed deletion, the -// failure (with whether its outcome is uncertain), and what was not -// attempted, together with the error. -func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (RetentionResult, error) { - e, _, err := c.volumeEntry(ctx, vol) - if err != nil { - return RetentionResult{}, err - } - p, set, err := decodeRetention(e) - if err != nil { - return RetentionResult{}, err - } - listed, err := c.listSnapshots(ctx, vol, true) - if err != nil { - return RetentionResult{}, err - } - var snaps, unfinished []SnapshotInfo - for _, s := range listed { - if s.State == SnapDeleting { - unfinished = append(unfinished, s) // a pass stopped after its mark - } else { - snaps = append(snaps, s) - } - } - res := RetentionResult{VolumeID: vol, Policy: p, PolicySet: set, DryRun: dryRun, - Deleted: []string{}, Replaced: []string{}, NotAttempted: []string{}} - res.Decisions = planRetention(p, snaps, c.now()) - var expired []RetentionDecision - for _, d := range res.Decisions { - if d.Keep { - res.Kept++ - continue - } - res.Expired++ - expired = append(expired, d) - } - for _, s := range unfinished { - d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: s.Pinned(), Reasons: []string{SnapDeleting}} - res.Decisions = append(res.Decisions, d) - res.Expired++ - expired = append(expired, d) - } - if dryRun { - return res, nil - } - c.hook(hookPlanned, "") - for i, d := range expired { - outcome, uncertain, err := c.deleteRetainedAttempt(ctx, vol, d.Name, d.Attempt) - if err != nil { - res.Failed = &RetentionFailure{Name: d.Name, Attempt: d.Attempt, Code: codeOrRemote(err), Message: err.Error(), Uncertain: uncertain} - for _, rest := range expired[i+1:] { - res.NotAttempted = append(res.NotAttempted, rest.Name) - } - return res, err - } - switch outcome { - case retainDeleted: - res.Deleted = append(res.Deleted, d.Name) - case retainReplaced: - res.Replaced = append(res.Replaced, d.Name) - } - } - return res, nil -} - -func codeOrRemote(err error) string { - if code := CodeOf(err); code != "" { - return code - } - return CodeRemoteUnavailable -} - -type retainOutcome int - -const ( - retainDeleted retainOutcome = iota // marked deleting (or already gone) and the name freed - retainReplaced // the planned attempt is gone; another attempt holds the name -) - -// deleteRetainedAttempt deletes the planned attempt of vol/name and only -// that attempt. uncertain reports, with an error, that the failing call -// was a mutation whose outcome is unknown. -func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt string) (retainOutcome, bool, error) { - root, err := c.volRoot(vol) - if err != nil { - return 0, false, err - } - if _, uncertain, err := c.markDeleting(ctx, vol, name, attempt); err != nil { - return 0, uncertain, err - } - return c.freeName(ctx, root, name, attempt) -} - -type markResult int - -const ( - markDone markResult = iota // this call marked the attempt deleting - markGone // the attempt's entry is gone - markSettled // already deleting or aborted -) - -// markDeleting marks attempt of vol/name deleting, the one path for -// retention and explicit delete: the mark is conditioned on {state active, -// gen}; a lost condition re-reads and decides again. No fork claim is read -// (INV-SNAP-DELETE-ANY-ORDER-001). uncertain reports, with an error, a -// mutation whose outcome is unknown. -func (c *Catalog) markDeleting(ctx context.Context, vol, name, attempt string) (markResult, bool, error) { - root, err := c.volRoot(vol) - if err != nil { - return 0, false, err - } - dir := path.Join(root, snapsDir, name) - for try := 0; try < 5; try++ { - e, err := c.f.LookupEntry(ctx, dir, attempt) - if errors.Is(err, ErrNotFound) { - return markGone, false, nil - } - if err != nil { - return 0, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) - } - if string(e.Extended[extSnapState]) != SnapActive { - return markSettled, false, nil - } - c.hook(hookChecked, name) - next := proto.Clone(e).(*filerpb.Entry) - next.Extended[extSnapState] = []byte(SnapDeleting) - next.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) - err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{ - extSnapState: []byte(SnapActive), - extSnapGen: e.Extended[extSnapGen], - }) - if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue // a delete or a replacement landed: decide again - } - if err != nil { - return 0, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) - } - c.hook(hookMarked, name) - return markDone, false, nil - } - return 0, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt) -} - -// Test seams: hook stages in a Retain pass. -const ( - hookPlanned = "planned" // after planning, before any deletion - hookChecked = "checked" // an attempt was read active, before its mark - hookMarked = "marked" // an attempt is marked deleting, before its name is freed -) - -func (c *Catalog) hook(stage, name string) { - if c.retainHook != nil { - c.retainHook(stage, name) - } -} - -// freeName removes the name record of name only while it names attempt. -func (c *Catalog) freeName(ctx context.Context, root, name, attempt string) (retainOutcome, bool, error) { - err := c.f.DeleteEntry(ctx, path.Join(root, snapNamesDir), name, map[string][]byte{extAttempt: []byte(attempt)}) - switch { - case err == nil || errors.Is(err, ErrNotFound): - return retainDeleted, false, nil - case errors.Is(err, ErrPrecondition): - return retainReplaced, false, nil - } - return 0, true, remoteErr(err, "remove the name record %s", name) -} - -// allSnapshots lists every published, not-deleting snapshot of vol, with -// the attempt each name resolved to. -func (c *Catalog) allSnapshots(ctx context.Context, vol string) ([]SnapshotInfo, error) { - return c.listSnapshots(ctx, vol, false) -} - -func (c *Catalog) listSnapshots(ctx context.Context, vol string, deleting bool) ([]SnapshotInfo, error) { - var out []SnapshotInfo - after := "" - for { - page, next, err := c.ListSnapshots(ctx, vol, ListOptions{StartAfter: after, Limit: maxListLimit, IncludeDeleting: deleting}) - if err != nil { - return nil, err - } - out = append(out, page...) - if next == "" { - return out, nil - } - if next <= after { - return nil, errors.New("chunkstore: non-advancing snapshot listing") - } - after = next - } -} diff --git a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go deleted file mode 100644 index 1b06bdd46d..0000000000 --- a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go +++ /dev/null @@ -1,254 +0,0 @@ -//go:build chunkstore_integration - -package chunkstore - -import ( - "bytes" - "context" - "fmt" - "path" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Retention and accounting against a real SeaweedFS (CHUNKSTORE_WEED): -// N+5 semantic snapshots plus pinned ones; a dry run writes nothing; retain -// leaves N plus the pinned; accounting follows (GC not run: the deleted -// snapshots' chunks are still stored, now unreferenced). -func TestIntegration_RetainAndUsage(t *testing.T) { - c := startWeed(t) - ctx := context.Background() - const base = "/swblock/chunks" - geo := Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} - full := uint64(geo.ChunkBlocks) * uint64(geo.BlockSize) - cat, err := NewCatalog(c.client(t, base), base) - if err != nil { - t.Fatal(err) - } - if _, err := cat.EnsureVolume(ctx, "v1", geo); err != nil { - t.Fatal(err) - } - r := c.remote(t, path.Join(base, "v1")) - clock := time.Now().Add(-72 * time.Hour) - cat.SetClock(func() time.Time { return clock }) - - // One snapshot per step; each step rewrites chunk 0 under a new key, - // so every snapshot but the newest owns one chunk exclusively. - cur, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - step := 0 - snapshot := func(name, class string) { - t.Helper() - data := bytes.Repeat([]byte{byte(step + 1)}, int(full)) - key := fmt.Sprintf("chunks/e1/c0/step-%02d", step) - step++ - if err := r.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: uint64(step), Chunks: map[uint64]storage.ChunkRef{0: ref(key, data)}} - next = publishIntegrationHead(t, r, cur, next, full) - cur = next - clock = clock.Add(time.Minute) - if _, err := cat.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: "r-" + name, Class: class}, next); err != nil { - t.Fatal(err) - } - } - snapshot("golden-a", SnapshotClassPinned) // the oldest, but pinned - snapshot("golden-b", SnapshotClassPinned) - const n = DefaultKeepNewest - for i := 0; i < n+5; i++ { - snapshot(fmt.Sprintf("s%02d", i), SnapshotClassSemantic) - } - clock = time.Now() - - before, err := cat.Usage(ctx, "v1") - if err != nil { - t.Fatal(err) - } - if len(before.Snapshots) != n+7 || before.StoredBindings != 2*(n+7) || before.ManifestBindings != n+7 || before.StoredUpperBound || before.LiveBytes != full { - t.Fatalf("before: %d snapshots, %d bindings, upper=%t, live=%d", len(before.Snapshots), before.StoredBindings, before.StoredUpperBound, before.LiveBytes) - } - exclusive := func(u VolumeUsage) uint64 { - var sum uint64 - for _, s := range u.Snapshots { - sum += s.ExclusiveBytes - } - return sum - } - if got := exclusive(before); got != uint64(n+6)*full { - t.Fatalf("before: exclusive %d, want %d (all but the newest snapshot)", got, uint64(n+6)*full) - } - - // Dry run: exactly the 5 oldest semantic snapshots, nothing written. - namesBefore, err := c.client(t, base).ListEntries(ctx, path.Join(base, "v1", snapNamesDir), "", "", 0) - if err != nil { - t.Fatal(err) - } - dry, err := cat.Retain(ctx, "v1", true) - if err != nil { - t.Fatal(err) - } - var wouldGo []string - for _, d := range dry.Decisions { - if !d.Keep { - wouldGo = append(wouldGo, d.Name) - } - } - if fmt.Sprint(wouldGo) != "[s04 s03 s02 s01 s00]" || len(dry.Deleted) != 0 { - t.Fatalf("dry run: would delete %v, deleted %v", wouldGo, dry.Deleted) - } - namesAfter, err := c.client(t, base).ListEntries(ctx, path.Join(base, "v1", snapNamesDir), "", "", 0) - if err != nil || len(namesAfter) != len(namesBefore) { - t.Fatalf("dry run changed the name records: %d -> %d (%v)", len(namesBefore), len(namesAfter), err) - } - - res, err := cat.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - if len(res.Deleted) != 5 || res.Kept != n+2 { - t.Fatalf("retain: deleted %v, kept %d", res.Deleted, res.Kept) - } - after, err := cat.Usage(ctx, "v1") - if err != nil { - t.Fatal(err) - } - left := map[string]bool{} - for _, s := range after.Snapshots { - left[s.Name] = true - } - if len(after.Snapshots) != n+2 || !left["golden-a"] || !left["golden-b"] || left["s04"] || !left["s05"] { - t.Fatalf("after: snapshots %v", left) - } - if got := exclusive(after); got != uint64(n+1)*full { - t.Fatalf("after: exclusive %d, want %d", got, uint64(n+1)*full) - } - if after.StoredBindings != 2*(n+7) || after.ManifestBindings != n+7 || !after.StoredUpperBound { - t.Fatalf("after: %d bindings, upper=%t; want all still stored (no GC yet), flagged as an upper bound", after.StoredBindings, after.StoredUpperBound) - } -} - -// The two held schedules of the review of #142 against a real filer: -// (1) a same-name pinned replacement made after planning survives (the -// filer's conditional name delete refuses the stale attempt); (2) a fork -// that starts after the scan and stops before its HEAD (VOLUME published, -// deadline exceeded) keeps its parent, and completes on retry; (3) a fork -// that claims between retention's claim check and its mark makes the -// filer refuse the mark (conditioned on no claims), so the parent is kept. -func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) { - c := startWeed(t) - ctx := context.Background() - const base = "/swblock/chunks" - geo := Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} - full := int(geo.ChunkBlocks) * int(geo.BlockSize) - cat, err := NewCatalog(c.client(t, base), base) - if err != nil { - t.Fatal(err) - } - if _, err := cat.EnsureVolume(ctx, "v1", geo); err != nil { - t.Fatal(err) - } - r := c.remote(t, path.Join(base, "v1")) - data := bytes.Repeat([]byte{7}, full) - if err := r.Put(ctx, "chunks/e1/c0/k", data); err != nil { - t.Fatal(err) - } - cur, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - head := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: ref("chunks/e1/c0/k", data)}} - head = publishIntegrationHead(t, r, cur, head, uint64(full)) - clock := time.Now().Add(-72 * time.Hour) - cat.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) // every read advances - for i := 0; i < 3; i++ { - if _, err := cat.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: fmt.Sprintf("s%02d", i), RequestID: fmt.Sprintf("r%02d", i), Class: SnapshotClassSemantic}, head); err != nil { - t.Fatal(err) - } - } - if err := cat.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy - t.Fatal(err) - } - clock = time.Now() - - var pinnedAttempt string - stoppedFork := func(snap, target string) { - t.Helper() - start := clock - cat.SetClock(func() time.Time { return clock }) - original := cat.f - cat.f = expireForkVolumeFiler{Filer: original, target: path.Join(base, target, volumeName), expire: func() { clock = start.Add(DefaultOpDeadline) }} - _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: snap, Target: target, RequestID: "f"}) - cat.f = original - cat.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) - if CodeOf(err) != CodeDeadlineExceeded { - t.Fatalf("fork %s past its deadline: %v; want deadline_exceeded", target, err) - } - if _, ok, err := cat.ReadVolume(ctx, target); !ok || err != nil { - t.Fatalf("the stopped fork %s VOLUME: ok=%t %v", target, ok, err) - } - } - cat.retainHook = func(stage, name string) { - if stage == hookChecked && name == "s02" { - stoppedFork("s02", "v3") // (3) lands between the check and the mark - return - } - if stage != hookPlanned { - return - } - // (1) s00 is replaced by a pinned snapshot of the same name. - if _, err := cat.DeleteSnapshot(ctx, "v1", "s00"); err != nil { - t.Fatal(err) - } - if _, err := cat.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s00", RequestID: "pinned-b", Class: SnapshotClassPinned}, head); err != nil { - t.Fatal(err) - } - b, err := cat.readSnap(ctx, "v1", "s00") - if err != nil { - t.Fatal(err) - } - pinnedAttempt = b.attempt - // (2) a fork of s01 publishes its VOLUME and stops before HEAD. - stoppedFork("s01", "v2") - } - res, err := cat.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - cat.retainHook = nil - if fmt.Sprint(res.Deleted) != "[s02 s01]" || fmt.Sprint(res.Replaced) != "[s00]" { - t.Fatalf("retain: deleted=%v replaced=%v; want s02 s01 / s00 (forks do not hold their parent)", res.Deleted, res.Replaced) - } - b, err := cat.readSnap(ctx, "v1", "s00") - if err != nil || b.attempt != pinnedAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned { - t.Fatalf("pinned replacement: %+v %v (attempt %s, want %s)", b, err, b.attempt, pinnedAttempt) - } - // A retry of either stopped fork reads its parent again and is refused. - for _, fk := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} { - _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: fk.snap, Target: fk.target, RequestID: "f"}) - if code := CodeOf(err); code != CodeSnapshotNotFound && code != CodeSnapshotDeleting { - t.Fatalf("fork %s retry after its parent was deleted: %v; want snapshot_not_found or snapshot_deleting", fk.target, err) - } - } -} - -// expireForkVolumeFiler advances only after the target identity was stored; -// the retention test therefore exercises an incomplete fork, not an absent one. -type expireForkVolumeFiler struct { - Filer - target string - expire func() -} - -func (f expireForkVolumeFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, exclusive bool) error { - err := f.Filer.CreateEntry(ctx, dir, e, exclusive) - if err == nil && path.Join(dir, e.Name) == f.target { - f.expire() - } - return err -} diff --git a/seaweed-block/core/frontend/chunkstore/retention_review_test.go b/seaweed-block/core/frontend/chunkstore/retention_review_test.go deleted file mode 100644 index 0ebd5b8081..0000000000 --- a/seaweed-block/core/frontend/chunkstore/retention_review_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" -) - -// Controls for the review of #142: attempt-bound deletion, fork claims, -// rolling windows, cross-volume holders and partial results. - -// Log-spaced keeps use rolling windows anchored at now, not calendar -// periods: at 10:30 with KeepHourly=1, 10:20 is kept and 09:50 (another -// clock hour, but inside the same rolling hour) is not. -func TestPlanRetention_RollingWindows(t *testing.T) { - day0 := time.Unix(86400*1000, 0) // midnight, so clock hours and days are visible - at := func(d time.Duration) time.Time { return day0.Add(d) } - nm := func(a time.Time) string { return a.UTC().Format("01-02T15:04") } - plan := func(p RetentionPolicy, now time.Time, ages ...time.Time) map[string][]string { - var snaps []SnapshotInfo - for _, a := range ages { - snaps = append(snaps, snapAt(nm(a), a, SnapshotClassSemantic, time.Time{}, nil)) - } - return kept(planRetention(p, snaps, now)) - } - now := at(10*time.Hour + 30*time.Minute) - if k := plan(RetentionPolicy{KeepHourly: 1}, now, at(10*time.Hour+20*time.Minute), at(9*time.Hour+50*time.Minute)); len(k) != 1 || k[nm(at(10*time.Hour+20*time.Minute))] == nil { - t.Fatalf("hourly at 10:30: kept %v; want only 10:20", k) - } - // Windows k=0,1: [09:30,10:30) and [08:30,09:30). 09:00 is the newest of window 1. - if k := plan(RetentionPolicy{KeepHourly: 2}, now, at(10*time.Hour+20*time.Minute), at(9*time.Hour+50*time.Minute), at(9*time.Hour), at(8*time.Hour+40*time.Minute)); len(k) != 2 || k[nm(at(10*time.Hour+20*time.Minute))] == nil || k[nm(at(9*time.Hour))] == nil { - t.Fatalf("hourly=2 at 10:30: kept %v; want 10:20 and 09:00", k) - } - // Daily across a non-aligned midnight: at 01:00, 00:30 and 23:00 the - // day before are both in the last rolling day; only the newest stays. - now = at(24*time.Hour + time.Hour) - if k := plan(RetentionPolicy{KeepDaily: 1}, now, at(24*time.Hour+30*time.Minute), at(23*time.Hour)); len(k) != 1 || k[nm(at(24*time.Hour+30*time.Minute))] == nil { - t.Fatalf("daily at 01:00: kept %v; want only 00:30", k) - } - // Weekly: 8 days back is week window 1, 6 days back window 0. - if k := plan(RetentionPolicy{KeepWeekly: 1}, now, now.Add(-6*24*time.Hour), now.Add(-8*24*time.Hour)); len(k) != 1 { - t.Fatalf("weekly=1: kept %v; want only the 6-day-old one", k) - } - if k := plan(RetentionPolicy{KeepWeekly: 2}, now, now.Add(-6*24*time.Hour), now.Add(-8*24*time.Hour), now.Add(-13*24*time.Hour)); len(k) != 2 { - t.Fatalf("weekly=2: kept %v; want 6 and 8 days old", k) - } -} - -// Deletion is bound to the planned attempt: a same-name pinned replacement -// made between planning and deletion survives, attempt and name intact. -func TestCatalog_RetainSkipsASameNameReplacement(t *testing.T) { - _, c, h, _ := retentionFixture(t, 15) // s00..s04 expire - ctx := context.Background() - var newAttempt string - c.retainHook = func(stage, _ string) { - if stage != hookPlanned { - return - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s02"); err != nil { - t.Fatal(err) - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s02", RequestID: "pinned-b", Class: SnapshotClassPinned}, h); err != nil { - t.Fatal(err) - } - b, err := c.readSnap(ctx, "v1", "s02") - if err != nil { - t.Fatal(err) - } - newAttempt = b.attempt - } - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - b, err := c.readSnap(ctx, "v1", "s02") - if err != nil { - t.Fatalf("the pinned replacement is gone: %v", err) - } - if b.attempt != newAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned { - t.Fatalf("replacement changed: %+v (attempt %s, want %s)", b, b.attempt, newAttempt) - } - if strings.Join(res.Replaced, ",") != "s02" || strings.Join(res.Deleted, ",") != "s04,s03,s01,s00" { - t.Fatalf("deleted=%v replaced=%v; want s02 replaced, the other four deleted", res.Deleted, res.Replaced) - } -} - -func forkFixture(t *testing.T) (*fakeFiler, *Catalog) { - t.Helper() - f, c, _, _ := retentionFixture(t, 3) - ctx := context.Background() - if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy - t.Fatal(err) - } - for _, vol := range []string{"v1", "v2"} { - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - } - return f, c -} - -// A fork arriving after the mark finds the parent deleting and refuses -// before installing anything (and leaves no claim). -func TestCatalog_ForkAfterTheMarkRefuses(t *testing.T) { - _, c := forkFixture(t) - ctx := context.Background() - ran := false - c.retainHook = func(stage, name string) { - if stage != hookMarked || name != "s01" { - return - } - ran = true - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotDeleting { - t.Fatalf("fork of a marked parent: %v; want snapshot_deleting", err) - } - } - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - if !ran || strings.Join(res.Deleted, ",") != "s02,s01,s00" { - t.Fatalf("ran=%v deleted=%v; want all three", ran, res.Deleted) - } - if _, ok, err := c.ReadVolume(ctx, "v2"); ok || err != nil { - t.Fatalf("a refused fork published its VOLUME (%v)", err) - } -} - -// A failure part way reports the confirmed deletions, the failing -// snapshot (uncertain: the mark's outcome is unknown) and what was not -// attempted; a lost response leaves the snapshot deleting and the next -// pass finishes it. -func TestCatalog_RetainReportsPartialProgress(t *testing.T) { - f, c, _, _ := retentionFixture(t, 15) // s04,s03,s02,s01,s00 expire, in that order - ctx := context.Background() - f.failUpdate = func(p string) error { - if strings.Contains(p, "/snaps/s03/") { - return errors.New("filer unavailable") - } - return nil - } - res, err := c.Retain(ctx, "v1", false) - if err == nil || res.Failed == nil { - t.Fatalf("retain with a failing mark: %+v %v; want an error with the partial result", res, err) - } - if strings.Join(res.Deleted, ",") != "s04" || res.Failed.Name != "s03" || !res.Failed.Uncertain || strings.Join(res.NotAttempted, ",") != "s02,s01,s00" { - t.Fatalf("partial: deleted=%v failed=%+v notAttempted=%v", res.Deleted, res.Failed, res.NotAttempted) - } - - f.failUpdate = nil - f.failUpdateAfterApply = func(p string) error { - if strings.Contains(p, "/snaps/s03/") { - return errors.New("response lost") - } - return nil - } - res, err = c.Retain(ctx, "v1", false) - if err == nil || res.Failed == nil || res.Failed.Name != "s03" || !res.Failed.Uncertain || len(res.Deleted) != 0 { - t.Fatalf("lost response: %+v %v", res, err) - } - f.failUpdateAfterApply = nil - dry, err := c.Retain(ctx, "v1", true) - if err != nil { - t.Fatal(err) - } - listed := false - for _, d := range dry.Decisions { - if d.Name == "s03" && !d.Keep && strings.Join(d.Reasons, ",") == SnapDeleting { - listed = true - } - } - if !listed || dry.Expired != 4 { - t.Fatalf("dry run after the lost response: expired=%d decisions=%+v; want s03 listed as deleting", dry.Expired, dry.Decisions) - } - res, err = c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s02,s01,s00,s03" { - t.Fatalf("rerun: deleted=%v %v; want the rest and the half-deleted s03", res.Deleted, err) - } - if _, ok, err := c.resolveSnap(ctx, "v1", "s03"); ok || err != nil { - t.Fatalf("s03's name still held after the rerun (%v)", err) - } -} - -// Exclusive bytes count other volumes' holders: after a completed fork, a -// snapshot whose chunks the fork's HEAD references ("@v1/key") owns none. -func TestCatalog_UsageCountsForkHolders(t *testing.T) { - f, b, c, h := catalogFixture(t) - ctx := context.Background() - for _, vol := range []string{"v1", "v2"} { - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { - t.Fatal(err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil { - t.Fatal(err) - } - publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)}) - u, err := c.Usage(ctx, "v1") - if err != nil { - t.Fatal(err) - } - if len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 { - t.Fatalf("s1 after v1's HEAD moved, v2 forked from it: %+v; want 0 exclusive (v2 holds both chunks)", u.Snapshots) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go deleted file mode 100644 index 29c13a3bdd..0000000000 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ /dev/null @@ -1,431 +0,0 @@ -package chunkstore - -import ( - "context" - "crypto/sha256" - "fmt" - "path" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Snapshot retention and space accounting: policy edges, dry run, forks, -// accounting. - -var retBase = time.Unix(1_000_000, 0) - -func snapAt(name string, at time.Time, class string, expiresAt time.Time, labels map[string]string) SnapshotInfo { - s := SnapshotInfo{Name: name, CreatedNs: at.UnixNano(), Class: class, Labels: labels} - if !expiresAt.IsZero() { - s.ExpiresAtNs = expiresAt.UnixNano() - } - return s -} - -func kept(ds []RetentionDecision) map[string][]string { - out := map[string][]string{} - for _, d := range ds { - if d.Keep { - out[d.Name] = d.Reasons - } - } - return out -} - -func noYoung() RetentionPolicy { return RetentionPolicy{KeepNewest: 10} } - -// Newest N unpinned are kept; equal creation times rank by name. -func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { - now := retBase.Add(48 * time.Hour) - var snaps []SnapshotInfo - for i := 0; i < 15; i++ { - snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), retBase.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) - } - k := kept(planRetention(noYoung(), snaps, now)) - if len(k) != 10 { - t.Fatalf("kept %d, want 10: %v", len(k), k) - } - for i := 5; i < 15; i++ { - if _, ok := k[fmt.Sprintf("s%02d", i)]; !ok { - t.Fatalf("newest s%02d not kept: %v", i, k) - } - } - tie := []SnapshotInfo{snapAt("b", retBase, "", time.Time{}, nil), snapAt("a", retBase, "", time.Time{}, nil)} - if k := kept(planRetention(RetentionPolicy{KeepNewest: 1}, tie, now)); len(k) != 1 || k["a"] == nil { - t.Fatalf("tie: kept %v, want only a (name order)", k) - } -} - -// Pinned: never expired by count or age; past its ExpiresAtNs it is -// unpinned again. Semantic and labeled snapshots are not exempt. -func TestPlanRetention_PinnedSemanticAndLabels(t *testing.T) { - now := retBase.Add(48 * time.Hour) - snaps := []SnapshotInfo{ - snapAt("pinned-old", retBase, SnapshotClassPinned, time.Time{}, nil), - snapAt("pinned-by-expiry", retBase, "", now.Add(time.Hour), nil), - snapAt("pinned-expired", retBase, SnapshotClassPinned, now.Add(-time.Second), nil), - snapAt("semantic-old", retBase, SnapshotClassSemantic, time.Time{}, nil), - snapAt("labeled-old", retBase, "", time.Time{}, map[string]string{"agent.step": "npm-ci"}), - } - k := kept(planRetention(RetentionPolicy{}, snaps, now)) - if len(k) != 2 || k["pinned-old"] == nil || k["pinned-by-expiry"] == nil { - t.Fatalf("kept %v; want exactly pinned-old and pinned-by-expiry", k) - } -} - -// Younger than T is kept beyond N; a creation time in the future (clock -// skew) counts as young. -func TestPlanRetention_YoungAndClockSkew(t *testing.T) { - now := retBase.Add(48 * time.Hour) - p := RetentionPolicy{KeepNewest: 0, KeepYoungerNs: int64(time.Hour)} - snaps := []SnapshotInfo{ - snapAt("young", now.Add(-30*time.Minute), SnapshotClassSemantic, time.Time{}, nil), - snapAt("future", now.Add(10*time.Minute), SnapshotClassSemantic, time.Time{}, nil), - snapAt("old", now.Add(-2*time.Hour), SnapshotClassSemantic, time.Time{}, nil), - } - k := kept(planRetention(p, snaps, now)) - if len(k) != 2 || k["young"] == nil || k["future"] == nil { - t.Fatalf("kept %v; want young and future", k) - } -} - -// Log-spaced keeps: the newest snapshot of each of the last H hours. -func TestPlanRetention_HourlyBuckets(t *testing.T) { - now := retBase.Add(48*time.Hour + 59*time.Minute) // late in an hour - var snaps []SnapshotInfo - for i := 0; i < 12; i++ { // every 30 min over the last 6 hours - snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), now.Add(-time.Duration(i)*30*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) - } - k := kept(planRetention(RetentionPolicy{KeepHourly: 3}, snaps, now)) - if len(k) != 3 { - t.Fatalf("kept %d, want 3 (one per hour for the last 3 hours): %v", len(k), k) - } - for _, reasons := range k { - if len(reasons) != 1 || reasons[0] != keepHourly { - t.Fatalf("reasons %v; want hourly", reasons) - } - } -} - -// An agent that checkpoints every step stays bounded: one semantic -// snapshot a minute for a day keeps at most N + T/step + hourly buckets. -func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) { - p := RetentionPolicy{KeepNewest: DefaultKeepNewest, KeepYoungerNs: int64(DefaultKeepYounger), KeepHourly: 24} - start := retBase - var snaps []SnapshotInfo - for i := 0; i < 24*60; i++ { - snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, map[string]string{"agent.step": fmt.Sprint(i)})) - } - now := start.Add(24 * time.Hour) - bound := p.KeepNewest + int(DefaultKeepYounger/time.Minute) + p.KeepHourly - if k := kept(planRetention(p, snaps, now)); len(k) > bound { - t.Fatalf("kept %d of %d step checkpoints; want at most %d", len(k), len(snaps), bound) - } - // The bound holds however long the agent runs. - for i := 24 * 60; i < 7*24*60; i++ { - snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) - } - if k := kept(planRetention(p, snaps, start.Add(7*24*time.Hour))); len(k) > bound { - t.Fatalf("after a week: kept %d; want at most %d", len(k), bound) - } -} - -// retentionFixture makes n semantic snapshots of v1, one a minute, two -// days before the catalog clock's now. -func retentionFixture(t *testing.T, n int) (*fakeFiler, *Catalog, storage.ChunkHead, *time.Time) { - t.Helper() - f, _, c, h := catalogFixture(t) - clock := retBase - c.SetClock(func() time.Time { return clock }) - for i := 0; i < n; i++ { - clock = retBase.Add(time.Duration(i) * time.Minute) - if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: fmt.Sprintf("s%02d", i), RequestID: fmt.Sprintf("r%02d", i), Class: SnapshotClassSemantic}, h); err != nil { - t.Fatal(err) - } - } - clock = retBase.Add(48 * time.Hour) - return f, c, h, &clock -} - -func snapNames(t *testing.T, c *Catalog) map[string]bool { - t.Helper() - snaps, err := c.allSnapshots(context.Background(), "v1") - if err != nil { - t.Fatal(err) - } - out := map[string]bool{} - for _, s := range snaps { - out[s.Name] = true - } - return out -} - -// A dry run lists exactly what would go and writes nothing. -func TestCatalog_RetainDryRunWritesNothing(t *testing.T) { - f, c, _, _ := retentionFixture(t, 15) - before := len(f.allWritten()) - res, err := c.Retain(context.Background(), "v1", true) - if err != nil { - t.Fatal(err) - } - if got := len(f.allWritten()); got != before { - t.Fatalf("dry run wrote %d entries", got-before) - } - var expired []string - for _, d := range res.Decisions { - if !d.Keep { - expired = append(expired, d.Name) - } - } - if res.Expired != 5 || res.Kept != 10 || len(res.Deleted) != 0 || strings.Join(expired, ",") != "s04,s03,s02,s01,s00" { - t.Fatalf("dry run: expired=%d kept=%d deleted=%v names=%v; want the 5 oldest listed, none deleted", res.Expired, res.Kept, res.Deleted, expired) - } - if len(snapNames(t, c)) != 15 { - t.Fatal("dry run removed snapshots") - } -} - -// Retain deletes the expired snapshots, keeps N plus the pinned one, and -// frees the expired names. -func TestCatalog_RetainKeepsNewestNAndPinned(t *testing.T) { - _, c, h, clock := retentionFixture(t, 15) - ctx := context.Background() - saved := *clock - *clock = retBase.Add(-time.Hour) // the oldest snapshot of all, but pinned - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "golden", RequestID: "rg", Class: SnapshotClassPinned}, h); err != nil { - t.Fatal(err) - } - *clock = saved - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - names := snapNames(t, c) - if len(res.Deleted) != 5 || len(names) != 11 || !names["golden"] || names["s00"] || !names["s14"] { - t.Fatalf("after retain: deleted=%v remaining=%v; want 5 deleted, s05..s14 and golden left", res.Deleted, names) - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s00", RequestID: "reuse"}, h); err != nil { - t.Fatalf("expired name not freed: %v", err) - } -} - -// The policy lives on the VOLUME entry: default until set; set stores it -// without touching the volume document; negatives are refused. -func TestCatalog_RetentionPolicyStoredOnVolume(t *testing.T) { - _, _, c, _ := catalogFixture(t) - ctx := context.Background() - p, set, err := c.ReadRetentionPolicy(ctx, "v1") - if err != nil || set || p != DefaultRetentionPolicy() { - t.Fatalf("unset policy: %+v set=%t err=%v; want the default", p, set, err) - } - want := RetentionPolicy{KeepNewest: 3, KeepYoungerNs: int64(time.Minute), KeepDaily: 7} - if err := c.SetRetentionPolicy(ctx, "v1", want); err != nil { - t.Fatal(err) - } - if p, set, err := c.ReadRetentionPolicy(ctx, "v1"); err != nil || !set || p != want { - t.Fatalf("stored policy: %+v set=%t err=%v", p, set, err) - } - if v, ok, err := c.ReadVolume(ctx, "v1"); err != nil || !ok || v.Geometry != catGeo { - t.Fatalf("volume after setting a policy: %+v %t %v", v, ok, err) - } - if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{KeepNewest: -1}); CodeOf(err) != CodeInvalidPolicy { - t.Fatalf("negative policy: %v; want invalid_policy", err) - } -} - -// Two setters racing on one revision: the second update's precondition -// fails. -func TestCatalog_RetentionPolicyConcurrentSetIsConditional(t *testing.T) { - f, _, c, _ := catalogFixture(t) - ctx := context.Background() - f.failUpdate = func(p string) error { - if p == path.Join(catBase, "v1", volumeName) { - f.failUpdate = nil - // another setter lands first - e := f.entries[p] - e.Extended[extRetentionRev] = []byte("7") - } - return nil - } - if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{KeepNewest: 1}); err == nil { - t.Fatal("a set that lost the race succeeded") - } -} - -// The class is validated and stored with the snapshot. -func TestCatalog_SnapshotClass(t *testing.T) { - _, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "x", RequestID: "rx", Class: "forever"}, h); CodeOf(err) != CodeInvalidClass { - t.Fatalf("unknown class: %v; want invalid_class", err) - } - s, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "p", RequestID: "rp", Class: SnapshotClassPinned}, h) - if err != nil || s.Class != SnapshotClassPinned || !s.Pinned() { - t.Fatalf("pinned snapshot: %+v %v", s, err) - } - snaps, err := c.allSnapshots(ctx, "v1") - if err != nil || len(snaps) != 1 || snaps[0].Class != SnapshotClassPinned { - t.Fatalf("listed class: %+v %v", snaps, err) - } -} - -// publishTagged installs a HEAD for vol with chunks under keys tagged tag. -func publishTagged(t *testing.T, f *fakeFiler, b *fakeBlobs, vol, tag string, chunks map[uint64][]byte) storage.ChunkHead { - t.Helper() - ctx := context.Background() - r, err := NewChunkRemote(f, b, path.Join(catBase, vol)) - if err != nil { - t.Fatal(err) - } - h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 43, Chunks: map[uint64]storage.ChunkRef{}} - for idx, data := range chunks { - key := fmt.Sprintf("chunks/%s/c%d/k", tag, idx) - if err := r.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} - } - cur, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - h, ids, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks)) - if err != nil { - t.Fatal(err) - } - gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h) - if err != nil { - t.Fatal(err) - } - h.Gen = gen - for _, id := range ids { - if err := r.DeleteIntent(ctx, id); err != nil { - t.Fatal(err) - } - } - return h -} - -// Accounting from manifests and listings: live bytes from HEAD; a -// snapshot's exclusive bytes are what only it references; stored bytes -// count every binding, exact for referenced keys. -func TestCatalog_UsageFromManifests(t *testing.T) { - f, b, c, h := catalogFixture(t) // HEAD: chunks 0 and 3 - ctx := context.Background() - full := uint64(catGeo.ChunkBlocks) * uint64(catGeo.BlockSize) - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - manifestBytes := func(head storage.ChunkHead) uint64 { - var total uint64 - for _, ref := range head.Segments { - body, err := r.Get(ctx, ref.Key) - if err != nil { - t.Fatal(err) - } - total += uint64(len(body)) - } - return total - } - expectedManifestBytes := manifestBytes(h) - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { - t.Fatal(err) - } - u, err := c.Usage(ctx, "v1") - if err != nil { - t.Fatal(err) - } - if u.LiveChunks != 2 || u.LiveBytes != 2*full || len(u.Snapshots) != 1 || u.Snapshots[0].ExclusiveBytes != 0 { - t.Fatalf("shared chunks: %+v", u) - } - if u.StoredBindings != 3 || u.ManifestBindings != 1 || expectedManifestBytes == 0 || u.ManifestBytes != expectedManifestBytes || u.StoredBytes != 2*full+expectedManifestBytes || u.StoredUpperBound { - t.Fatalf("stored: %+v; want 2 bindings, exact", u) - } - - // HEAD moves on: chunk 0 is rewritten, so s1 alone holds the old one. - newHead := publishTagged(t, f, b, "v1", "e2", map[uint64][]byte{0: chunkBytes(0x20), 3: chunkBytes(0x13)}) - expectedManifestBytes += manifestBytes(newHead) - u, err = c.Usage(ctx, "v1") - if err != nil { - t.Fatal(err) - } - if u.Snapshots[0].ExclusiveBytes != 2*full { - // both of s1's chunks are now exclusive: the new HEAD uses e2 keys - t.Fatalf("after HEAD moved: s1 exclusive %d, want %d", u.Snapshots[0].ExclusiveBytes, 2*full) - } - if u.StoredBindings != 6 || u.ManifestBindings != 2 || u.ManifestBytes != expectedManifestBytes || u.StoredBytes != 4*full+expectedManifestBytes || u.StoredUpperBound { - t.Fatalf("stored after HEAD moved: %+v; want 4 bindings, exact", u) - } - - // s1 deleted: its keys are unreferenced but still stored (until GC), - // counted at the full chunk size as an upper bound. - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - u, err = c.Usage(ctx, "v1") - if err != nil { - t.Fatal(err) - } - if len(u.Snapshots) != 0 || u.StoredBindings != 6 || !u.StoredUpperBound { - t.Fatalf("after delete: %+v; want no snapshots, 4 bindings, upper bound", u) - } -} - -// chunkSize clips the last chunk to NumBlocks. -func TestChunkSizeClipsLastChunk(t *testing.T) { - g := Geometry{NumBlocks: 20, BlockSize: 4096, ChunkBlocks: 8} - for idx, want := range map[uint64]uint64{0: 8 * 4096, 1: 8 * 4096, 2: 4 * 4096, 3: 0} { - if got := chunkSize(g, idx); got != want { - t.Errorf("chunk %d: %d, want %d", idx, got, want) - } - } -} - -// Scheduled snapshots form their own class: retention keeps the newest K -// of them, K from the newest one's LabelScheduleKeep, and they neither -// count against KeepNewest nor get the age keeps; other snapshots are -// planned as before. -func TestPlanRetention_ScheduledClassKeepsItsOwnNewest(t *testing.T) { - now := retBase.Add(30 * 24 * time.Hour) - keep3 := map[string]string{LabelScheduleKeep: "3"} - var snaps []SnapshotInfo - for d := 0; d < 6; d++ { // one scheduled snapshot a day, the newest first at now-1h - snaps = append(snaps, snapAt(fmt.Sprintf("sched-%d", d), now.Add(-time.Hour-time.Duration(d)*24*time.Hour), SnapshotClassScheduled, time.Time{}, keep3)) - } - snaps = append(snaps, - snapAt("manual-new", now.Add(-2*time.Hour), "", time.Time{}, nil), - snapAt("manual-old", now.Add(-20*24*time.Hour), "", time.Time{}, nil)) - k := kept(planRetention(RetentionPolicy{KeepNewest: 2, KeepYoungerNs: int64(30 * 24 * time.Hour)}, snaps, now)) - for _, name := range []string{"sched-0", "sched-1", "sched-2", "manual-new", "manual-old"} { - if k[name] == nil { - t.Fatalf("kept %v; %s missing", k, name) - } - } - if len(k) != 5 { - t.Fatalf("kept %v; want the 3 newest scheduled and both manual (KeepNewest 2 is theirs alone)", k) - } - // Without a valid label the default count applies. - snaps[0].Labels = nil - if k := kept(planRetention(RetentionPolicy{}, snaps[:6], now)); len(k) != 6 { - t.Fatalf("kept %v with no label on the newest; want min(6, DefaultScheduleKeep)", k) - } -} - -// A pinned scheduled snapshot stays in its class: it is kept by its pin, -// ranks among the scheduled ones (its label sets K when it is the newest), -// and takes no log-spaced window from a manual snapshot. -func TestPlanRetention_PinnedScheduledStaysInItsClass(t *testing.T) { - now := retBase.Add(30 * 24 * time.Hour) - newest := snapAt("sched-pinned", now.Add(-10*time.Minute), SnapshotClassScheduled, now.Add(24*time.Hour), map[string]string{LabelScheduleKeep: "2"}) - snaps := []SnapshotInfo{ - newest, - snapAt("sched-1", now.Add(-24*time.Hour), SnapshotClassScheduled, time.Time{}, map[string]string{LabelScheduleKeep: "9"}), - snapAt("sched-2", now.Add(-48*time.Hour), SnapshotClassScheduled, time.Time{}, map[string]string{LabelScheduleKeep: "9"}), - snapAt("manual", now.Add(-20*time.Minute), "", time.Time{}, nil), // same hourly window as the pinned scheduled one - } - k := kept(planRetention(RetentionPolicy{KeepHourly: 1}, snaps, now)) - if len(k) != 3 || k["sched-pinned"] == nil || k["sched-1"] == nil || k["manual"] == nil { - t.Fatalf("kept %v; want sched-pinned (pin, K=2 from its label), sched-1 (second newest scheduled) and manual (its hourly window)", k) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go b/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go deleted file mode 100644 index a70a44babb..0000000000 --- a/seaweed-block/core/frontend/chunkstore/segment_fuzz_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package chunkstore - -import ( - "crypto/sha256" - "encoding/json" - "reflect" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func FuzzDecodeVersionedSegment(f *testing.F) { - sum := sha256.Sum256([]byte("stored bytes")) - refs := map[uint64]storage.ChunkRef{0: {Key: "@v1/k", SHA256: sum, Encoding: "full", BirthLSN: 7}} - body, _, err := encodeSegmentV2(0, 4096, "v1", refs) - if err != nil { - f.Fatal(err) - } - f.Add(body, uint8(2)) - legacy, err := json.Marshal(legacySegmentDoc{Format: 1, Range: 0, ChunkBytes: 4096, Owner: "v1", Chunks: map[uint64]legacyChunkRefDoc{0: {Key: "@v1/k", SHA256: sum}}}) - if err != nil { - f.Fatal(err) - } - f.Add(legacy, uint8(1)) - f.Add([]byte(`{"format":2,"format":1}`), uint8(2)) - f.Add([]byte(`{"format":3}`), uint8(3)) - f.Fuzz(func(t *testing.T, body []byte, version uint8) { - ref := storage.ChunkSegment{SegFormat: int(version), MaxBirthLSN: 7} - got, err := decodeSegment(body, ref, 7) - if err != nil { - return - } - if got.Format != 1 && got.Format != 2 { - t.Fatalf("accepted format %d", got.Format) - } - for _, cr := range got.Chunks { - if cr.Encoding != "full" || cr.BirthLSN > 7 { - t.Fatalf("accepted unsupported chunk metadata: %+v", cr) - } - } - if got.Format == 2 { - encoded, maxBirth, err := encodeSegmentV2(got.Range, got.ChunkBytes, got.Owner, got.Chunks) - if err != nil { - t.Fatal(err) - } - ref.MaxBirthLSN = maxBirth - again, err := decodeSegment(encoded, ref, 7) - if err != nil || !reflect.DeepEqual(got, again) { - t.Fatalf("round trip: %+v / %+v: %v", got, again, err) - } - } - }) -} diff --git a/seaweed-block/core/frontend/chunkstore/share_guard.go b/seaweed-block/core/frontend/chunkstore/share_guard.go deleted file mode 100644 index 1f4ba19c7c..0000000000 --- a/seaweed-block/core/frontend/chunkstore/share_guard.go +++ /dev/null @@ -1,61 +0,0 @@ -package chunkstore - -import ( - "context" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// ShareGuard is told about every sharer of a volume's chunks. A snapshot or -// fork calls Begin before it obtains the HEAD it will reference, and Finish, -// with that HEAD, right before it activates its result; an error from either -// aborts the share before anything is activated. A token Begin returned and -// nobody finished is the guard's to expire. -// -// No guard (the default) changes nothing: no call is made and no check is -// added. -type ShareGuard interface { - Begin(ctx context.Context, vol string) (token string, err error) - Finish(ctx context.Context, vol, token string, head storage.ChunkHead) error -} - -// SetShareGuard installs g (nil removes it). Set it before the catalog is -// used. -func (c *Catalog) SetShareGuard(g ShareGuard) { c.guard = g } - -// ShareGuard returns the installed guard, or nil. -func (c *Catalog) ShareGuard() ShareGuard { return c.guard } - -// beginShare starts a share of vol's chunks for a caller that passes the -// HEAD in: with a guard, it begins the share, then refuses unless head is -// still vol's current HEAD (a share that obtained an older HEAD could -// reference chunks superseded meanwhile). token is "" without a guard. -func (c *Catalog) beginShare(ctx context.Context, vol string, head storage.ChunkHead) (token string, err error) { - if c.guard == nil { - return "", nil - } - token, err = c.guard.Begin(ctx, vol) - if err != nil { - return "", remoteErr(err, "share guard for %s", vol) - } - cur, ok, err := c.ReadHead(ctx, vol) - if err != nil { - return "", err - } - if !ok || cur.Gen != head.Gen || cur.Epoch != head.Epoch { - return "", catErr(CodeOutcomeUnknown, true, nil, "volume %s: the HEAD to share (gen %d) is no longer current (gen %d); retry", vol, head.Gen, cur.Gen) - } - return token, nil -} - -// finishShare finishes a share before its result is activated; no-op -// without a guard. -func (c *Catalog) finishShare(ctx context.Context, vol, token string, head storage.ChunkHead) error { - if c.guard == nil { - return nil - } - if err := c.guard.Finish(ctx, vol, token, head); err != nil { - return remoteErr(err, "share guard for %s refused the share", vol) - } - return nil -} diff --git a/seaweed-block/core/frontend/chunkstore/share_guard_test.go b/seaweed-block/core/frontend/chunkstore/share_guard_test.go deleted file mode 100644 index a0f7661520..0000000000 --- a/seaweed-block/core/frontend/chunkstore/share_guard_test.go +++ /dev/null @@ -1,204 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "fmt" - "strings" - "sync" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// recGuard records Begin and Finish; onFinish runs inside Finish. -type recGuard struct { - mu sync.Mutex - events []string - n int - finishErr error - beginErr error - onFinish func() -} - -func (g *recGuard) Begin(_ context.Context, vol string) (string, error) { - g.mu.Lock() - defer g.mu.Unlock() - g.n++ - g.events = append(g.events, "begin:"+vol) - if g.beginErr != nil { - return "", g.beginErr - } - return fmt.Sprintf("tok-%d", g.n), nil -} - -func (g *recGuard) Finish(_ context.Context, vol, token string, head storage.ChunkHead) error { - if g.onFinish != nil { - g.onFinish() - } - g.mu.Lock() - defer g.mu.Unlock() - g.events = append(g.events, fmt.Sprintf("finish:%s:%s:%d", vol, token, head.Gen)) - return g.finishErr -} - -func (g *recGuard) list() []string { - g.mu.Lock() - defer g.mu.Unlock() - return append([]string(nil), g.events...) -} - -func countUnder(f *fakeFiler, prefix string) int { - f.mu.Lock() - defer f.mu.Unlock() - n := 0 - for k := range f.entries { - if strings.HasPrefix(k, prefix) { - n++ - } - } - return n -} - -// A snapshot of a passed-in HEAD begins the share, checks the HEAD is still -// current, and finishes it before the snapshot entry is written. -func TestShareGuard_SnapshotFinishesBeforeActivation(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - g := &recGuard{} - g.onFinish = func() { - if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { - t.Errorf("snapshot entry written before Finish (%d entries)", n) - } - } - c.SetShareGuard(g) - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - want := []string{"begin:v1", fmt.Sprintf("finish:v1:tok-1:%d", h.Gen)} - if got := g.list(); len(got) != 2 || got[0] != want[0] || got[1] != want[1] { - t.Fatalf("guard events %v; want %v", got, want) - } - if countUnder(f, catBase+"/v1/snaps/s1/") == 0 { - t.Fatal("snapshot not written after a successful Finish") - } -} - -// A refused Finish aborts the snapshot: nothing activated, its intent dropped. -func TestShareGuard_RefusedFinishAbortsTheSnapshot(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - intents := countUnder(f, catBase+"/v1/intents/") - c.SetShareGuard(&recGuard{finishErr: errors.New("token expired")}) - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { - t.Fatal("snapshot activated after a refused Finish") - } - if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { - t.Fatalf("%d snapshot entries after a refused Finish", n) - } - if n := countUnder(f, catBase+"/v1/intents/"); n != intents { - t.Fatalf("intents %d -> %d; want the snapshot's intent dropped", intents, n) - } -} - -// A passed-in HEAD that is no longer current is refused before Finish. -func TestShareGuard_StaleHeadIsRefused(t *testing.T) { - f, b, c, h := catalogFixture(t) - ctx := context.Background() - publishSource(t, f, b, "v1", map[uint64][]byte{5: chunkBytes(0x20)}) // HEAD moves on - g := &recGuard{} - c.SetShareGuard(g) - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { - t.Fatal("snapshot of a superseded HEAD accepted with a guard") - } - for _, e := range g.list() { - if strings.HasPrefix(e, "finish:") { - t.Fatalf("Finish called for a refused share: %v", g.list()) - } - } - if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { - t.Fatalf("%d snapshot entries for a refused share", n) - } -} - -// A caller that began the share itself passes its token: no second Begin. -func TestShareGuard_CallerToken(t *testing.T) { - _, _, c, h := catalogFixture(t) - g := &recGuard{} - c.SetShareGuard(g) - if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r", ShareToken: "owner-tok"}, h); err != nil { - t.Fatal(err) - } - if got := g.list(); len(got) != 1 || got[0] != fmt.Sprintf("finish:v1:owner-tok:%d", h.Gen) { - t.Fatalf("guard events %v; want only Finish with the caller's token", got) - } -} - -// A fork begins the share before reading the snapshot and finishes it with -// the snapshot's HEAD before writing the child's HEAD; a refused Finish -// writes no child HEAD. -func TestShareGuard_Fork(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - g := &recGuard{} - g.onFinish = func() { - if countUnder(f, catBase+"/v2/HEAD") != 0 { - t.Error("child HEAD written before Finish") - } - } - c.SetShareGuard(g) - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"}); err != nil { - t.Fatal(err) - } - want := []string{"begin:v1", fmt.Sprintf("finish:v1:tok-1:%d", h.Gen)} - if got := g.list(); len(got) != 2 || got[0] != want[0] || got[1] != want[1] { - t.Fatalf("guard events %v; want %v", got, want) - } - - c.SetShareGuard(&recGuard{finishErr: errors.New("token expired")}) - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "fork-2"}); err == nil { - t.Fatal("fork activated after a refused Finish") - } - if countUnder(f, catBase+"/v3/HEAD") != 0 { - t.Fatal("child HEAD written after a refused Finish") - } - if n := countUnder(f, catBase+"/v3/intents/"); n != 0 { - t.Fatalf("%d intents left for the refused fork; want its new intent dropped", n) - } -} - -// A refused Begin stops the snapshot and the fork before anything is -// written: no Finish, no snapshot entry, no child HEAD, no intent left. -func TestShareGuard_BeginRefused(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s0", RequestID: "r0"}, h); err != nil { - t.Fatal(err) - } - intents := countUnder(f, catBase+"/v1/intents/") - g := &recGuard{beginErr: errors.New("share refused")} - c.SetShareGuard(g) - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { - t.Fatal("snapshot after a refused Begin") - } - if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { - t.Fatalf("%d snapshot entries after a refused Begin", n) - } - if n := countUnder(f, catBase+"/v1/intents/"); n != intents { - t.Fatalf("intents %d -> %d after a refused Begin", intents, n) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s0", Target: "v4", RequestID: "fork-b"}); err == nil { - t.Fatal("fork after a refused Begin") - } - if countUnder(f, catBase+"/v4/HEAD") != 0 || countUnder(f, catBase+"/v4/intents/") != 0 { - t.Fatal("a fork refused at Begin wrote a child HEAD or an intent") - } - for _, e := range g.list() { - if strings.HasPrefix(e, "finish:") { - t.Fatalf("Finish after a refused Begin: %v", g.list()) - } - } -} diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go deleted file mode 100644 index d1c9eda111..0000000000 --- a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go +++ /dev/null @@ -1,208 +0,0 @@ -package chunkstore - -import ( - "bytes" - "context" - "fmt" - "path" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// INV-SNAP-DELETE-ANY-ORDER-001: forks and restores do not hold their parent. - -// A fork stopped past its deadline does not keep its parent: the snapshot is -// deleted, and a retry of the same request reads the parent again and is -// refused; it never publishes from its first read. -func TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent(t *testing.T) { - f, _, c, h := catalogFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} - clock := time.Now() - c.SetClock(func() time.Time { return clock }) - f.beforeCreate = func(p string) { - if p == catBase+"/v2/VOLUME" { - clock = clock.Add(DefaultOpDeadline) - } - } - if _, err := c.Fork(ctx, req); CodeOf(err) != CodeDeadlineExceeded { - t.Fatalf("fork past its deadline: %v, want deadline_exceeded", err) - } - f.beforeCreate = nil - if _, ok, err := c.ReadVolume(ctx, "v2"); !ok || err != nil { - t.Fatalf("the stopped fork's VOLUME: ok=%v %v", ok, err) - } - if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { - t.Fatalf("delete the parent of an incomplete fork: %q %v, want deleting", got, err) - } - _, err := c.Fork(ctx, req) - if code := CodeOf(err); code != CodeSnapshotNotFound && code != CodeSnapshotDeleting { - t.Fatalf("retry after the parent was deleted: %v, want snapshot_not_found or snapshot_deleting", err) - } - if _, err := f.LookupEntry(ctx, catBase+"/v2", headName); err == nil { - t.Fatal("the retry published a HEAD from its first read of a deleted parent") - } -} - -// A delete that lands between a fork's read of its parent and its HEAD -// publish succeeds; the fork still publishes inside its deadline, and the -// target keeps every chunk after the source snapshot and volume are gone and -// GC has run past its grace. -func TestSnapshotDelete_DeleteDuringAForkInFlight(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - want := map[uint64][]byte{0: chunkBytes(0x41), 2: chunkBytes(0x42)} - h := publishSource(t, f, b.fakeBlobs, "v1", want) - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - deleted := false - f.stallCreate = func(p string) bool { // runs before the fake takes its lock - if p == catBase+"/v2/"+headName && !deleted { - deleted = true - if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { - t.Errorf("delete while the fork is in flight: %q %v", got, err) - } - } - return false - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork whose parent was deleted after its read: %v", err) - } - f.stallCreate = nil - if !deleted { - t.Fatal("the delete never ran inside the fork") - } - detachHead(t, f, b.fakeBlobs, "v1") - if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { - t.Fatalf("delete the source volume: %v", err) - } - for i := 0; i < 3; i++ { - if _, err := g.Run(ctx); err != nil { - t.Fatalf("gc: %v", err) - } - *now = now.Add(2 * time.Hour) - } - r2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) - h2, err := r2.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - requireChunks(t, ctx, r2, h2, want, "fork") -} - -// An unknown publish outcome keeps the fork's intent, and that intent roots -// the parent's keys with no time bound: the snapshot deleted, the source -// volume deleted, GC run well past its grace, the keys survive while the -// intent exists. -func TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists(t *testing.T) { - f, b, c, g, now := gcFixture(t) - ctx := context.Background() - want := map[uint64][]byte{0: chunkBytes(0x51), 1: chunkBytes(0x52)} - h := publishSource(t, f, b.fakeBlobs, "v1", want) - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - f.failCreate = func(p string) error { - if p == catBase+"/v2/"+headName { - return errTransport - } - return nil - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with an unknown HEAD create: %v", err) - } - f.failCreate = nil - if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { - t.Fatalf("delete the parent: %q %v", got, err) - } - detachHead(t, f, b.fakeBlobs, "v1") - if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { - t.Fatalf("delete the source volume: %v", err) - } - intents := func() int { - list, err := f.ListEntries(ctx, path.Join(catBase, "v2", intentsDir), "", "", 0) - if err != nil { - t.Fatal(err) - } - return len(list) - } - if intents() == 0 { - t.Fatal("the unknown publish left no intent") - } - for i := 0; i < 4; i++ { - if _, err := g.Run(ctx); err != nil { - t.Fatalf("gc: %v", err) - } - *now = now.Add(2 * time.Hour) // far past the grace - } - if intents() == 0 { - t.Fatal("GC settled the fork intent without the target being resolved") - } - r1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - requireChunks(t, ctx, r1, h, want, "parent (fork intent still present)") -} - -// requireChunks fails unless h names exactly the indexes of want and each one -// reads back want's bytes (a missing index cannot pass by iterating h alone). -func requireChunks(t *testing.T, ctx context.Context, r *ChunkRemote, h storage.ChunkHead, want map[uint64][]byte, what string) { - t.Helper() - if err := chunksMismatch(ctx, r, h, want); err != nil { - t.Fatalf("%s: %v", what, err) - } -} - -func chunksMismatch(ctx context.Context, r *ChunkRemote, h storage.ChunkHead, want map[uint64][]byte) error { - if len(h.Chunks) != len(want) { - return fmt.Errorf("HEAD names %d chunks, want %d", len(h.Chunks), len(want)) - } - for idx, data := range want { - ref, ok := h.Chunks[idx] - if !ok { - return fmt.Errorf("HEAD lost chunk %d", idx) - } - if got, err := r.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, data) { - return fmt.Errorf("chunk %d unreadable or changed: %v", idx, err) - } - } - return nil -} - -// The check refuses a HEAD that lost an index, even when every chunk it -// still names reads back correctly. -func TestSnapshotDelete_ChunkCheckCatchesAMissingIndex(t *testing.T) { - f, b, _, h := catalogFixture(t) - ctx := context.Background() - r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) - want := map[uint64][]byte{} - missing := uint64(0) - for idx, ref := range h.Chunks { - data, err := r.Get(ctx, ref.Key) - if err != nil { - t.Fatal(err) - } - want[idx] = data - if idx >= missing { - missing = idx + 1 - } - } - if err := chunksMismatch(ctx, r, h, want); err != nil { - t.Fatalf("the matching HEAD failed the check: %v", err) - } - want[missing] = chunkBytes(0x62) // an index the HEAD does not name - if err := chunksMismatch(ctx, r, h, want); err == nil { - t.Fatal("a HEAD missing an expected chunk passed the check") - } -} diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_info_b.go b/seaweed-block/core/frontend/chunkstore/snapshot_info_b.go new file mode 100644 index 0000000000..61259683ad --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/snapshot_info_b.go @@ -0,0 +1,16 @@ +package chunkstore + +import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + +// SnapshotInfoFromHead is a snapshot request's answer from HEAD's record +// of the name: its root, cut position, dependents and retention facts (as +// recorded when it was named, so a replay after later cuts answers the +// same), and the HEAD that holds it. +func SnapshotInfoFromHead(volumeID, name string, h layout.Head) SnapshotInfo { + s := h.Snapshots[name] + return SnapshotInfo{ + VolumeID: volumeID, Name: name, Root: s.Root.String(), Dependents: s.Dependents, + HeadGen: h.Gen, HeadEpoch: h.Epoch, CutLSN: s.Position, State: SnapActive, + Class: s.Meta.Class, CreatedNs: s.Meta.CreatedNs, ExpiresAtNs: s.Meta.ExpiresNs, Labels: s.Meta.Labels, + } +} diff --git a/seaweed-block/core/frontend/chunkstore/start_any_test.go b/seaweed-block/core/frontend/chunkstore/start_any_test.go new file mode 100644 index 0000000000..e61edc6976 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/start_any_test.go @@ -0,0 +1,7 @@ +package chunkstore + +import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + +// anyStart is a local root that can start from any HEAD: these tests do +// not model the local store. +func anyStart(layout.Head) error { return nil } diff --git a/seaweed-block/core/frontend/chunkstore/swfs.go b/seaweed-block/core/frontend/chunkstore/swfs.go index f206db5fd8..bc469c91e4 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs.go +++ b/seaweed-block/core/frontend/chunkstore/swfs.go @@ -169,13 +169,14 @@ func (c *SWFS) ListEntries(ctx context.Context, dir, prefix, startAfter string, } } -// DeleteEntry implements Filer. It never deletes data or recurses. A failed +// DeleteEntry implements Filer. The filer reclaims the file's chunks; the +// request never recurses. A failed // expected_extended (including a missing entry) comes back as gRPC // FailedPrecondition; other failures are a gRPC error or the response's // Error string, and are returned unwrapped from the sentinels. func (c *SWFS) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { resp, err := c.fc.DeleteEntry(ctx, &filerpb.DeleteEntryRequest{ - Directory: dir, Name: name, IsDeleteData: false, IsRecursive: false, ExpectedExtended: expected, + Directory: dir, Name: name, IsDeleteData: true, IsRecursive: false, ExpectedExtended: expected, }) if err != nil { if status.Code(err) == codes.FailedPrecondition { @@ -342,6 +343,10 @@ var ( _ Blobs = (*SWFS)(nil) ) +// ErrBlobDeleteRejected identifies a definite per-object refusal (HTTP 400). +// It never proves the needle absent. +var ErrBlobDeleteRejected = errors.New("chunkstore: blob DELETE rejected") + // DeleteBlob removes an immutable needle from every resolved replica. A // partial/unknown result is an error, so GC retains its binding tombstone // and retries later; no response body is used to infer success. diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch_integration_test.go b/seaweed-block/core/frontend/chunkstore/swfs_batch_integration_test.go index 744fcf5551..dffd9e4dc3 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_batch_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch_integration_test.go @@ -68,41 +68,3 @@ func TestIntegrationBatch_JWTNativeOffsets(t *testing.T) { t.Fatalf("upload to the arithmetic fid %s with the base token: %v; want a rejected token", arith, err) } } - -// A round of more than one group writes through real assigns, binds every -// key, and reads every key back; it takes one assign per group. -func TestIntegrationBatch_RoundBindsAndReadsBack(t *testing.T) { - c := startWeedWith(t, jwtSecurity) - cl := c.client(t, "/swblock/vols/v1") - r, err := NewChunkRemote(cl, cl, "/swblock/vols/v1") - if err != nil { - t.Fatal(err) - } - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) - defer cancel() - const n = 130 // three groups - rd := r.BeginPutRound(n, 4096) - for i := 0; i < n; i++ { - if err := rd.Put(ctx, i, roundKey(i), []byte(roundKey(i))); err != nil { - t.Fatalf("object %d: %v", i, err) - } - } - for i := 0; i < n; i++ { - got, err := r.Get(ctx, roundKey(i)) - if err != nil || !bytes.Equal(got, []byte(roundKey(i))) { - t.Fatalf("key %d read back %q, %v", i, got, err) - } - } - if a := r.AssignCounts(); a.Initial != 3 || a.Extra() != 0 { - t.Fatalf("assign counts %+v; want 3 initial", a) - } - suffixed := 0 - for i := 0; i < n; i++ { - if strings.Contains(r.fids[roundKey(i)], "_") { - suffixed++ - } - } - if suffixed != n-3 { - t.Fatalf("%d of %d bindings use an offset fid; want all but the 3 bases", suffixed, n) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go b/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go index fa0572a17d..2f89fb3c73 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_batch_test.go @@ -192,20 +192,6 @@ func TestSWFSRange_ReserveValidates(t *testing.T) { t.Fatalf("reserve %d: offset %d gave %q", n, n, fid) } } - // A rejected location leaves nothing to upload to: a round over it makes - // no upload at all. - vol := newBatchVolume(t) - bad := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 2, Location: &filerpb.Location{Url: vol.host() + "\t"}}}) - rr, err := NewChunkRemote(newFakeFiler(), bad, "/swblock/vols/v1") - if err != nil { - t.Fatal(err) - } - if err := rr.BeginPutRound(2, 4096).Put(context.Background(), 0, "k00000", []byte("x")); err == nil { - t.Fatal("round over a malformed location stored an object") - } - if uploads, _, _ := vol.snapshot(); len(uploads) != 0 { - t.Fatalf("uploads %v after a malformed location", uploads) - } s := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 1, Location: loc}}) for _, n := range []int{0, -1, maxRangeCount + 1} { if _, err := s.reserve(context.Background(), n, 4096); err == nil { diff --git a/seaweed-block/core/frontend/chunkstore/swfs_catalog.go b/seaweed-block/core/frontend/chunkstore/swfs_catalog.go new file mode 100644 index 0000000000..28bcfa268f --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/swfs_catalog.go @@ -0,0 +1,22 @@ +package chunkstore + +import "context" + +// DialBCatalog gives master creation and blockvolume attachment the same +// single-filer check, storage rule, and catalog path. +func DialBCatalog(ctx context.Context, cfg SWFSConfig) (*BCatalog, *SWFS, error) { + client, err := DialSWFS(cfg) + if err != nil { + return nil, nil, err + } + if err := client.CheckSingleFiler(ctx); err != nil { + _ = client.Close() + return nil, nil, err + } + cat, err := NewBCatalog(client, client, cfg.AssignPath) + if err != nil { + _ = client.Close() + return nil, nil, err + } + return cat, client, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/swfs_flags.go b/seaweed-block/core/frontend/chunkstore/swfs_flags.go new file mode 100644 index 0000000000..e887a0391c --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/swfs_flags.go @@ -0,0 +1,14 @@ +package chunkstore + +import "flag" + +// DefaultChunkPath is the filer directory shared by master creation and +// blockvolume attachment. Both commands register the same storage flags. +const DefaultChunkPath = "/swblock/chunks" + +func RegisterSWFSFlags(fs *flag.FlagSet, filer, path, collection, replication *string) { + fs.StringVar(filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + fs.StringVar(path, "chunk-path", DefaultChunkPath, "filer directory holding one directory per volume") + fs.StringVar(collection, "chunk-collection", "", "collection for chunk needles (empty = filer default / storage rule)") + fs.StringVar(replication, "chunk-replication", "", "replication for chunk needles (empty = filer default / storage rule)") +} diff --git a/seaweed-block/core/frontend/chunkstore/swfs_list_delete_test.go b/seaweed-block/core/frontend/chunkstore/swfs_list_delete_test.go index 670f12e7bd..e7aca3c5d0 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_list_delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_list_delete_test.go @@ -117,8 +117,8 @@ func TestSWFS_DeleteEntry_ConditionalStyles(t *testing.T) { t.Fatalf("ok delete: %v", err) } r := f.lastDelete - if r.Directory != "/d" || r.Name != "x" || r.IsDeleteData || r.IsRecursive || string(r.ExpectedExtended["swb.snap.state"]) != "deleting" { - t.Fatalf("request %+v: want no data delete, not recursive, expected_extended sent", r) + if r.Directory != "/d" || r.Name != "x" || !r.IsDeleteData || r.IsRecursive || string(r.ExpectedExtended["swb.snap.state"]) != "deleting" { + t.Fatalf("request %+v: want filer-owned data deletion, not recursive, expected_extended sent", r) } // The filer reports a failed precondition, including a missing entry, as diff --git a/seaweed-block/core/frontend/chunkstore/usage.go b/seaweed-block/core/frontend/chunkstore/usage.go deleted file mode 100644 index 472c1ed877..0000000000 --- a/seaweed-block/core/frontend/chunkstore/usage.go +++ /dev/null @@ -1,282 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "net/url" - "path" - "sort" - "strings" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Space accounting. Everything is -// computed from manifests and filer listings; segment objects are verified, -// but data chunks are not read. -// -// A chunk's bytes are ChunkBlocks x BlockSize, the last chunk clipped to -// NumBlocks (ChunkRef carries no size). -// -// - LiveBytes: the chunks HEAD references. -// - per snapshot, ExclusiveBytes: the chunks that snapshot references -// and no other holder does, where the holders are this volume's HEAD -// and live snapshots AND every other volume's HEAD and live snapshots -// (a fork's "@owner/key" references are resolved to the owner's -// chunk). These are the bytes deleting that snapshot makes eligible -// for GC; GC still keeps them through its grace period and while any -// in-flight intent names them, so they are not reclaimed at once. -// - StoredBytes: the volume's chunk-key bindings in the filer (what is -// stored now, referenced or not). A binding a manifest references is -// counted at its exact (clipped) size; any other binding at the full -// chunk size, so StoredBytes is an upper bound whenever -// StoredUpperBound is set. -// -// "Bytes uploaded since creation" needs a counter nothing records today (a -// follow-up). The unreferenced-not-yet-collected bytes come from GC's -// preview once that lands (#140). - -// SnapshotUsage is one snapshot's share of a volume's space. -type SnapshotUsage struct { - Name string `json:"name"` // the snapshot name - CreatedNs int64 `json:"createdNs"` // when it was created (Unix ns) - Class string `json:"class"` // its retention class - Pinned bool `json:"pinned"` // retention never deletes it - Chunks int `json:"chunks"` // chunks its manifest references - ExclusiveBytes uint64 `json:"exclusiveBytes"` // bytes no other holder references: what deleting it makes eligible for GC -} - -// VolumeUsage is a volume's space accounting. -type VolumeUsage struct { - VolumeID string `json:"volumeID"` // the volume - ChunkBytes uint64 `json:"chunkBytes"` // one full chunk - LiveChunks int `json:"liveChunks"` // chunks HEAD references - LiveBytes uint64 `json:"liveBytes"` // their bytes (the last chunk clipped) - Snapshots []SnapshotUsage `json:"snapshots"` // one entry per live snapshot - ManifestBindings int `json:"manifestBindings"` // stored chunk-key bindings some manifest references - ManifestBytes uint64 `json:"manifestBytes"` // their exact bytes - StoredBindings int `json:"storedBindings"` // all chunk-key bindings in the filer, referenced or not - StoredBytes uint64 `json:"storedBytes"` // their bytes; unreferenced ones counted at full chunk size - StoredUpperBound bool `json:"storedUpperBound"` // StoredBytes is an upper bound (some bindings are unreferenced) - Policy RetentionPolicy `json:"policy"` // the snapshot retention policy in force - PolicySet bool `json:"policySet"` // the volume set its own policy (else the default applies) -} - -// chunkSize is the byte size of chunk index idx under g. -func chunkSize(g Geometry, idx uint64) uint64 { - full := uint64(g.ChunkBlocks) * uint64(g.BlockSize) - if g.ChunkBlocks == 0 { - return 0 - } - first := idx * uint64(g.ChunkBlocks) - if first >= g.NumBlocks { - return 0 - } - if rest := g.NumBlocks - first; rest < uint64(g.ChunkBlocks) { - return rest * uint64(g.BlockSize) - } - return full -} - -// Usage computes vol's space accounting. -func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) { - v, ok, err := c.ReadVolume(ctx, vol) - if err != nil { - return VolumeUsage{}, err - } - if !ok { - return VolumeUsage{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol) - } - g := v.Geometry - u := VolumeUsage{VolumeID: vol, ChunkBytes: uint64(g.ChunkBlocks) * uint64(g.BlockSize), Snapshots: []SnapshotUsage{}} - if u.Policy, u.PolicySet, err = c.ReadRetentionPolicy(ctx, vol); err != nil { - return VolumeUsage{}, err - } - - head, _, err := c.ReadHead(ctx, vol) - if err != nil { - return VolumeUsage{}, err - } - snaps, err := c.allSnapshots(ctx, vol) - if err != nil { - return VolumeUsage{}, err - } - - head, err = c.usageHead(ctx, vol, head) - if err != nil { - return VolumeUsage{}, err - } - for i := range snaps { - snaps[i].head, err = c.usageHead(ctx, vol, snaps[i].head) - if err != nil { - return VolumeUsage{}, err - } - } - // holders counts, per chunk identity (owner volume + key), how many - // HEADs and live snapshots of any volume reference it; size is each - // identity's byte size as this volume's geometry indexes it. - holders := map[string]int{} - size := map[string]uint64{} - addHolder := func(owner string, h storage.ChunkHead, sized bool) { - seen := map[string]bool{} - for idx, ref := range h.Chunks { - id := chunkIdentity(owner, ref.Key) - if sized { - size[id] = chunkSize(g, idx) - } - if !seen[id] { - seen[id] = true - holders[id]++ - } - } - } - addHolder(vol, head, true) - for idx := range head.Chunks { - u.LiveChunks++ - u.LiveBytes += chunkSize(g, idx) - } - for _, s := range snaps { - addHolder(vol, s.Head(), true) - } - others, err := c.ListVolumes(ctx) - if err != nil { - return VolumeUsage{}, err - } - for _, other := range others { - if other == vol { - continue - } - oh, has, err := c.ReadHead(ctx, other) - if err != nil { - return VolumeUsage{}, err - } - if has { - oh, err = c.usageHead(ctx, other, oh) - if err != nil { - return VolumeUsage{}, err - } - addHolder(other, oh, false) - } - osnaps, err := c.allSnapshots(ctx, other) - if err != nil { - return VolumeUsage{}, err - } - for _, s := range osnaps { - otherHead, err := c.usageHead(ctx, other, s.Head()) - if err != nil { - return VolumeUsage{}, err - } - addHolder(other, otherHead, false) - } - } - for _, s := range snaps { - su := SnapshotUsage{Name: s.Name, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: s.Pinned(), Chunks: len(s.Head().Chunks)} - seen := map[string]bool{} - for _, ref := range s.Head().Chunks { - id := chunkIdentity(vol, ref.Key) - if seen[id] { - continue - } - seen[id] = true - if holders[id] == 1 { - su.ExclusiveBytes += size[id] - } - } - u.Snapshots = append(u.Snapshots, su) - } - sort.Slice(u.Snapshots, func(i, j int) bool { - if u.Snapshots[i].CreatedNs != u.Snapshots[j].CreatedNs { - return u.Snapshots[i].CreatedNs > u.Snapshots[j].CreatedNs - } - return u.Snapshots[i].Name < u.Snapshots[j].Name - }) - - // Stored: this volume's own chunk-key bindings. - r, err := NewChunkRemote(c.f, nilBlobs{}, path.Join(c.base, vol)) - if err != nil { - return VolumeUsage{}, err - } - after := "" - for { - page, err := c.f.ListEntries(ctx, r.keyDir(), "", after, listPage) - if err != nil { - return VolumeUsage{}, remoteErr(err, "list the chunk keys of %s", vol) - } - for _, e := range page { - if e.GetName() <= after { - return VolumeUsage{}, errors.New("chunkstore: non-advancing chunk key listing") - } - after = e.GetName() - if e.GetIsDirectory() || string(e.Extended[extKind]) != kindChunkKey { - continue - } - key, err := url.PathUnescape(e.GetName()) - if err != nil || strings.HasPrefix(key, "@") { - continue - } - u.StoredBindings++ - if string(e.Extended["swb.object"]) == "segment" { - if e.Attributes == nil || e.Attributes.FileSize == 0 || e.Attributes.FileSize > maxManifestBytes { - return VolumeUsage{}, errors.New("chunkstore: invalid manifest binding size") - } - u.ManifestBindings++ - u.ManifestBytes += e.Attributes.FileSize - u.StoredBytes += e.Attributes.FileSize - continue - } - - if n, ok := size[chunkIdentity(vol, key)]; ok { - u.StoredBytes += n - } else { - u.StoredBytes += u.ChunkBytes - u.StoredUpperBound = true - } - } - if len(page) < listPage { - return u, nil - } - } -} - -// chunkIdentity names the chunk a ref in volume vol points at: an -// owner-qualified "@owner/key" (a fork's reference) is owner's key, -// anything else is vol's. -func chunkIdentity(vol, key string) string { - if strings.HasPrefix(key, "@") { - if owner, rest, ok := strings.Cut(key[1:], "/"); ok { - return owner + "\x00" + rest - } - } - return vol + "\x00" + key -} - -func (c *Catalog) usageHead(ctx context.Context, vol string, h storage.ChunkHead) (storage.ChunkHead, error) { - if h.Segments == nil { - return h, nil - } - var blobs Blobs = c.blobs - if blobs == nil { - return h, errors.New("chunkstore: usage segment reader unavailable") - } - r, err := NewChunkRemote(c.f, blobs, path.Join(c.base, vol)) - if err != nil { - return h, err - } - resolved, err := r.resolveManifest(ctx, h) - if err != nil { - return h, err - } - v, ok, err := c.ReadVolume(ctx, vol) - if err != nil { - return h, err - } - if !ok || h.ChunkBytes != uint64(v.Geometry.ChunkBlocks)*uint64(v.Geometry.BlockSize) { - return h, errors.New("chunkstore: usage manifest/volume geometry mismatch") - } - for idx := range resolved.Chunks { - if idx >= (v.Geometry.NumBlocks+uint64(v.Geometry.ChunkBlocks)-1)/uint64(v.Geometry.ChunkBlocks) { - return h, errors.New("chunkstore: usage chunk outside volume") - } - } - return resolved, nil -} diff --git a/seaweed-block/core/frontend/chunkstore/verify.go b/seaweed-block/core/frontend/chunkstore/verify.go deleted file mode 100644 index 0c11116d75..0000000000 --- a/seaweed-block/core/frontend/chunkstore/verify.go +++ /dev/null @@ -1,1633 +0,0 @@ -package chunkstore - -// Verify: a read-only check of one volume's remote image against what its -// HEAD (and, on request, its snapshots) say. It writes nothing to the filer -// or the blob store: no intent, no mark, no tombstone, no binding. -// -// Depths, each including the one before: -// -// - meta: the HEAD root decodes and is self-consistent; its geometry -// matches VOLUME; a snapshot's document names the volume and the -// snapshot it was found under; every segment a selected root names is -// readable and passes its SHA-256 and strict decode; a fork's record -// matches the parent snapshot it was made from. References to one -// chunk with different SHA-256s disagree (CONTENT_MISMATCH). -// - bindings (the default): every chunk key a selected root references -// has a sound binding in its owner's keys/ (one listing per owner), -// not tombstoned by GC. -// - data: every distinct chunk (owner + key, across all selected roots) -// is fetched once; its length must be the chunk size and its SHA-256 -// each reference's (the rule the chunk layer applies on a read miss). -// -// The pass runs beside a live owner and beside GC, so what it reports about -// chunks comes from a small automaton (the V.* names on the functions): -// -// - V.Discover: an object (a chunk or a segment, by owner and key) a root -// view names that the pass has not seen is queued for one check; every -// reference met is recorded as seen, with nothing judged about it. -// - V.Settle: the check records the object's one outcome (its content, or -// binding missing or tombstoned, needle missing, read error) and reports -// nothing; a settled object is never checked again. -// - V.Refresh: HEAD is read again at least every RefreshInterval; a newer -// generation replaces the HEAD view (an older one is ignored), the keys -// the old view named and the new one does not are marked dropped, and -// its new keys are discovered. -// - V.Round: once every queued chunk is settled, one closing read of HEAD -// and of each selected snapshot's state; if it names a chunk not seen, -// the pass checks it and reads again, at most ClosingRounds times -// (V.GiveUp: then the pass is incomplete). -// - V.Close: a closing read that names no chunk not seen is the final view. -// Only a decodable HEAD, not older than the view, can close a pass as -// complete: a closing read that finds no HEAD, or one that does not -// decode (ROOT_INVALID), leaves no HEAD root and the pass incomplete. -// - V.Reconcile: the findings and counters are computed from the outcomes, -// the references seen and the final view alone, nowhere else. Judge, a -// pure function of an object's outcome and one reference, gives the -// outcome when it is bad, else CONTENT_MISMATCH (another hash), -// SIZE_MISMATCH (a chunk not a chunk long) or SEGMENT_UNREADABLE (a -// segment that does not decode under that reference's fields), else -// sound. Per object and class Judge gives a final reference: one finding, -// under the first final root having one (HEAD, then the snapshots not -// gone, in order) at its first such index. An object with a problem -// under any reference seen, and no finding, is counted once. A key HEAD -// dropped and names again is ROOT_INVALID, whatever its outcome. -// -// The pass therefore reports the state of each named chunk at its check, -// for the roots at the final read; a chunk damaged after its check is the -// next pass's finding. A chunk that left HEAD can be collected after GC's -// grace, and a deleted snapshot's chunks are kept only for the grace, so an -// object that no root names at the final read is not a finding. -// -// A needle is NEEDLE_MISSING only when the store reports it absent -// (ErrBlobNotFound). Any other read failure is retried; if it persists it is -// READ_ERROR, which means "not verified", not "damaged". -// -// A finding never stops the pass. Only an inability to continue does (the -// context ended, the filer failed) or a HEAD that keeps naming new chunks: -// Verify then returns the result with Complete false and the reason in -// Incomplete, the findings computed from what was checked, and the error. - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "errors" - "fmt" - "path" - "sort" - "strings" - "sync" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// VerifyDepth selects how far Verify checks. -type VerifyDepth string - -const ( - VerifyMeta VerifyDepth = "meta" - VerifyBindings VerifyDepth = "bindings" - VerifyData VerifyDepth = "data" -) - -const ( - // DefaultVerifyConcurrency bounds the chunk reads in flight. - DefaultVerifyConcurrency = 2 - // DefaultVerifyBytesPerSecond paces chunk reads. - DefaultVerifyBytesPerSecond int64 = 32 << 20 - // DefaultVerifyRefresh is the longest a pass works from one HEAD view; - // it stays below the operation deadline, the shortest time a chunk - // that just left HEAD is still guaranteed to be kept by GC. - DefaultVerifyRefresh = 2 * time.Minute - // DefaultVerifyIntentStaleAge is the age past which a capture intent - // below HEAD's epoch is reported as stale (the gc --intent-ttl default). - DefaultVerifyIntentStaleAge = time.Hour - // DefaultVerifyClosingRounds is the default ClosingRounds. - DefaultVerifyClosingRounds = 3 -) - -// Finding classes. -const ( - FindingRootInvalid = "ROOT_INVALID" - FindingGeometry = "GEOMETRY" - FindingSegmentUnreadable = "SEGMENT_UNREADABLE" - FindingBindingMissing = "BINDING_MISSING" - FindingBindingTombstoned = "BINDING_TOMBSTONED" - FindingNeedleMissing = "NEEDLE_MISSING" - FindingContentMismatch = "CONTENT_MISMATCH" - FindingSizeMismatch = "SIZE_MISMATCH" - FindingForkRecordMismatch = "FORK_RECORD_MISMATCH" - FindingIntentStale = "INTENT_STALE" - // FindingReadError is not proof of damage: a needle (chunk or segment) - // could not be read for a reason other than the store reporting it - // absent, after retries. That object was not verified; re-run. - FindingReadError = "READ_ERROR" -) - -// A read the store does not answer with "not found" is tried this many -// times in all, the retries spaced by verifyRetryBackoff times the attempt. -const verifyReadAttempts = 3 - -var verifyRetryBackoff = 50 * time.Millisecond - -// VerifyOptions configures a Verify pass. Zero values take the defaults. -type VerifyOptions struct { - // Depth is meta, bindings (default) or data. - Depth VerifyDepth - // Snapshot adds the named snapshot to the roots checked; AllSnapshots - // adds every published snapshot not marked deleting. HEAD is always - // checked. At most one of the two may be set. - Snapshot string - AllSnapshots bool - // Concurrency bounds the chunk reads in flight (depth data). - Concurrency int - // BytesPerSecond paces chunk reads: 0 is the default, a negative value - // leaves them unpaced. - BytesPerSecond int64 - // RefreshInterval is the longest the pass works from one HEAD view. - RefreshInterval time.Duration - // IntentStaleAge is the age past which a capture intent below HEAD's - // epoch that names no key HEAD references is reported (a hint only). - IntentStaleAge time.Duration - // ClosingRounds bounds the closing reads that may name chunks not seen - // before; past it the pass is incomplete. - ClosingRounds int - - // hook, when set, runs at the named stages of a pass (a test seam). - hook func(stage string) -} - -// Verify stages passed to the hook. -const ( - verifyHookHeadWalked = "head-walked" // the first HEAD view has been read and walked - verifyHookRootsWalked = "roots-walked" // the selected snapshots have been read and walked too - verifyHookBatchChecked = "batch-checked" // a batch of checks has settled - verifyHookClosingRead = "closing-read" // a closing read is about to be made - verifyHookClosed = "closed" // the quiet closing read was made: the final view is fixed -) - -// VerifyIncomplete is why a pass did not complete. -type VerifyIncomplete string - -const ( - VerifyIncompleteDeadline VerifyIncomplete = "deadline" // the caller's deadline passed - VerifyIncompleteCancelled VerifyIncomplete = "cancelled" // the caller cancelled - VerifyIncompleteRounds VerifyIncomplete = "closing_rounds_exhausted" // every closing read named new chunks - VerifyIncompleteHeadAbsent VerifyIncomplete = "head_absent" // the closing read found no HEAD - VerifyIncompleteHeadInvalid VerifyIncomplete = "head_invalid" // the closing read's HEAD does not decode - VerifyIncompleteError VerifyIncomplete = "error" // a filer or blob store failure, or a refused request -) - -// CodeVerifyIncomplete: the closing reads could not close the pass (each -// named chunks not seen before, or the last found no usable HEAD). -const CodeVerifyIncomplete = "verify_incomplete" - -// VerifyFinding is one problem found. Segment is set for a segment's own -// problem, Index for a chunk's. -type VerifyFinding struct { - Volume string `json:"volume"` - Root string `json:"root"` - Segment *uint64 `json:"segment,omitempty"` - Index *uint64 `json:"index,omitempty"` - Owner string `json:"owner,omitempty"` - Key string `json:"key,omitempty"` - FID string `json:"fid,omitempty"` - Class string `json:"class"` - Detail string `json:"detail"` -} - -// VerifyResult is a pass's summary and findings. Complete is false when the -// pass could not finish (Incomplete says why); the counters and findings -// then cover what it checked. -type VerifyResult struct { - VolumeID string `json:"volumeID"` - Depth VerifyDepth `json:"depth"` - Complete bool `json:"complete"` - // Incomplete is why the pass did not complete ("" when it did). - Incomplete VerifyIncomplete `json:"incomplete,omitempty"` - // HeadGens are the HEAD generations the pass read, in order; the last - // is the final view's. - HeadGens []uint64 `json:"headGens"` - // Snapshots are the snapshots checked, as name/attempt. - Snapshots []string `json:"snapshots"` - // SegmentsChecked counts segment references checked (per root walked); - // SegmentReads the segment objects actually read. - SegmentsChecked int `json:"segmentsChecked"` - SegmentReads int `json:"segmentReads"` - // ChunksChecked counts the chunk references (root, index) of the final - // view; DistinctChunks the distinct chunks (owner, key) the pass saw. - ChunksChecked int `json:"chunksChecked"` - DistinctChunks int `json:"distinctChunks"` - // DistinctChunksRead and BytesRead count the chunk data read. - DistinctChunksRead int `json:"distinctChunksRead"` - BytesRead int64 `json:"bytesRead"` - // SupersededDuringVerify counts the chunks and segments that had a bad - // outcome or a problem under a reference seen during the pass, yet yield - // no finding (no final reference has a problem), once each; - // RootDeletedDuringVerify counts instead those whose problem reference - // was carried by a selected snapshot deleted during the pass. - SupersededDuringVerify int `json:"supersededDuringVerify"` - RootDeletedDuringVerify int `json:"rootDeletedDuringVerify"` - // SnapshotsDeletedDuringVerify lists, as name/attempt, the checked - // snapshots gone at the final read: they are not fully covered. - SnapshotsDeletedDuringVerify []string `json:"snapshotsDeletedDuringVerify"` - // ForkSourceGone: this volume is a fork whose source volume no longer - // exists, so its fork record could not be compared with the parent - // snapshot. Not a finding. - ForkSourceGone bool `json:"forkSourceGone,omitempty"` - // ChunksNotRead counts the READ_ERROR findings: chunks or segments that - // could not be read, so were not verified. ReadRetries counts the - // retried reads. - ChunksNotRead int `json:"chunksNotRead"` - ReadRetries int `json:"readRetries"` - FindingsByClass map[string]int `json:"findingsByClass"` - Findings []VerifyFinding `json:"findings"` -} - -// Verify checks vol's remote image at opts.Depth; see the top of this file. -func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (VerifyResult, error) { - res := VerifyResult{VolumeID: vol, HeadGens: []uint64{}, Snapshots: []string{}, SnapshotsDeletedDuringVerify: []string{}, - FindingsByClass: map[string]int{}, Findings: []VerifyFinding{}} - refuse := func(err error) (VerifyResult, error) { - res.Incomplete = VerifyIncompleteError - return res, err - } - if opts.Depth == "" { - opts.Depth = VerifyBindings - } - res.Depth = opts.Depth - if opts.Depth != VerifyMeta && opts.Depth != VerifyBindings && opts.Depth != VerifyData { - return refuse(catErr(CodeInvalidName, false, nil, "verify depth %q: meta, bindings or data", opts.Depth)) - } - if opts.Snapshot != "" && opts.AllSnapshots { - return refuse(catErr(CodeInvalidName, false, nil, "verify: a named snapshot and all snapshots do not combine")) - } - if opts.Snapshot != "" { - if err := CheckSnapshotName(opts.Snapshot); err != nil { - return refuse(err) - } - } - if opts.Concurrency <= 0 { - opts.Concurrency = DefaultVerifyConcurrency - } - if opts.BytesPerSecond == 0 { - opts.BytesPerSecond = DefaultVerifyBytesPerSecond - } - if opts.RefreshInterval <= 0 { - opts.RefreshInterval = DefaultVerifyRefresh - } - if opts.IntentStaleAge <= 0 { - opts.IntentStaleAge = DefaultVerifyIntentStaleAge - } - if opts.ClosingRounds <= 0 { - opts.ClosingRounds = DefaultVerifyClosingRounds - } - root, err := c.volRoot(vol) - if err != nil { - return refuse(err) - } - v := &verifier{c: c, vol: vol, root: root, opts: opts, res: &res, blobs: c.blobs, - segs: map[string]*verifySegment{}, chunks: map[string]*verifyChunk{}, dropped: map[string]bool{}, - seenChunks: map[string]map[seenChunk]bool{}, seenSegs: map[string]map[seenSeg]bool{}, - pacer: &verifyPacer{rate: opts.BytesPerSecond}} - err = v.run(ctx) - v.reconcile() - sort.SliceStable(res.Findings, func(i, j int) bool { return findingLess(res.Findings[i], res.Findings[j]) }) - for _, f := range res.Findings { - res.FindingsByClass[f.Class]++ - } - res.DistinctChunks = len(v.chunks) - if err != nil { - switch { - case errors.Is(err, errVerifyHeadAbsent): - res.Incomplete = VerifyIncompleteHeadAbsent - case errors.Is(err, errVerifyHeadInvalid): - res.Incomplete = VerifyIncompleteHeadInvalid - case CodeOf(err) == CodeVerifyIncomplete: - res.Incomplete = VerifyIncompleteRounds - case errors.Is(err, context.DeadlineExceeded): - res.Incomplete = VerifyIncompleteDeadline - case errors.Is(err, context.Canceled): - res.Incomplete = VerifyIncompleteCancelled - default: - res.Incomplete = VerifyIncompleteError - } - return res, err - } - res.Complete = true - return res, nil -} - -// Why a closing read leaves no HEAD root (wrapped in CodeVerifyIncomplete). -var ( - errVerifyHeadAbsent = errors.New("chunkstore: verify: the closing read found no HEAD") - errVerifyHeadInvalid = errors.New("chunkstore: verify: the closing read's HEAD does not decode") -) - -// verifySegment is one segment object (owner, key): read once, like a chunk -// (keys are never rebound). Its one outcome is a bad one (class and detail: -// binding missing, needle missing, read error) or its content (sum, body: -// a segment keeps its bytes). A reference to it is judged at need -// (judgeSegment); nothing about a reference is kept but the decode memo. -type verifySegment struct { - owner, key string - fid string - tombstoned bool - class, detail string - sum [32]byte - body []byte - memo map[segRef]segJudged // decodes by the full reference (every input of the decode) -} - -// segRef is one root's reference to a segment, with every root field its -// decode depends on. -type segRef struct { - group, chunkBytes, remoteLSN uint64 - ref storage.ChunkSegment -} - -// segJudged is Judge's answer for a segment reference: a class (and detail) -// when it is not sound, else this root's chunk references. -type segJudged struct { - class, detail string - chunks map[uint64]storage.ChunkRef -} - -// segID is a segment's identity: its owner and key. -func segID(vol string, ref storage.ChunkSegment) string { return chunkIdentity(vol, ref.Key) } - -// Seen references, per object: the root (HEAD, or a snapshot's label), the -// index (a chunk's) or the reference with its root fields (a segment's). -type seenChunk struct { - root string - idx uint64 - sha [32]byte -} - -type seenSeg struct { - root string - ref segRef -} - -const headRoot = "HEAD" // the root of every HEAD generation's references - -// verifyChunk is one distinct chunk (owner volume + the owner's own key): -// unseen while absent from the verifier's map, then queued, then settled. -type verifyChunk struct { - id string - owner, key string - fid string - bound bool // a sound, untombstoned binding was found - - // The outcome, under the verifier's lock until the checks are joined: - // class and detail of a bad outcome (binding missing or tombstoned, - // needle missing, read error), or the content read (read: its SHA-256 - // and length). - settled bool - class, detail string - read bool - digest [32]byte - length int -} - -// verifyView is one root as last read: its references by index, and its -// root document (for the segments it names). -type verifyView struct { - label string - h storage.ChunkHead - chunks map[uint64]storage.ChunkRef - // snapshots only: the identity they were found under, and whether the - // final round read them gone. - name, attempt string - gone bool -} - -type verifier struct { - c *Catalog - vol string - root string - opts VerifyOptions - blobs Blobs - pacer *verifyPacer - - geo Geometry - chunkBytes uint64 - nChunks uint64 - - mu sync.Mutex - res *VerifyResult - segs map[string]*verifySegment // the segments read, by identity - chunks map[string]*verifyChunk // the chunks seen, by identity - pending []*verifyChunk // queued, not yet checked - listed bool // the owners' keys/ were listed once - - head *verifyView // the HEAD view; nil without a usable HEAD - dropped map[string]bool // keys a HEAD view named and a later one did not - snaps []*verifyView // the selected snapshots, in order - lastRefresh time.Time - - seenChunks map[string]map[seenChunk]bool // the references seen, per chunk - seenSegs map[string]map[seenSeg]bool // the references seen, per segment -} - -func (v *verifier) hook(stage string) { - if v.opts.hook != nil { - v.opts.hook(stage) - } -} - -func (v *verifier) finding(f VerifyFinding) { - f.Volume = v.vol - v.mu.Lock() - v.res.Findings = append(v.res.Findings, f) - if f.Class == FindingReadError { - v.res.ChunksNotRead++ - } - v.mu.Unlock() -} - -func isContextErr(ctx context.Context, err error) bool { - return ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) -} - -// fetch reads one needle. A needle the store reports absent (ErrBlobNotFound) -// and a context error are returned at once; any other failure is retried, -// up to verifyReadAttempts reads in all, before it is returned. -func (v *verifier) fetch(ctx context.Context, fid string) ([]byte, error) { - for attempt := 1; ; attempt++ { - data, err := v.blobs.Get(ctx, fid) - if err == nil || errors.Is(err, ErrBlobNotFound) || isContextErr(ctx, err) || attempt == verifyReadAttempts { - return data, err - } - v.mu.Lock() - v.res.ReadRetries++ - v.mu.Unlock() - t := time.NewTimer(verifyRetryBackoff * time.Duration(attempt)) - select { - case <-t.C: - case <-ctx.Done(): - t.Stop() - return nil, ctx.Err() - } - } -} - -// readErrorDetail describes a read that failed for a reason other than "not found". -func readErrorDetail(err error) string { - return fmt.Sprintf("not verified: could not read the needle in %d attempts (re-run): %v", verifyReadAttempts, err) -} - -// verifyPrefetched serves one needle already read, so the shared segment -// decoder verifies exactly the bytes fetch returned. -type verifyPrefetched struct { - fid string - body []byte -} - -func (p verifyPrefetched) Put(context.Context, []byte) (string, error) { - return "", errors.New("chunkstore: verify is read-only") -} - -func (p verifyPrefetched) Get(_ context.Context, fid string) ([]byte, error) { - if fid != p.fid { - return nil, fmt.Errorf("chunkstore: verify: unexpected needle %s", fid) - } - return p.body, nil -} - -// abortErr turns a failure that stops the pass into its error: a context -// error stays one (the CLI reports deadline_exceeded), anything else from -// the filer is remote_unavailable. -func abortErr(ctx context.Context, err error, format string, a ...any) error { - if ctx.Err() != nil { - return fmt.Errorf("chunkstore: verify: %s: %w", fmt.Sprintf(format, a...), ctx.Err()) - } - if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { - return fmt.Errorf("chunkstore: verify: %s: %w", fmt.Sprintf(format, a...), err) - } - if CodeOf(err) != "" { - return err - } - return remoteErr(err, format, a...) -} - -func headLabel(gen uint64) string { return fmt.Sprintf("HEAD gen %d", gen) } - -func (v *verifier) run(ctx context.Context) error { - vi, ok, err := v.c.ReadVolume(ctx, v.vol) - if err != nil { - if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { - return abortErr(ctx, err, "read VOLUME of %s", v.vol) - } - v.finding(VerifyFinding{Root: "VOLUME", Class: FindingRootInvalid, Detail: err.Error()}) - return nil - } - if !ok { - return catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", v.vol) - } - v.geo = vi.Geometry - v.chunkBytes = uint64(v.geo.ChunkBlocks) * uint64(v.geo.BlockSize) - if v.geo.ChunkBlocks > 0 { - v.nChunks = (v.geo.NumBlocks + uint64(v.geo.ChunkBlocks) - 1) / uint64(v.geo.ChunkBlocks) - } - if v.chunkBytes == 0 { - v.finding(VerifyFinding{Root: "VOLUME", Class: FindingGeometry, Detail: fmt.Sprintf("VOLUME geometry %+v has no chunk size", v.geo)}) - } - if err := v.forkRecord(ctx, vi); err != nil { - return err - } - - // HEAD: the root once, then the segments it names. - e, err := v.c.f.LookupEntry(ctx, v.root, headName) - switch { - case errors.Is(err, ErrNotFound): - v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "the volume has a VOLUME entry but no HEAD"}) - case err != nil: - return abortErr(ctx, err, "read HEAD of %s", v.vol) - default: - h, derr := decodeHead(path.Join(v.root, headName), e) - if derr != nil { - v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: derr.Error()}) - break - } - v.lastRefresh = v.c.now() - if _, err := v.refresh(ctx, h); err != nil { - return err - } - if err := v.intents(ctx, h, v.head.chunks); err != nil { - return err - } - } - v.hook(verifyHookHeadWalked) - - if err := v.snapshots(ctx); err != nil { - return err - } - v.hook(verifyHookRootsWalked) - for rounds := 0; ; { - if err := v.drain(ctx); err != nil { - return err - } - named, err := v.round(ctx) - if err != nil { - return err - } - if !named { - v.hook(verifyHookClosed) - return nil // V.Close: this read is the final view - } - if rounds++; rounds == v.opts.ClosingRounds { - return catErr(CodeVerifyIncomplete, true, nil, // V.GiveUp - "verify of %s: each of %d closing reads of HEAD named chunks not seen before; the pass is incomplete (re-run when the volume is quieter)", - v.vol, rounds) - } - } -} - -// drain checks every queued chunk, batch by batch, refreshing HEAD between -// batches (a refresh can queue more). -func (v *verifier) drain(ctx context.Context) error { - for len(v.pending) > 0 { - batch := v.pending - v.pending = nil - if err := v.checkBindings(ctx, batch, !v.listed); err != nil { - return err - } - v.listed = true - if v.opts.Depth == VerifyData { - if err := v.checkData(ctx, batch); err != nil { - return err - } - } - v.hook(verifyHookBatchChecked) - if err := v.maybeRefresh(ctx); err != nil { - return err - } - } - return nil -} - -// V.Round: once every queued chunk is settled, read HEAD and each selected snapshot's state once; report whether HEAD named a chunk not seen. -func (v *verifier) round(ctx context.Context) (bool, error) { - v.hook(verifyHookClosingRead) - named := false - if v.head != nil { - var err error - if named, err = v.readHead(ctx, true); err != nil { - return false, err - } - } - for _, s := range v.snaps { - active, err := v.snapshotActive(ctx, s) - if err != nil { - return false, err - } - s.gone = !active - } - return named, nil -} - -// ---- roots and segments ---- - -// V.Discover and V.Settle (segments): the segment ref names, read once per (owner, key) by this pass, its outcome kept. An error stops the pass. -func (v *verifier) segment(ctx context.Context, ref storage.ChunkSegment) (*verifySegment, error) { - id := segID(v.vol, ref) - if s := v.segs[id]; s != nil { - return s, nil - } - s, err := v.readSegment(ctx, ref) - if err != nil { - return nil, err - } - v.segs[id] = s - return s, nil -} - -func (v *verifier) readSegment(ctx context.Context, ref storage.ChunkSegment) (*verifySegment, error) { - if v.blobs == nil { - return nil, errors.New("chunkstore: verify needs a blob reader for segmented roots") - } - r, err := NewChunkRemote(v.c.f, v.blobs, v.root) - if err != nil { - return nil, err - } - s := &verifySegment{owner: ref.Owner, key: ref.Key, memo: map[segRef]segJudged{}} - dir, name, err := r.keyLocation(ref.Key) - if err != nil { - s.class, s.detail = FindingBindingMissing, "segment binding: "+err.Error() - return s, nil - } - e, err := v.c.f.LookupEntry(ctx, dir, name) - if errors.Is(err, ErrNotFound) { - s.class, s.detail = FindingBindingMissing, "segment binding not found" - return s, nil - } - if err != nil { - return nil, abortErr(ctx, err, "read segment binding %s/%s", dir, name) - } - s.fid = string(e.Extended[extFid]) - if bad := bindingProblem(e); bad != "" { - s.class, s.detail = FindingBindingMissing, "invalid segment binding: "+bad - return s, nil - } - s.tombstoned = len(e.Extended[extGCDeleted]) != 0 - v.mu.Lock() - v.res.SegmentReads++ - v.mu.Unlock() - body, err := v.fetch(ctx, s.fid) - switch { - case err == nil: - case isContextErr(ctx, err): - return nil, abortErr(ctx, err, "read segment %s", ref.Key) - case errors.Is(err, ErrBlobNotFound): - s.class, s.detail = FindingNeedleMissing, "segment needle not found: "+err.Error() - return s, nil - default: - s.class, s.detail = FindingReadError, readErrorDetail(err) - return s, nil - } - s.sum, s.body = sha256.Sum256(body), body - return s, nil -} - -// V.Reconcile's Judge for a segment reference (also used to walk a root): the segment's bad outcome; a hash mismatch; bytes that do not decode under this reference's own fields (SEGMENT_UNREADABLE); else this root's chunk references. -func (v *verifier) judgeSegment(ctx context.Context, s *verifySegment, k segRef) segJudged { - switch { - case s.class != "": - return segJudged{class: s.class, detail: s.detail} - case k.ref.SHA256 != s.sum: - return segJudged{class: FindingContentMismatch, detail: fmt.Sprintf("segment SHA-256 %s, reference %s", hex.EncodeToString(s.sum[:]), hex.EncodeToString(k.ref.SHA256[:]))} - } - // A memo of the decode, keyed by the full reference: the decode is a - // function of the bytes and of k alone, so the memo cannot change an - // answer; it only saves decoding a segment again at each walk. - if j, ok := s.memo[k]; ok { - return j - } - j := segJudged{} - r, err := NewChunkRemote(v.c.f, verifyPrefetched{s.fid, s.body}, v.root) - if err == nil { - r.mu.Lock() - r.fids[k.ref.Key] = s.fid - r.mu.Unlock() - one := storage.ChunkHead{Segments: map[uint64]storage.ChunkSegment{k.group: k.ref}, ChunkBytes: k.chunkBytes, - ManifestChunkCount: k.ref.Count, RemoteLSN: k.remoteLSN, State: storage.ChunkHeadActive} - var resolved storage.ChunkHead - if resolved, err = r.resolveManifest(ctx, one); err == nil { - j.chunks = resolved.Chunks - } - } - if err != nil { - j = segJudged{class: FindingSegmentUnreadable, detail: err.Error()} - } - s.memo[k] = j - return j -} - -// bindingProblem is what makes e unusable as a chunk key binding, or "". -func bindingProblem(e *filerpb.Entry) string { - switch { - case e.GetIsDirectory(): - return "is a directory" - case len(e.GetChunks()) != 0: - return fmt.Sprintf("carries %d filer chunks", len(e.GetChunks())) - case string(e.Extended[extKind]) != kindChunkKey: - return fmt.Sprintf("kind %q, want %q", e.Extended[extKind], kindChunkKey) - case len(e.Extended[extFid]) == 0: - return "no fid" - } - return "" -} - -// walk reads the segments root h (of root, HEAD or a snapshot's label) names -// and returns its chunk references by index, and the segment groups whose -// reference Judge does not find sound (their chunks are unknown). Every -// reference met is recorded as seen. -func (v *verifier) walk(ctx context.Context, root string, h storage.ChunkHead) (map[uint64]storage.ChunkRef, map[uint64]bool, error) { - out := map[uint64]storage.ChunkRef{} - unusable := map[uint64]bool{} - if h.Segments == nil { - for idx, ref := range h.Chunks { - out[idx] = ref - } - } - for _, g := range sortedGroups(h.Segments) { - v.mu.Lock() - v.res.SegmentsChecked++ - v.mu.Unlock() - s, err := v.segment(ctx, h.Segments[g]) - if err != nil { - return out, unusable, err - } - k := segRef{group: g, chunkBytes: h.ChunkBytes, remoteLSN: h.RemoteLSN, ref: h.Segments[g]} - see(v.seenSegs, segID(v.vol, k.ref), seenSeg{root, k}) - j := v.judgeSegment(ctx, s, k) - if j.class != "" { - unusable[g] = true - continue - } - for idx, cr := range j.chunks { - out[idx] = cr - } - } - for idx, ref := range out { - see(v.seenChunks, chunkIdentity(v.vol, ref.Key), seenChunk{root, idx, ref.SHA256}) - } - return out, unusable, nil -} - -// see records a reference to object id as seen. -func see[R comparable](seen map[string]map[R]bool, id string, r R) { - if seen[id] == nil { - seen[id] = map[R]bool{} - } - seen[id][r] = true -} - -// geometry reports a root's chunk size and chunk indices against VOLUME. -func (v *verifier) geometry(label string, h storage.ChunkHead, chunks map[uint64]storage.ChunkRef) { - if h.Segments != nil && h.ChunkBytes != v.chunkBytes { - v.finding(VerifyFinding{Root: label, Class: FindingGeometry, - Detail: fmt.Sprintf("root chunk_bytes %d, VOLUME chunk size %d", h.ChunkBytes, v.chunkBytes)}) - } - for _, idx := range sortedIndexes(chunks) { - if idx >= v.nChunks { - i := idx - owner, key := splitIdentity(chunkIdentity(v.vol, chunks[idx].Key)) - v.finding(VerifyFinding{Root: label, Index: &i, Owner: owner, Key: key, Class: FindingGeometry, - Detail: fmt.Sprintf("chunk index %d outside the volume (%d chunks)", idx, v.nChunks)}) - } - } -} - -// V.Discover: queue one check of each chunk the references name that this pass has not seen; report whether there was one. -func (v *verifier) discover(chunks map[uint64]storage.ChunkRef) bool { - found := false - for _, idx := range sortedIndexes(chunks) { - id := chunkIdentity(v.vol, chunks[idx].Key) - if v.chunks[id] != nil { - continue - } - owner, key := splitIdentity(id) - w := &verifyChunk{id: id, owner: owner, key: key} - v.chunks[id] = w - found = true - if v.opts.Depth == VerifyMeta { - w.settled = true // nothing to check at this depth - continue - } - v.pending = append(v.pending, w) - } - return found -} - -// V.Settle: record w's outcome (a bad outcome's class and detail, or none); report nothing. -func (v *verifier) settle(w *verifyChunk, class, detail string) { - v.mu.Lock() - w.settled, w.class, w.detail = true, class, detail - v.mu.Unlock() -} - -// snapshotActive reads snapshot s's state again (part of V.Round): its name -// record must still name s's attempt, and the attempt entry must still -// exist, neither aborted nor marked deleting (the attempt path is never -// reused, so a snapshot read gone stays gone). -func (v *verifier) snapshotActive(ctx context.Context, s *verifyView) (bool, error) { - ne, err := v.c.f.LookupEntry(ctx, path.Join(v.root, snapNamesDir), s.name) - if errors.Is(err, ErrNotFound) { - return false, nil - } - if err != nil { - return false, abortErr(ctx, err, "re-read snapshot name %s/%s", v.vol, s.name) - } - if rec, err := decodeNameRecord(path.Join(v.root, snapNamesDir, s.name), ne); err == nil && rec.Attempt != s.attempt { - return false, nil - } - e, err := v.c.f.LookupEntry(ctx, path.Join(v.root, snapsDir, s.name), s.attempt) - if errors.Is(err, ErrNotFound) { - return false, nil - } - if err != nil { - return false, abortErr(ctx, err, "re-read snapshot %s/%s/%s", v.vol, s.name, s.attempt) - } - st := string(e.Extended[extSnapState]) - return st != SnapAborted && st != SnapDeleting && len(e.Extended[extSnapDeletedNs]) == 0, nil -} - -func sortedIndexes(m map[uint64]storage.ChunkRef) []uint64 { - out := make([]uint64, 0, len(m)) - for idx := range m { - out = append(out, idx) - } - sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) - return out -} - -// splitIdentity splits a chunkIdentity into the owner volume and its key. -func splitIdentity(id string) (owner, key string) { - owner, key, _ = strings.Cut(id, "\x00") - return owner, key -} - -// ---- snapshots and fork record ---- - -func (v *verifier) snapshots(ctx context.Context) error { - if v.opts.Snapshot != "" { - ref, ok, err := v.c.resolveSnap(ctx, v.vol, v.opts.Snapshot) - if err != nil { - if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { - return abortErr(ctx, err, "read snapshot %s/%s", v.vol, v.opts.Snapshot) - } - v.finding(VerifyFinding{Root: "snapshot " + v.opts.Snapshot, Class: FindingRootInvalid, Detail: err.Error()}) - return nil - } - if !ok || ref.entry == nil || ref.info.State == SnapAborted { - return catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", v.vol, v.opts.Snapshot) - } - if ref.info.State == SnapDeleting { - return catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted; GC may already reclaim its chunks", v.vol, v.opts.Snapshot) - } - return v.snapshot(ctx, v.opts.Snapshot, ref) - } - if !v.opts.AllSnapshots { - return nil - } - dir := path.Join(v.root, snapNamesDir) - after := "" - for { - page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) - if err != nil { - return abortErr(ctx, err, "list snapshots of %s", v.vol) - } - for _, e := range page { - if e.GetName() <= after { - return remoteErr(nil, "non-advancing snapshot listing of %s", v.vol) - } - after = e.GetName() - ref, ok, err := v.c.resolveSnap(ctx, v.vol, e.GetName()) - if err != nil { - if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { - return abortErr(ctx, err, "read snapshot %s/%s", v.vol, e.GetName()) - } - v.finding(VerifyFinding{Root: "snapshot " + e.GetName(), Class: FindingRootInvalid, Detail: err.Error()}) - continue - } - if !ok || ref.entry == nil || ref.info.State == SnapAborted || ref.info.State == SnapDeleting { - continue - } - if err := v.snapshot(ctx, e.GetName(), ref); err != nil { - return err - } - } - if len(page) < listPage { - return nil - } - } -} - -// snapshot selects the snapshot found under name, at the attempt its name -// record names: that path is its identity (label, state reads), and a -// document naming another volume or snapshot is ROOT_INVALID. Its -// references are fixed; its chunks are discovered (V.Discover). -func (v *verifier) snapshot(ctx context.Context, name string, ref snapRef) error { - s := &verifyView{label: "snapshot " + name + "/" + ref.rec.Attempt, h: ref.info.Head(), name: name, attempt: ref.rec.Attempt} - v.res.Snapshots = append(v.res.Snapshots, name+"/"+s.attempt) - v.snaps = append(v.snaps, s) - if ref.info.VolumeID != v.vol || ref.info.Name != name { - v.finding(VerifyFinding{Root: s.label, Class: FindingRootInvalid, - Detail: fmt.Sprintf("snapshot document names %s/%s, found as %s/%s", ref.info.VolumeID, ref.info.Name, v.vol, name)}) - } - if ref.info.geo != (Geometry{}) && ref.info.geo != v.geo { - v.finding(VerifyFinding{Root: s.label, Class: FindingGeometry, Detail: fmt.Sprintf("snapshot geometry %+v, VOLUME %+v", ref.info.geo, v.geo)}) - } - chunks, _, err := v.walk(ctx, s.label, s.h) - if err != nil { - return err - } - s.chunks = chunks - v.geometry(s.label, s.h, chunks) - v.discover(chunks) - return nil -} - -// forkRecord checks a fork's record against the parent snapshot it names: -// some attempt of that snapshot, at the recorded source generation, must -// have exactly the recorded HEAD digest (attempt entries are never -// removed, so a parent snapshot deleted or renamed since still answers). -func (v *verifier) forkRecord(ctx context.Context, vi VolumeInfo) error { - fr := vi.Fork - if vi.Origin != OriginFork || fr == nil { - return nil - } - const label = "VOLUME fork record" - mismatch := func(format string, a ...any) error { - v.finding(VerifyFinding{Root: label, Owner: fr.Source, Class: FindingForkRecordMismatch, Detail: fmt.Sprintf(format, a...)}) - return nil - } - if CheckVolumeID(fr.Source) != nil || CheckSnapshotName(fr.Snapshot) != nil { - return mismatch("fork record names source %q snapshot %q", fr.Source, fr.Snapshot) - } - dir := path.Join(v.c.base, fr.Source, snapsDir, fr.Snapshot) - after := "" - sawGen := false - for { - page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) - if err != nil { - return abortErr(ctx, err, "list attempts of %s/%s", fr.Source, fr.Snapshot) - } - for _, e := range page { - if e.GetName() <= after { - return remoteErr(nil, "non-advancing attempt listing of %s/%s", fr.Source, fr.Snapshot) - } - after = e.GetName() - info, _, err := decodeSnap(path.Join(dir, e.GetName()), e) - if err != nil || info.State == SnapAborted || info.HeadGen != fr.SourceGen { - continue - } - sawGen = true - if info.digest == fr.HeadSHA256 { - return nil - } - } - if len(page) < listPage { - break - } - } - if sawGen { - return mismatch("no attempt of snapshot %s/%s at gen %d has HEAD digest %s", fr.Source, fr.Snapshot, fr.SourceGen, fr.HeadSHA256) - } - // The source volume itself may have been deleted since the fork: its - // snapshot records went with it and there is nothing to compare with. - // That is not damage to this volume, whose chunks are checked through - // its own roots. - if _, ok, err := v.c.ReadVolume(ctx, fr.Source); err != nil { - return abortErr(ctx, err, "read fork source %s", fr.Source) - } else if !ok { - v.res.ForkSourceGone = true - return nil - } - return mismatch("no attempt of snapshot %s/%s at gen %d found", fr.Source, fr.Snapshot, fr.SourceGen) -} - -// ---- intents ---- - -// intents reports capture intents that look stale: below HEAD's epoch, -// older than IntentStaleAge, and naming no key HEAD references. It is a -// hint; whether GC may expire one is GC's decision, with blockmaster -// authority. An intent that does not decode is an invalid GC root. -func (v *verifier) intents(ctx context.Context, h storage.ChunkHead, chunks map[uint64]storage.ChunkRef) error { - named := map[string]bool{} - for _, ref := range chunks { - named[chunkIdentity(v.vol, ref.Key)] = true - } - for _, ref := range h.Segments { - named[chunkIdentity(v.vol, ref.Key)] = true - } - now := v.c.now() - dir := path.Join(v.root, intentsDir) - after := "" - for { - page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) - if err != nil { - return abortErr(ctx, err, "list intents of %s", v.vol) - } - for _, e := range page { - if e.GetName() <= after { - return remoteErr(nil, "non-advancing intent listing of %s", v.vol) - } - after = e.GetName() - in, err := decodeIntent(path.Join(dir, e.GetName()), e) - if err != nil { - v.finding(VerifyFinding{Root: "intent " + e.GetName(), Class: FindingRootInvalid, Detail: err.Error()}) - continue - } - if strings.HasPrefix(in.Holder, "snapshot:") || strings.HasPrefix(in.Holder, "fork:") { - continue // copy intents never expire by epoch - } - age := now.Sub(time.Unix(0, in.CreatedNs)) - if in.Epoch >= h.Epoch || age <= v.opts.IntentStaleAge { - continue - } - bound := false - for _, k := range in.Keys { - if named[chunkIdentity(v.vol, k)] { - bound = true - break - } - } - if bound { - continue - } - v.finding(VerifyFinding{Root: "intent " + in.ID, Class: FindingIntentStale, - Detail: fmt.Sprintf("capture intent of %q at epoch %d below HEAD epoch %d, %s old, naming %d keys HEAD does not reference", - in.Holder, in.Epoch, h.Epoch, age.Round(time.Second), len(in.Keys))}) - } - if len(page) < listPage { - return nil - } - } -} - -// ---- refresh ---- - -// maybeRefresh reads HEAD again (V.Refresh) once RefreshInterval has passed since the last read. -func (v *verifier) maybeRefresh(ctx context.Context) error { - if v.head == nil || v.c.now().Sub(v.lastRefresh) < v.opts.RefreshInterval { - return nil - } - _, err := v.readHead(ctx, false) - return err -} - -// readHead reads HEAD and applies it (V.Refresh); it reports whether HEAD -// named a chunk not seen. A periodic read that finds no HEAD, one that does -// not decode, or an older generation changes nothing: the closing read -// decides. At the closing read (closing set) every answer decides the final -// view: no HEAD leaves no HEAD root and the pass incomplete (HEAD absent); -// an undecodable one is ROOT_INVALID, no HEAD root, incomplete (HEAD -// invalid); an older generation than the view cannot be the final view and -// cannot keep the earlier one, so the pass is incomplete (an error). -func (v *verifier) readHead(ctx context.Context, closing bool) (bool, error) { - v.lastRefresh = v.c.now() - e, err := v.c.f.LookupEntry(ctx, v.root, headName) - if errors.Is(err, ErrNotFound) { - if !closing { - return false, nil - } - v.head = nil - return false, catErr(CodeVerifyIncomplete, true, errVerifyHeadAbsent, "verify of %s: the closing read found no HEAD; the pass has no HEAD to report against", v.vol) - } - if err != nil { - return false, abortErr(ctx, err, "refresh HEAD of %s", v.vol) - } - h, err := decodeHead(path.Join(v.root, headName), e) - if err != nil { - if !closing { - return false, nil - } - v.head = nil - v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "HEAD at the closing read: " + err.Error()}) - return false, catErr(CodeVerifyIncomplete, true, errVerifyHeadInvalid, "verify of %s: the HEAD of the closing read does not decode", v.vol) - } - if closing && v.head != nil && h.Gen < v.head.h.Gen { - return false, remoteErr(nil, "verify of %s: the closing read returned HEAD gen %d, older than gen %d already read", v.vol, h.Gen, v.head.h.Gen) - } - return v.refresh(ctx, h) -} - -// V.Refresh: replace the HEAD view with h unless h is older (or the same); mark the keys it drops; discover its new keys. -func (v *verifier) refresh(ctx context.Context, h storage.ChunkHead) (bool, error) { - if v.head != nil && (h.Gen < v.head.h.Gen || h.Gen == v.head.h.Gen && h.Epoch == v.head.h.Epoch) { - return false, nil - } - chunks, unusable, err := v.walk(ctx, headRoot, h) - if err != nil { - return false, err - } - if v.head != nil { - // A key the old view named that h does not is dropped, unless its - // old index lies in a segment of h that could not be read. - perSeg := uint64(0) - if h.ChunkBytes > 0 { - perSeg = manifestSegmentBytes / h.ChunkBytes - } - now := map[string]bool{} - for _, ref := range chunks { - now[chunkIdentity(v.vol, ref.Key)] = true - } - for idx, ref := range v.head.chunks { - if id := chunkIdentity(v.vol, ref.Key); !now[id] && (perSeg == 0 || !unusable[idx/perSeg]) { - v.dropped[id] = true - } - } - } - v.head = &verifyView{label: headLabel(h.Gen), h: h, chunks: chunks} - v.res.HeadGens = append(v.res.HeadGens, h.Gen) - return v.discover(chunks), nil -} - -// ---- bindings ---- - -// checkBindings checks the binding of every chunk in batch. The first batch -// lists each owner's keys/ once; chunks not found in a listing (bound after -// it, or queued by a refresh) are looked up one by one. -func (v *verifier) checkBindings(ctx context.Context, batch []*verifyChunk, list bool) error { - found := map[*verifyChunk]*filerpb.Entry{} - if list { - byOwner := map[string]map[string]*verifyChunk{} - var owners []string - for _, w := range batch { - name, err := keyName(w.key) - if err != nil { - continue - } - if byOwner[w.owner] == nil { - byOwner[w.owner] = map[string]*verifyChunk{} - owners = append(owners, w.owner) - } - byOwner[w.owner][name] = w - } - sort.Strings(owners) - for _, owner := range owners { - if err := v.maybeRefresh(ctx); err != nil { - return err - } - if CheckVolumeID(owner) != nil { - continue - } - want := byOwner[owner] - dir := path.Join(v.c.base, owner, keysDir) - after := "" - for { - page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) - if err != nil { - return abortErr(ctx, err, "list the chunk keys of %s", owner) - } - for _, e := range page { - if e.GetName() <= after { - return remoteErr(nil, "non-advancing chunk key listing of %s", owner) - } - after = e.GetName() - if w := want[e.GetName()]; w != nil { - found[w] = e - } - } - if len(page) < listPage { - break - } - } - } - } - for _, w := range batch { - e := found[w] - if e == nil { - var err error - if e, err = v.lookupBinding(ctx, w); err != nil { - return err - } - } - v.evaluateBinding(w, e) - } - return nil -} - -// lookupBinding reads w's binding directly; nil when it does not exist. -func (v *verifier) lookupBinding(ctx context.Context, w *verifyChunk) (*filerpb.Entry, error) { - if CheckVolumeID(w.owner) != nil { - return nil, nil - } - name, err := keyName(w.key) - if err != nil { - return nil, nil - } - dir := path.Join(v.c.base, w.owner, keysDir) - e, err := v.c.f.LookupEntry(ctx, dir, name) - if errors.Is(err, ErrNotFound) { - return nil, nil - } - if err != nil { - return nil, abortErr(ctx, err, "read chunk key binding %s/%s", dir, name) - } - return e, nil -} - -// V.Settle (bindings): a missing, invalid or tombstoned binding is w's outcome; a sound one settles it at depth bindings. -func (v *verifier) evaluateBinding(w *verifyChunk, e *filerpb.Entry) { - if e == nil { - v.settle(w, FindingBindingMissing, fmt.Sprintf("no binding in %s/keys", w.owner)) - return - } - w.fid = string(e.Extended[extFid]) - switch bad := bindingProblem(e); { - case bad != "": - v.settle(w, FindingBindingMissing, "invalid binding: "+bad) - case len(e.Extended[extGCDeleted]) != 0: - v.settle(w, FindingBindingTombstoned, fmt.Sprintf("binding tombstoned by GC (%s=%s)", extGCDeleted, e.Extended[extGCDeleted])) - default: - w.bound = true - if v.opts.Depth != VerifyData { - v.settle(w, "", "") - } - } -} - -// ---- data ---- - -// checkData fetches every bound chunk of batch once, at bounded concurrency -// and paced. -func (v *verifier) checkData(ctx context.Context, batch []*verifyChunk) error { - if v.blobs == nil { - return errors.New("chunkstore: verify needs a blob reader for depth data") - } - jobs := make(chan *verifyChunk) - var ( - wg sync.WaitGroup - errMu sync.Mutex - firstEr error - ) - setErr := func(err error) { - errMu.Lock() - if firstEr == nil { - firstEr = err - } - errMu.Unlock() - } - getErr := func() error { - errMu.Lock() - defer errMu.Unlock() - return firstEr - } - wctx, cancel := context.WithCancel(ctx) - defer cancel() - for i := 0; i < v.opts.Concurrency; i++ { - wg.Add(1) - go func() { - defer wg.Done() - for w := range jobs { - if err := v.readChunk(wctx, w); err != nil { - setErr(err) - cancel() - } - } - }() - } - dispatch := func() error { - for _, w := range batch { - if !w.bound { - continue - } - if err := getErr(); err != nil { - return err - } - if err := v.maybeRefresh(ctx); err != nil { - return err - } - if err := v.pacer.wait(wctx, int64(v.chunkBytes)); err != nil { - if werr := getErr(); werr != nil { - return werr - } - return abortErr(ctx, err, "pace chunk reads") - } - select { - case jobs <- w: - case <-wctx.Done(): - if err := getErr(); err != nil { - return err - } - return abortErr(ctx, wctx.Err(), "read chunks of %s", v.vol) - } - } - return nil - } - if err := dispatch(); err != nil { - // Stop the reads in flight before waiting for them, so a known - // failure is not held up by a read that would end only with the - // caller's deadline. The failure that stopped the pass is the one - // returned, not the cancellation it caused in the readers. - setErr(err) - cancel() - } - close(jobs) - wg.Wait() - return getErr() -} - -// V.Settle (data): read w's needle once and record the outcome (missing, read error, wrong size, or the content's SHA-256). -func (v *verifier) readChunk(ctx context.Context, w *verifyChunk) error { - data, err := v.fetch(ctx, w.fid) - switch { - case err == nil: - case isContextErr(ctx, err): - return abortErr(ctx, err, "read chunk %s", w.fid) - case errors.Is(err, ErrBlobNotFound): - v.settle(w, FindingNeedleMissing, err.Error()) - return nil - default: - v.settle(w, FindingReadError, readErrorDetail(err)) - return nil - } - sum := sha256.Sum256(data) - v.mu.Lock() - defer v.mu.Unlock() - v.res.DistinctChunksRead++ - v.res.BytesRead += int64(len(data)) - w.settled, w.read, w.digest, w.length = true, true, sum, len(data) - return nil -} - -// ---- reconcile ---- - -// V.Reconcile's Judge for a chunk reference: the chunk's bad outcome; a hash mismatch; a wrong length; else sound (""). -func (v *verifier) judgeChunk(w *verifyChunk, sha [32]byte) (string, string) { - switch { - case w.class != "": - return w.class, w.detail - case !w.read: // checked to its binding (depth bindings), or not checked (depth meta) - return "", "" - case sha != w.digest: - return FindingContentMismatch, fmt.Sprintf("needle SHA-256 %s, reference %s", hex.EncodeToString(w.digest[:]), hex.EncodeToString(sha[:])) - case uint64(w.length) != v.chunkBytes: - return FindingSizeMismatch, fmt.Sprintf("needle holds %d bytes, chunk size %d", w.length, v.chunkBytes) - } - return "", "" -} - -// judged is Judge's answer for one final reference: its root (position -// among the final roots), its index (a chunk's) or group (a segment's), the -// SHA-256 it expects, and its class ("" when sound) and detail. -type judged struct { - root int - at uint64 - sha [32]byte - class, detail string -} - -// V.Reconcile: every finding and counter, from the settled outcomes, the references seen and the final view alone (an incomplete pass: its last view); root deleted takes precedence over superseded. -func (v *verifier) reconcile() { - // The final roots: the HEAD view, then each selected snapshot not gone, - // in order. Per object and class Judge gives a final reference: one - // finding (byClass). An object with a bad outcome or a problem under any - // reference seen, and no finding, is counted once (count). Objects never - // settled (an incomplete pass) are not judged. - var roots []*verifyView - gone := map[string]bool{} - if v.head != nil { - roots = append(roots, v.head) - v.geometry(v.head.label, v.head.h, v.head.chunks) - } - for _, s := range v.snaps { - if s.gone { - gone[s.label] = true - v.res.SnapshotsDeletedDuringVerify = append(v.res.SnapshotsDeletedDuringVerify, s.name+"/"+s.attempt) - } else { - roots = append(roots, s) - } - } - finalChunks := map[string][]judged{} - for ri, r := range roots { - for _, idx := range sortedIndexes(r.chunks) { - ref := r.chunks[idx] - id := chunkIdentity(v.vol, ref.Key) - finalChunks[id] = append(finalChunks[id], judged{root: ri, at: idx, sha: ref.SHA256}) - v.res.ChunksChecked++ - } - } - for _, id := range sortedKeys(v.chunks) { - w := v.chunks[id] - if !w.settled { - continue - } - refs := finalChunks[id] - for i := range refs { - refs[i].class, refs[i].detail = v.judgeChunk(w, refs[i].sha) - } - mk := func(j judged) VerifyFinding { - idx := j.at - return VerifyFinding{Root: roots[j.root].label, Index: &idx, Owner: w.owner, Key: w.key, FID: w.fid, Class: j.class, Detail: j.detail} - } - reported := v.byClass(roots, refs, mk) - if v.opts.Depth != VerifyData { - // Below depth data no content was read: final references to one - // chunk with different SHA-256s disagree with each other. - for _, r := range refs[min(1, len(refs)):] { - if r.sha != refs[0].sha { - v.finding(mk(judged{root: r.root, at: r.at, class: FindingContentMismatch, detail: fmt.Sprintf( - "references to this chunk disagree: SHA-256 %s here, %s under %s at index %d (depth data reads the chunk)", - hex.EncodeToString(r.sha[:]), hex.EncodeToString(refs[0].sha[:]), roots[refs[0].root].label, refs[0].at)})) - reported = true - break - } - } - } - if !reported { - var problem []string - for r := range v.seenChunks[id] { - if c, _ := v.judgeChunk(w, r.sha); c != "" { - problem = append(problem, r.root) - } - } - v.count(problem, w.class != "", gone) - } - } - if v.head != nil { - reported := map[string]bool{} - for _, idx := range sortedIndexes(v.head.chunks) { - id := chunkIdentity(v.vol, v.head.chunks[idx].Key) - if v.dropped[id] && !reported[id] { - reported[id] = true - i := idx - owner, key := splitIdentity(id) - fid := "" - if w := v.chunks[id]; w != nil { - fid = w.fid - } - v.finding(VerifyFinding{Root: v.head.label, Index: &i, Owner: owner, Key: key, FID: fid, Class: FindingRootInvalid, - Detail: "HEAD names a key it had dropped earlier in this pass; a key that left every root must not be named again"}) - } - } - } - for _, id := range sortedKeys(v.segs) { - s := v.segs[id] - var refs []judged - for ri, r := range roots { - for _, g := range sortedGroups(r.h.Segments) { - if ref := r.h.Segments[g]; segID(v.vol, ref) == id { - j := v.judgeSegment(context.Background(), s, segRef{group: g, chunkBytes: r.h.ChunkBytes, remoteLSN: r.h.RemoteLSN, ref: ref}) - refs = append(refs, judged{root: ri, at: g, class: j.class, detail: j.detail}) - } - } - } - mk := func(j judged) VerifyFinding { - g := j.at - return VerifyFinding{Root: roots[j.root].label, Segment: &g, Owner: s.owner, Key: s.key, FID: s.fid, Class: j.class, Detail: j.detail} - } - reported := v.byClass(roots, refs, mk) - // A tombstoned segment binding is reported beside the segment's - // outcome, at depths that check bindings. - tomb := s.tombstoned && v.opts.Depth != VerifyMeta - if tomb && len(refs) > 0 { - v.finding(mk(judged{root: refs[0].root, at: refs[0].at, class: FindingBindingTombstoned, detail: "segment binding tombstoned by GC"})) - reported = true - } - if !reported { - var problem []string - for r := range v.seenSegs[id] { - if tomb || v.judgeSegment(context.Background(), s, r.ref).class != "" { - problem = append(problem, r.root) - } - } - v.count(problem, s.class != "" || tomb, gone) - } - } -} - -// byClass reports one finding per class among refs (in final-root order): -// under the first reference of that class, its detail counting the others -// of that class and naming the next root carrying one. It reports whether it -// made one. -func (v *verifier) byClass(roots []*verifyView, refs []judged, mk func(judged) VerifyFinding) bool { - var order []string - first, more, next := map[string]int{}, map[string]int{}, map[string]string{} - for i, j := range refs { - if j.class == "" { - continue - } - f, ok := first[j.class] - if !ok { - first[j.class] = i - order = append(order, j.class) - continue - } - more[j.class]++ - if next[j.class] == "" && j.root != refs[f].root { - next[j.class] = roots[j.root].label - } - } - for _, c := range order { - j := refs[first[c]] - if n := more[c]; n > 0 { - j.detail += fmt.Sprintf("; %d more final reference(s) of this class", n) - if next[c] != "" { - j.detail += ", next under " + next[c] - } - } - v.finding(mk(j)) - } - return len(order) > 0 -} - -// count counts an object that yields no finding but had a bad outcome (bad) -// or a problem under a reference seen (problem: those references' roots), -// once: root deleted when a snapshot that is gone carried such a reference, -// otherwise superseded. -func (v *verifier) count(problem []string, bad bool, gone map[string]bool) { - if len(problem) == 0 && !bad { - return - } - for _, r := range problem { - if gone[r] { - v.res.RootDeletedDuringVerify++ - return - } - } - v.res.SupersededDuringVerify++ -} - -func sortedKeys[T any](m map[string]T) []string { - out := make([]string, 0, len(m)) - for k := range m { - out = append(out, k) - } - sort.Strings(out) - return out -} - -func sortedGroups(m map[uint64]storage.ChunkSegment) []uint64 { - out := make([]uint64, 0, len(m)) - for g := range m { - out = append(out, g) - } - sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) - return out -} - -// verifyPacer spaces reads so they average at most rate bytes per second. -type verifyPacer struct { - mu sync.Mutex - rate int64 // <= 0: unpaced - next time.Time -} - -func (p *verifyPacer) wait(ctx context.Context, n int64) error { - if p == nil || p.rate <= 0 || n <= 0 { - return ctx.Err() - } - p.mu.Lock() - now := time.Now() - if p.next.Before(now) { - p.next = now - } - start := p.next - p.next = p.next.Add(time.Duration(float64(n) / float64(p.rate) * float64(time.Second))) - p.mu.Unlock() - d := time.Until(start) - if d <= 0 { - return ctx.Err() - } - t := time.NewTimer(d) - defer t.Stop() - select { - case <-t.C: - return nil - case <-ctx.Done(): - return ctx.Err() - } -} - -func findingLess(a, b VerifyFinding) bool { - if a.Root != b.Root { - return a.Root < b.Root - } - if (a.Index == nil) != (b.Index == nil) { - return a.Index == nil // a root's and its segments' findings first - } - if as, bs := ptrOr(a.Segment), ptrOr(b.Segment); as != bs { - return as < bs - } - if ai, bi := ptrOr(a.Index), ptrOr(b.Index); ai != bi { - return ai < bi - } - if a.Key != b.Key { - return a.Key < b.Key - } - return a.Class < b.Class -} - -func ptrOr(p *uint64) uint64 { - if p == nil { - return 0 - } - return *p -} diff --git a/seaweed-block/core/frontend/chunkstore/verify_test.go b/seaweed-block/core/frontend/chunkstore/verify_test.go deleted file mode 100644 index 407b223b36..0000000000 --- a/seaweed-block/core/frontend/chunkstore/verify_test.go +++ /dev/null @@ -1,2036 +0,0 @@ -package chunkstore - -import ( - "context" - "crypto/sha256" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "path" - "strings" - "sync" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// A geometry with three segments' worth of chunks (one segment covers a -// logical GiB: 32768 chunks of 32 KiB), so a test can damage one segment -// and see the others still checked. -var verifyGeo = Geometry{NumBlocks: 3 * 32768 * 8, BlockSize: 4096, ChunkBlocks: 8} - -const ( - verifyChunkBytes = 8 * 4096 - verifyPer = 32768 // chunks per segment at verifyGeo -) - -// countingBlobs counts reads per fid, and fails reads of a fid on request -// with a transient (not "not found") error. -type countingBlobs struct { - gcBlobs - mu sync.Mutex - gets map[string]int - fail map[string]int // reads of fid still to fail; negative: every read -} - -var errTransient = errors.New("read tcp 127.0.0.1:8080: connection reset by peer") - -func (b *countingBlobs) Get(ctx context.Context, fid string) ([]byte, error) { - b.mu.Lock() - b.gets[fid]++ - n := b.fail[fid] - if n > 0 { - b.fail[fid] = n - 1 - } - b.mu.Unlock() - if n != 0 { - return nil, fmt.Errorf("chunkstore: read %s: %w", fid, errTransient) - } - return b.gcBlobs.Get(ctx, fid) -} - -// failReads makes the next n reads of fid fail (n < 0: all of them). -func (b *countingBlobs) failReads(fid string, n int) { - b.mu.Lock() - defer b.mu.Unlock() - b.fail[fid] = n -} - -func (b *countingBlobs) reads(fid string) int { - b.mu.Lock() - defer b.mu.Unlock() - return b.gets[fid] -} - -type verifyFixture struct { - t *testing.T - f *fakeFiler - b gcBlobs - cb *countingBlobs - c *Catalog - tag int -} - -func newVerifyFixture(t *testing.T, vols ...string) *verifyFixture { - t.Helper() - fx := &verifyFixture{t: t, f: newFakeFiler(), b: gcBlobs{newFakeBlobs()}} - fx.cb = &countingBlobs{gcBlobs: fx.b, gets: map[string]int{}, fail: map[string]int{}} - c, err := NewCatalog(manifestFilerBlobs{fx.f, fx.cb}, catBase) - if err != nil { - t.Fatal(err) - } - fx.c = c - for _, vol := range vols { - if err := fx.f.CreateEntry(context.Background(), catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - if _, err := c.EnsureVolume(context.Background(), vol, verifyGeo); err != nil { - t.Fatal(err) - } - } - return fx -} - -func verifyData(fill byte) []byte { - b := make([]byte, verifyChunkBytes) - for i := range b { - b[i] = fill + byte(i%7) - } - return b -} - -// publish installs a new HEAD for vol: the current chunks when keep is set, -// with set written under fresh keys over them. -func (fx *verifyFixture) publish(vol string, set map[uint64][]byte, keep bool) storage.ChunkHead { - fx.t.Helper() - ctx := context.Background() - r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) - if err != nil { - fx.t.Fatal(err) - } - cur, err := r.GetHead(ctx) - if err != nil { - fx.t.Fatal(err) - } - next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: max(cur.RemoteLSN, 42) + 1, Chunks: map[uint64]storage.ChunkRef{}} - if keep { - for idx, ref := range cur.Chunks { - next.Chunks[idx] = ref - } - } - for idx, data := range set { - fx.tag++ - key := fmt.Sprintf("chunks/t%d/c%d", fx.tag, idx) - if err := r.Put(ctx, key, data); err != nil { - fx.t.Fatal(err) - } - next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} - } - next, ids, err := r.PrepareManifest(ctx, cur, next, verifyChunkBytes) - if err != nil { - fx.t.Fatal(err) - } - gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next) - if err != nil { - fx.t.Fatal(err) - } - next.Gen = gen - for _, id := range ids { - if err := r.DeleteIntent(ctx, id); err != nil { - fx.t.Fatal(err) - } - } - return next -} - -// binding returns the directory and name of a qualified key's binding. -func bindingOf(t *testing.T, qkey string) (string, string) { - t.Helper() - owner, own, ok := strings.Cut(strings.TrimPrefix(qkey, "@"), "/") - if !ok || !strings.HasPrefix(qkey, "@") { - t.Fatalf("key %q is not owner-qualified", qkey) - } - return path.Join(catBase, owner, keysDir), url.PathEscape(own) -} - -func (fx *verifyFixture) fid(qkey string) string { - fx.t.Helper() - dir, name := bindingOf(fx.t, qkey) - e, err := fx.f.LookupEntry(context.Background(), dir, name) - if err != nil { - fx.t.Fatalf("binding of %s: %v", qkey, err) - } - return string(e.Extended[extFid]) -} - -func (fx *verifyFixture) deleteBinding(qkey string) { - fx.t.Helper() - dir, name := bindingOf(fx.t, qkey) - if err := fx.f.DeleteEntry(context.Background(), dir, name, nil); err != nil { - fx.t.Fatal(err) - } -} - -func (fx *verifyFixture) tombstone(qkey string) { - fx.t.Helper() - dir, name := bindingOf(fx.t, qkey) - fx.f.bumpExtended(path.Join(dir, name), extGCDeleted, "done") -} - -// needle edits the stored bytes of fid (nil deletes the needle). -func (fx *verifyFixture) needle(fid string, edit func([]byte) []byte) { - fx.t.Helper() - fx.b.mu.Lock() - defer fx.b.mu.Unlock() - d, ok := fx.b.data[fid] - if !ok { - fx.t.Fatalf("no needle %s", fid) - } - if out := edit(append([]byte(nil), d...)); out == nil { - delete(fx.b.data, fid) - } else { - fx.b.data[fid] = out - } -} - -func flipByte(d []byte) []byte { d[len(d)/2] ^= 0xff; return d } -func truncate(d []byte) []byte { return d[:len(d)-4096] } -func dropNeedle([]byte) []byte { return nil } - -func (fx *verifyFixture) verify(vol string, opts VerifyOptions) VerifyResult { - fx.t.Helper() - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - res, err := fx.c.Verify(ctx, vol, opts) - if err != nil { - fx.t.Fatalf("verify %s %+v: %v", vol, opts, err) - } - if !res.Complete { - fx.t.Fatalf("verify %s: incomplete without an error: %+v", vol, res) - } - return res -} - -// classes renders findings as "CLASS@index" (or "CLASS@seg"), in order. -func classes(res VerifyResult) []string { - var out []string - for _, f := range res.Findings { - switch { - case f.Index != nil: - out = append(out, fmt.Sprintf("%s@%d", f.Class, *f.Index)) - case f.Segment != nil: - out = append(out, fmt.Sprintf("%s@seg%d", f.Class, *f.Segment)) - default: - out = append(out, f.Class) - } - } - return out -} - -func wantClasses(t *testing.T, what string, res VerifyResult, want ...string) { - t.Helper() - got := classes(res) - if strings.Join(got, ",") != strings.Join(want, ",") { - t.Fatalf("%s: findings %v, want %v\n%+v", what, got, want, res.Findings) - } - n := 0 - for _, c := range res.FindingsByClass { - n += c - } - if n != len(res.Findings) { - t.Fatalf("%s: findingsByClass %v does not count %d findings", what, res.FindingsByClass, len(res.Findings)) - } -} - -func allDepths() []VerifyDepth { return []VerifyDepth{VerifyMeta, VerifyBindings, VerifyData} } - -// A healthy volume with three segments and a snapshot verifies clean at -// every depth; the shared segments are read once. -func TestVerify_CleanVolumeAllDepths(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) - if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { - t.Fatal(err) - } - for _, d := range allDepths() { - res := fx.verify("v1", VerifyOptions{Depth: d, AllSnapshots: true}) - wantClasses(t, string(d), res) - if len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen || len(res.Snapshots) != 1 || !strings.HasPrefix(res.Snapshots[0], "s1/") || - res.SegmentsChecked != 6 || res.SegmentReads != 3 || res.ChunksChecked != 6 || res.DistinctChunks != 3 { - t.Fatalf("%s: summary %+v", d, res) - } - wantRead := 0 - if d == VerifyData { - wantRead = 3 - } - if res.DistinctChunksRead != wantRead || res.BytesRead != int64(wantRead*verifyChunkBytes) { - t.Fatalf("%s: read %d chunks, %d bytes; want %d chunks", d, res.DistinctChunksRead, res.BytesRead, wantRead) - } - } -} - -// The gap the default depth closes: GC's mark never looks a rooted key up, -// so a HEAD key whose binding is missing passes it; verify reports it. -func TestVerify_MissingBindingGCPassesVerifyReports(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - fx.deleteBinding(h.Chunks[1].Key) - - now := time.Now().Add(24 * time.Hour) - g, err := NewCollector(fx.c, fx.b, GCConfig{Grace: time.Hour, IntentTTL: time.Hour, Now: func() time.Time { return now }, - IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) - if err != nil { - t.Fatal(err) - } - if _, err := g.Preview(context.Background()); err != nil { - t.Fatalf("GC mark: %v; the gap is that it passes", err) - } - - wantClasses(t, "meta", fx.verify("v1", VerifyOptions{Depth: VerifyMeta})) - res := fx.verify("v1", VerifyOptions{}) - wantClasses(t, "default depth", res, "BINDING_MISSING@1") - f := res.Findings[0] - if res.Depth != VerifyBindings || f.Volume != "v1" || f.Root != headLabel(h.Gen) || f.Owner != "v1" || !strings.HasPrefix(h.Chunks[1].Key, "@v1/"+f.Key) { - t.Fatalf("finding %+v (depth %s)", f, res.Depth) - } -} - -// A flipped byte is invisible to metadata; depth data catches it. -func TestVerify_FlippedByteDataOnly(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - fx.needle(fx.fid(h.Chunks[0].Key), flipByte) - wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{Depth: VerifyBindings})) - res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) - wantClasses(t, "data", res, "CONTENT_MISMATCH@0") - if res.Findings[0].FID != fx.fid(h.Chunks[0].Key) { - t.Fatalf("finding fid %q", res.Findings[0].FID) - } -} - -// A reference is judged by its hash first: a needle truncated in the store -// no longer matches its reference (CONTENT_MISMATCH); a needle that matches -// its reference but is not a chunk long is SIZE_MISMATCH. -func TestVerify_TruncatedNeedleSizeMismatch(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - fx.needle(fx.fid(h.Chunks[1].Key), truncate) - wantClasses(t, "truncated in the store", fx.verify("v1", VerifyOptions{Depth: VerifyData}), "CONTENT_MISMATCH@1") - - fx = newVerifyFixture(t, "v1") - fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)[:verifyChunkBytes-4096]}, false) - wantClasses(t, "short but as referenced", fx.verify("v1", VerifyOptions{Depth: VerifyData}), "SIZE_MISMATCH@1") -} - -func TestVerify_MissingNeedle(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) - wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{Depth: VerifyBindings})) - res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) - wantClasses(t, "data", res, "NEEDLE_MISSING@0") - // The store said "not found": that answer is not retried. - if res.ReadRetries != 0 || res.ChunksNotRead != 0 || fx.cb.reads(fx.fid(h.Chunks[0].Key)) != 1 { - t.Fatalf("not-found needle: %d retries, %d not read, %d reads; want 0, 0, 1", - res.ReadRetries, res.ChunksNotRead, fx.cb.reads(fx.fid(h.Chunks[0].Key))) - } -} - -// A read that fails once with an error other than "not found" is retried -// and then verifies: no finding. -func TestVerify_TransientReadIsRetried(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - chunk, seg := fx.fid(h.Chunks[0].Key), fx.fid(h.Segments[0].Key) - fx.cb.failReads(chunk, 1) - fx.cb.failReads(seg, 1) - res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) - wantClasses(t, "transient", res) - if res.ReadRetries != 2 || res.ChunksNotRead != 0 || res.DistinctChunksRead != 2 || fx.cb.reads(chunk) != 2 || fx.cb.reads(seg) != 2 { - t.Fatalf("transient errors: %d retries, %d not read, %d chunks read, reads chunk %d segment %d; want 2, 0, 2, 2, 2", - res.ReadRetries, res.ChunksNotRead, res.DistinctChunksRead, fx.cb.reads(chunk), fx.cb.reads(seg)) - } -} - -// A read that keeps failing with an error other than "not found" is -// READ_ERROR (not verified), never NEEDLE_MISSING or SEGMENT_UNREADABLE. -func TestVerify_PersistentReadErrorIsNotAMissingNeedle(t *testing.T) { - t.Run("chunk", func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - fid := fx.fid(h.Chunks[0].Key) - fx.cb.failReads(fid, -1) - res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) - wantClasses(t, "chunk read error", res, "READ_ERROR@0") - f := res.Findings[0] - if res.ChunksNotRead != 1 || res.ReadRetries != 2 || fx.cb.reads(fid) != 3 || f.FID != fid || - !strings.Contains(f.Detail, "not verified") || !strings.Contains(f.Detail, errTransient.Error()) { - t.Fatalf("chunk read error: %d not read, %d retries, %d reads, finding %+v", res.ChunksNotRead, res.ReadRetries, fx.cb.reads(fid), f) - } - }) - t.Run("segment", func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2)}, false) - fx.cb.failReads(fx.fid(h.Segments[0].Key), -1) - res := fx.verify("v1", VerifyOptions{}) - wantClasses(t, "segment read error", res, "READ_ERROR@seg0") - if res.ChunksNotRead != 1 || res.ChunksChecked != 1 { - t.Fatalf("segment read error: %+v", res) - } - }) -} - -// SWFS reports a needle absent (ErrBlobNotFound) only when every location -// answers 404; the error text is what it was before. -func TestSWFS_GetNotFoundIsErrBlobNotFound(t *testing.T) { - server := func(status int) string { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(status) })) - t.Cleanup(s.Close) - return strings.TrimPrefix(s.URL, "http://") - } - missing, broken := server(http.StatusNotFound), server(http.StatusInternalServerError) - // dropped closes every connection without an answer: a transport error. - dropped := func() string { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - conn, _, err := w.(http.Hijacker).Hijack() - if err == nil { - _ = conn.Close() - } - })) - t.Cleanup(s.Close) - return strings.TrimPrefix(s.URL, "http://") - }() - statusOf := map[string]int{missing: http.StatusNotFound, broken: http.StatusInternalServerError} - for _, tc := range []struct { - name string - hosts []string - notFound bool - }{ - {"every location 404", []string{missing, missing}, true}, - {"one location 500", []string{missing, broken}, false}, - {"only 500", []string{broken}, false}, - // Only the last answer is 404: still not proof of absence. - {"500 then 404", []string{broken, missing}, false}, - {"transport error then 404", []string{dropped, missing}, false}, - } { - t.Run(tc.name, func(t *testing.T) { - var locs []*filerpb.Location - for _, h := range tc.hosts { - locs = append(locs, &filerpb.Location{Url: h}) - } - c := startFakeFiler(t, &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: locs}}}}) - _, err := c.Get(context.Background(), "7,0000dead") - last := tc.hosts[len(tc.hosts)-1] - status := statusOf[last] - if err == nil || errors.Is(err, ErrBlobNotFound) != tc.notFound || err.Error() != fmt.Sprintf("chunkstore: read 7,0000dead: http %d from %s", status, last) { - t.Fatalf("Get: %v (not found %v), want not found %v", err, errors.Is(err, ErrBlobNotFound), tc.notFound) - } - }) - } -} - -// volumeAt is a LookupVolume answer placing volume vid at hosts. -func volumeAt(vid string, hosts ...string) *filerpb.LookupVolumeResponse { - var locs []*filerpb.Location - for _, h := range hosts { - locs = append(locs, &filerpb.Location{Url: h}) - } - return &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{vid: {Locations: locs}}} -} - -func (f *fakeFilerGRPC) volumeLookups() int { - f.mu.Lock() - defer f.mu.Unlock() - return f.volLookups -} - -// Cached locations can be stale (the volume moved): 404 from every cached -// location is not proof of absence. Get looks the volume up again and reads -// from the fresh locations; only 404 from every fresh location is -// ErrBlobNotFound. A read the cache serves makes no lookup. -func TestSWFS_GetStaleCachedLocationLooksUpAgain(t *testing.T) { - body := []byte("needle bytes") - server := func(status int) string { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(status) - if status == http.StatusOK { - _, _ = w.Write(body) - } - })) - t.Cleanup(s.Close) - return strings.TrimPrefix(s.URL, "http://") - } - oldLoc, newLoc, alsoMissing := server(http.StatusNotFound), server(http.StatusOK), server(http.StatusNotFound) - const fid = "7,0000dead" - for _, tc := range []struct { - name string - cached []string // nil: nothing cached - fresh string - wantBody bool - wantLookups int - }{ - {"cached location 404, fresh location has it", []string{oldLoc}, newLoc, true, 1}, - {"cached and fresh locations 404", []string{oldLoc}, alsoMissing, false, 1}, - {"warm cache", []string{newLoc}, newLoc, true, 0}, - {"nothing cached, fresh location 404", nil, alsoMissing, false, 1}, - } { - t.Run(tc.name, func(t *testing.T) { - f := &fakeFilerGRPC{lookupVol: volumeAt("7", tc.fresh)} - c := startFakeFiler(t, f) - if tc.cached != nil { - c.mu.Lock() - c.vidCache["7"] = tc.cached - c.mu.Unlock() - } - b, err := c.Get(context.Background(), fid) - if n := f.volumeLookups(); n != tc.wantLookups { - t.Fatalf("Get made %d volume lookups, want %d (err %v)", n, tc.wantLookups, err) - } - if tc.wantBody { - if err != nil || string(b) != string(body) { - t.Fatalf("Get: %q, %v; want the needle from %s", b, err, tc.fresh) - } - return - } - if !errors.Is(err, ErrBlobNotFound) || err.Error() != "chunkstore: read "+fid+": http 404 from "+tc.fresh { - t.Fatalf("Get: %v (not found %v); want ErrBlobNotFound from the fresh location %s", err, errors.Is(err, ErrBlobNotFound), tc.fresh) - } - }) - } -} - -// A volume that moved after its location was cached is not missing: depth -// data through SWFS reads every needle from the new location, no finding. -func TestVerify_MovedVolumeIsNotAMissingNeedle(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - var mu sync.Mutex - moved := false - serve := func(old bool) string { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - mu.Lock() - gone := old && moved - mu.Unlock() - fx.b.mu.Lock() - d, ok := fx.b.data[strings.TrimPrefix(r.URL.Path, "/")] - fx.b.mu.Unlock() - if gone || !ok { - w.WriteHeader(http.StatusNotFound) - return - } - _, _ = w.Write(d) - })) - t.Cleanup(s.Close) - return strings.TrimPrefix(s.URL, "http://") - } - oldLoc, newLoc := serve(true), serve(false) - vid, _, _ := strings.Cut(fx.fid(h.Chunks[0].Key), ",") - f := &fakeFilerGRPC{lookupVol: volumeAt(vid, oldLoc)} - sw := startFakeFiler(t, f) - ctx := context.Background() - // Warm the location cache at the old location, then move the volume. - if _, err := sw.Get(ctx, fx.fid(h.Chunks[0].Key)); err != nil { - t.Fatal(err) - } - mu.Lock() - moved = true - mu.Unlock() - f.mu.Lock() - f.lookupVol = volumeAt(vid, newLoc) - f.mu.Unlock() - - cat, err := NewCatalog(manifestFilerBlobs{fx.f, sw}, catBase) - if err != nil { - t.Fatal(err) - } - res, err := cat.Verify(ctx, "v1", VerifyOptions{Depth: VerifyData, BytesPerSecond: -1}) - if err != nil || !res.Complete { - t.Fatalf("verify: %v, %+v", err, res) - } - wantClasses(t, "moved volume", res) - if res.DistinctChunksRead != 2 || res.SegmentReads != 1 { - t.Fatalf("read %d chunks, %d segments; want 2, 1", res.DistinctChunksRead, res.SegmentReads) - } -} - -// A root that names a binding GC tombstoned: the chunk is gone or going. -func TestVerify_TombstonedBinding(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - fx.tombstone(h.Chunks[0].Key) - fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) - wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{}), "BINDING_TOMBSTONED@0") - // No read of a tombstoned binding's needle: one finding, not two. - res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) - wantClasses(t, "data", res, "BINDING_TOMBSTONED@0") - if res.DistinctChunksRead != 1 { - t.Fatalf("read %d chunks, want only the sound one", res.DistinctChunksRead) - } -} - -// A corrupt segment (its content no longer matches the root's reference: a -// mismatch for that root) and a segment whose binding is gone are each a -// finding; the pass goes on to the other segments and their chunks. -func TestVerify_UnreadableSegmentContinues(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) - fx.needle(fx.fid(h.Segments[0].Key), flipByte) - fx.deleteBinding(h.Segments[1].Key) - fx.deleteBinding(h.Chunks[2*verifyPer].Key) - res := fx.verify("v1", VerifyOptions{}) - wantClasses(t, "bindings", res, "CONTENT_MISMATCH@seg0", "BINDING_MISSING@seg1", fmt.Sprintf("BINDING_MISSING@%d", 2*verifyPer)) - if res.SegmentsChecked != 3 || res.ChunksChecked != 1 { - t.Fatalf("summary %+v", res) - } - if !strings.Contains(res.Findings[0].Detail, "SHA-256") || res.Findings[0].Key != h.Segments[0].Key { - t.Fatalf("corrupt segment finding %+v", res.Findings[0]) - } -} - -// A chunk that leaves HEAD and is collected while the pass runs is not a -// finding when no root names it at the final read (a bad outcome is then -// counted as superseded during verify; read content has no reference left -// to compare with); under a snapshot that still names it, it is one. -func TestVerify_SupersededDuringPass(t *testing.T) { - type damage struct { - name string - depth VerifyDepth - apply func(fx *verifyFixture, qkey string) - class string - } - cases := []damage{ - {"binding deleted", VerifyBindings, func(fx *verifyFixture, k string) { - fid := fx.fid(k) - fx.deleteBinding(k) - fx.needle(fid, dropNeedle) - }, FindingBindingMissing}, - {"binding tombstoned", VerifyBindings, func(fx *verifyFixture, k string) { - fx.tombstone(k) - fx.needle(fx.fid(k), dropNeedle) - }, FindingBindingTombstoned}, - {"needle deleted", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), dropNeedle) }, FindingNeedleMissing}, - {"needle overwritten", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), flipByte) }, FindingContentMismatch}, - {"needle unreadable", VerifyData, func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) }, FindingReadError}, - } - for _, tc := range cases { - for _, withSnap := range []bool{false, true} { - t.Run(fmt.Sprintf("%s/snapshot=%v", tc.name, withSnap), func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - if withSnap { - if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { - t.Fatal(err) - } - } - old := h.Chunks[0].Key - hooked := 0 - opts := VerifyOptions{Depth: tc.depth, AllSnapshots: withSnap} - opts.hook = func(stage string) { - if stage != verifyHookHeadWalked { - return - } - hooked++ - // After verify read HEAD: the owner replaces chunk 0 and GC - // collects the old one. - fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) - tc.apply(fx, old) - } - res := fx.verify("v1", opts) - if !withSnap { - wantClasses(t, "HEAD only", res) - } else { - wantClasses(t, "with the snapshot", res, tc.class+"@0") - if !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") { - t.Fatalf("finding root %q, want the snapshot", res.Findings[0].Root) - } - } - superseded := 0 - if !withSnap { - superseded = 1 // a problem under a reference seen, and no finding - } - // The closing read sees the owner's new HEAD: it is the final view. - if hooked != 1 || res.SupersededDuringVerify != superseded || len(res.HeadGens) != 2 || res.HeadGens[0] != h.Gen { - t.Fatalf("hooked %d, superseded %d, gens %v; want 1, %d, [%d next]", hooked, res.SupersededDuringVerify, res.HeadGens, superseded, h.Gen) - } - }) - } - } -} - -// A miss under a snapshot is a finding only while that attempt is still -// active at the final read: a snapshot deleted during the pass, whose chunk -// is then collected, is listed as not fully covered, its bad chunk counted -// as root deleted during verify, not reported. -func TestVerify_SnapshotDeletedDuringPass(t *testing.T) { - cases := []struct { - name string - depth VerifyDepth - apply func(fx *verifyFixture, qkey string) - class string - }{ - {"binding deleted", VerifyBindings, func(fx *verifyFixture, k string) { - fid := fx.fid(k) - fx.deleteBinding(k) - fx.needle(fid, dropNeedle) - }, FindingBindingMissing}, - {"needle overwritten", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), flipByte) }, FindingContentMismatch}, - {"needle truncated", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), truncate) }, FindingContentMismatch}, - {"needle unreadable", VerifyData, func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) }, FindingReadError}, - } - for _, tc := range cases { - for _, deleteSnap := range []bool{false, true} { - t.Run(fmt.Sprintf("%s/deleted=%v", tc.name, deleteSnap), func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - s, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h) - if err != nil { - t.Fatal(err) - } - // HEAD moves on before the pass: only the snapshot names the old chunk 0. - fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) - old := h.Chunks[0].Key - opts := VerifyOptions{Depth: tc.depth, AllSnapshots: true} - opts.hook = func(stage string) { - if stage != verifyHookRootsWalked { - return - } - if deleteSnap { - if st, err := fx.c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting { - t.Errorf("delete s1: %q %v", st, err) - } - } - tc.apply(fx, old) - } - res := fx.verify("v1", opts) - if len(res.Snapshots) != 1 { - t.Fatalf("snapshots checked %v", res.Snapshots) - } - if !deleteSnap { - wantClasses(t, "active snapshot", res, tc.class+"@0") - if res.RootDeletedDuringVerify != 0 || len(res.SnapshotsDeletedDuringVerify) != 0 || !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") { - t.Fatalf("active snapshot: %+v", res) - } - return - } - wantClasses(t, "deleted snapshot", res) - // The gone snapshot carried the only problem reference. - if res.RootDeletedDuringVerify != 1 || res.SupersededDuringVerify != 0 || - len(res.SnapshotsDeletedDuringVerify) != 1 || res.SnapshotsDeletedDuringVerify[0] != res.Snapshots[0] { - t.Fatalf("deleted snapshot: root deleted %d, superseded %d, deleted list %v (checked %v, created %+v)", - res.RootDeletedDuringVerify, res.SupersededDuringVerify, res.SnapshotsDeletedDuringVerify, res.Snapshots, s.Name) - } - }) - } - } -} - -// A chunk named by HEAD (superseded during the pass) and by a snapshot that -// is still active is one finding, under the snapshot (and not counted as -// superseded: a root still names it). -func TestVerify_SharedChunkReportedUnderStillNamingRoot(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { - t.Fatal(err) - } - opts := VerifyOptions{Depth: VerifyData, AllSnapshots: true} - opts.hook = func(stage string) { - if stage == verifyHookRootsWalked { - fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) - fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) - } - } - res := fx.verify("v1", opts) - wantClasses(t, "shared chunk", res, "NEEDLE_MISSING@0") - if !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") || res.SupersededDuringVerify != 0 || res.RootDeletedDuringVerify != 0 { - t.Fatalf("finding under %q, superseded %d, root deleted %d; want the snapshot, 0, 0", - res.Findings[0].Root, res.SupersededDuringVerify, res.RootDeletedDuringVerify) - } -} - -// A HEAD that advances mid-pass: the result lists both generations, only -// the segment whose key changed is read again, and the references checked -// are the final view's. -func TestVerify_HeadRefreshRewalksChangedSegments(t *testing.T) { - for _, d := range []VerifyDepth{VerifyBindings, VerifyData} { - t.Run(string(d), func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) - var h2 storage.ChunkHead - opts := VerifyOptions{Depth: d, RefreshInterval: time.Minute} - opts.hook = func(stage string) { - if stage == verifyHookHeadWalked { - h2 = fx.publish("v1", map[uint64][]byte{verifyPer: verifyData(7)}, true) - } - } - fx.c.SetClock(tickingClock(time.Minute)) // past the refresh interval at every read - res := fx.verify("v1", opts) - wantClasses(t, "refresh", res) - if len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen { - t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) - } - if h2.Segments[0] != h1.Segments[0] || h2.Segments[2] != h1.Segments[2] || h2.Segments[1] == h1.Segments[1] { - t.Fatal("fixture: the new HEAD should change only segment 1") - } - if res.SegmentReads != 4 || res.SegmentsChecked != 6 { - t.Fatalf("segment reads %d (checked %d); want 3 + 1 changed", res.SegmentReads, res.SegmentsChecked) - } - if res.DistinctChunks != 4 || res.ChunksChecked != 3 { - t.Fatalf("chunks %d distinct, %d checked; want the 3 first and the 1 new, 3 final references", res.DistinctChunks, res.ChunksChecked) - } - if d == VerifyData && (res.DistinctChunksRead != 4 || fx.cb.reads(fx.fid(h2.Chunks[verifyPer].Key)) != 1) { - t.Fatalf("read %d chunks; want 4, the new one included", res.DistinctChunksRead) - } - }) - } -} - -// A chunk shared by HEAD and two snapshots is fetched once. -func TestVerify_DedupSharedChunkReadOnce(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - for _, n := range []string{"s1", "s2"} { - if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: n, RequestID: "r-" + n}, h); err != nil { - t.Fatal(err) - } - } - res := fx.verify("v1", VerifyOptions{Depth: VerifyData, AllSnapshots: true}) - wantClasses(t, "dedup", res) - if res.ChunksChecked != 6 || res.DistinctChunks != 2 || res.DistinctChunksRead != 2 || len(res.Snapshots) != 2 { - t.Fatalf("summary %+v", res) - } - for _, idx := range []uint64{0, 1} { - if n := fx.cb.reads(fx.fid(h.Chunks[idx].Key)); n != 1 { - t.Fatalf("chunk %d read %d times, want once", idx, n) - } - } - // One named snapshot works the same way. - res = fx.verify("v1", VerifyOptions{Depth: VerifyBindings, Snapshot: "s2"}) - if len(res.Snapshots) != 1 || !strings.HasPrefix(res.Snapshots[0], "s2/") || res.ChunksChecked != 4 { - t.Fatalf("named snapshot: %+v", res) - } - if _, err := fx.c.Verify(context.Background(), "v1", VerifyOptions{Snapshot: "nope"}); CodeOf(err) != CodeSnapshotNotFound { - t.Fatalf("missing snapshot: %v", err) - } -} - -// A fork's qualified keys are checked in the owner volume's keys/, and its -// fork record against the parent snapshot. -func TestVerify_ForkQualifiedKeysAndRecord(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { - t.Fatal(err) - } - if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { - t.Fatal(err) - } - for _, d := range allDepths() { - wantClasses(t, "clean fork "+string(d), fx.verify("v2", VerifyOptions{Depth: d})) - } - // The fork wrote no binding of its own: every chunk resolves to v1. - fx.deleteBinding(h.Chunks[1].Key) - res := fx.verify("v2", VerifyOptions{}) - wantClasses(t, "fork, parent binding gone", res, "BINDING_MISSING@1") - if res.Findings[0].Owner != "v1" || res.Findings[0].Volume != "v2" { - t.Fatalf("finding %+v, want owner v1 in volume v2", res.Findings[0]) - } - - // A fork record whose digest is not the parent snapshot's. - e, err := fx.f.LookupEntry(ctx, path.Join(catBase, "v2"), volumeName) - if err != nil { - t.Fatal(err) - } - var vi VolumeInfo - if err := json.Unmarshal(e.Content, &vi); err != nil { - t.Fatal(err) - } - vi.Fork.HeadSHA256 = strings.Repeat("0", 64) - if e.Content, err = json.Marshal(vi); err != nil { - t.Fatal(err) - } - if err := fx.f.UpdateEntry(ctx, path.Join(catBase, "v2"), e, nil); err != nil { - t.Fatal(err) - } - res = fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) - wantClasses(t, "tampered fork record", res, "FORK_RECORD_MISMATCH") - if res.Findings[0].Owner != "v1" || !strings.Contains(res.Findings[0].Detail, "s1") { - t.Fatalf("finding %+v", res.Findings[0]) - } -} - -// A fork whose source volume was deleted afterwards has nothing to compare -// its fork record with. That is not damage: no finding, and the result -// says the source is gone. While the source volume still exists, a missing -// parent snapshot attempt is a finding. -func TestVerify_ForkSourceVolumeDeleted(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) - if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { - t.Fatal(err) - } - if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { - t.Fatal(err) - } - // The parent's snapshot attempts vanish, the source volume remains. - dir := path.Join(catBase, "v1", snapsDir, "s1") - es, err := fx.f.ListEntries(ctx, dir, "", "", 100) - if err != nil || len(es) == 0 { - t.Fatalf("attempts of s1: %d, %v", len(es), err) - } - for _, e := range es { - if err := fx.f.DeleteEntry(ctx, dir, e.GetName(), nil); err != nil { - t.Fatal(err) - } - } - res := fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) - wantClasses(t, "attempts gone, source present", res, "FORK_RECORD_MISMATCH") - if res.ForkSourceGone { - t.Fatal("ForkSourceGone set while the source volume exists") - } - // Now the source volume record goes too. - if err := fx.f.DeleteEntry(ctx, path.Join(catBase, "v1"), volumeName, nil); err != nil { - t.Fatal(err) - } - res = fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) - wantClasses(t, "source volume deleted", res) - if !res.ForkSourceGone { - t.Fatal("ForkSourceGone not set") - } -} - -// Intent bookkeeping: an old capture intent below HEAD's epoch naming keys -// HEAD does not reference is reported; one naming a key HEAD binds, a -// current one and a copy intent are not. -func TestVerify_IntentStale(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) - root := path.Join(catBase, "v1") - headKey := strings.TrimPrefix(h.Chunks[0].Key, "@v1/") - stale, err := putIntent(ctx, fx.f, root, storage.ChunkIntent{Gen: 1, Epoch: 0, Holder: "old/r1", Keys: []string{"chunks/lost/k"}}) - if err != nil { - t.Fatal(err) - } - for _, in := range []storage.ChunkIntent{ - {Gen: 1, Epoch: 0, Holder: "old/r1", Keys: []string{headKey}}, // HEAD binds its key - {Gen: 2, Epoch: 1, Holder: "h1", Keys: []string{"chunks/next/k"}}, // the current epoch - {Gen: 0, Epoch: 0, Holder: "snapshot:v1/s9/1-0000000000000000", Keys: []string{"x/y"}}, // a copy intent - } { - if _, err := putIntent(ctx, fx.f, root, in); err != nil { - t.Fatal(err) - } - } - wantClasses(t, "young intents", fx.verify("v1", VerifyOptions{})) - fx.c.SetClock(func() time.Time { return time.Now().Add(2 * time.Hour) }) - res := fx.verify("v1", VerifyOptions{Depth: VerifyMeta}) - wantClasses(t, "old intents", res, "INTENT_STALE") - if res.Findings[0].Root != "intent "+stale { - t.Fatalf("stale intent finding %+v, want intent %s", res.Findings[0], stale) - } -} - -// recordingStore counts every write the catalog makes through it. -type recordingStore struct { - Filer - blobs *countingBlobs - mu sync.Mutex - creates, updates, deletes int - blobPuts, blobDeletes, reads int -} - -func (r *recordingStore) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, o bool) error { - r.mu.Lock() - r.creates++ - r.mu.Unlock() - return r.Filer.CreateEntry(ctx, dir, e, o) -} -func (r *recordingStore) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, x map[string][]byte) error { - r.mu.Lock() - r.updates++ - r.mu.Unlock() - return r.Filer.UpdateEntry(ctx, dir, e, x) -} -func (r *recordingStore) DeleteEntry(ctx context.Context, dir, name string, x map[string][]byte) error { - r.mu.Lock() - r.deletes++ - r.mu.Unlock() - return r.Filer.DeleteEntry(ctx, dir, name, x) -} -func (r *recordingStore) Put(ctx context.Context, d []byte) (string, error) { - r.mu.Lock() - r.blobPuts++ - r.mu.Unlock() - return r.blobs.Put(ctx, d) -} -func (r *recordingStore) Get(ctx context.Context, fid string) ([]byte, error) { - r.mu.Lock() - r.reads++ - r.mu.Unlock() - return r.blobs.Get(ctx, fid) -} -func (r *recordingStore) DeleteBlob(ctx context.Context, fid string) error { - r.mu.Lock() - r.blobDeletes++ - r.mu.Unlock() - return r.blobs.DeleteBlob(ctx, fid) -} - -// Verify writes nothing, at any depth, also on the miss, superseded and -// refresh paths and for a fork. -func TestVerify_ReadOnlyAtEveryDepth(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2), verifyPer: verifyData(3)}, false) - if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { - t.Fatal(err) - } - if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { - t.Fatal(err) - } - if _, err := putIntent(ctx, fx.f, path.Join(catBase, "v1"), storage.ChunkIntent{Gen: 1, Holder: "old", Keys: []string{"k/old"}}); err != nil { - t.Fatal(err) - } - fx.needle(fx.fid(h.Chunks[1].Key), flipByte) - rec := &recordingStore{Filer: fx.f, blobs: fx.cb} - cat, err := NewCatalog(rec, catBase) - if err != nil { - t.Fatal(err) - } - cat.SetClock(func() time.Time { return time.Now().Add(2 * time.Hour) }) - for _, d := range allDepths() { - for _, vol := range []string{"v1", "v2"} { - opts := VerifyOptions{Depth: d, AllSnapshots: true, RefreshInterval: time.Millisecond} - opts.hook = func(stage string) { - if vol == "v1" && stage == verifyHookHeadWalked { - // Writes by the owner (through the fixture, not the - // recorder): a new HEAD, and the old chunk 0 collected. - r, _ := NewChunkRemote(fx.f, fx.b, path.Join(catBase, "v1")) - cur, err := r.GetHead(ctx) - if err != nil { - t.Error(err) - return - } - oldFid := fx.fid(cur.Chunks[0].Key) - fx.publish("v1", map[uint64][]byte{0: verifyData(byte(10 + len(d)))}, true) - fx.needle(oldFid, dropNeedle) - time.Sleep(3 * time.Millisecond) - } - } - res, err := cat.Verify(ctx, vol, opts) - if err != nil || !res.Complete { - t.Fatalf("%s %s: %v", d, vol, err) - } - if d == VerifyData && rec.reads == 0 { - t.Fatalf("%s %s: no blob reads recorded; the recorder is not in the path", d, vol) - } - } - } - if rec.creates+rec.updates+rec.deletes+rec.blobPuts+rec.blobDeletes != 0 { - t.Fatalf("verify wrote: %d creates, %d updates, %d deletes, %d blob puts, %d blob deletes", - rec.creates, rec.updates, rec.deletes, rec.blobPuts, rec.blobDeletes) - } -} - -// A chunk index past the end of VOLUME's geometry is a GEOMETRY finding. -func TestVerify_GeometryOutsideVolume(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - fx.publish("v1", map[uint64][]byte{0: verifyData(1), 2 * verifyPer: verifyData(2)}, false) - e, err := fx.f.LookupEntry(ctx, path.Join(catBase, "v1"), volumeName) - if err != nil { - t.Fatal(err) - } - var vi VolumeInfo - if err := json.Unmarshal(e.Content, &vi); err != nil { - t.Fatal(err) - } - vi.NumBlocks = 2 * verifyPer * 8 - if e.Content, err = json.Marshal(vi); err != nil { - t.Fatal(err) - } - if err := fx.f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { - t.Fatal(err) - } - wantClasses(t, "meta", fx.verify("v1", VerifyOptions{Depth: VerifyMeta}), fmt.Sprintf("GEOMETRY@%d", 2*verifyPer)) -} - -// A HEAD that does not decode is a finding, not a failure to run. -func TestVerify_InvalidHeadRoot(t *testing.T) { - fx := newVerifyFixture(t, "v1") - fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) - fx.f.bumpExtended(path.Join(catBase, "v1", headName), extGen, "999") - res := fx.verify("v1", VerifyOptions{}) - wantClasses(t, "bad HEAD", res, "ROOT_INVALID") - if len(res.HeadGens) != 0 { - t.Fatalf("covered gens %v of an invalid HEAD", res.HeadGens) - } -} - -// Only an inability to continue stops the pass: the result then says it is -// incomplete and keeps what was covered. -func TestVerify_ContextEndedIsIncomplete(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - opts := VerifyOptions{Depth: VerifyData} - opts.hook = func(stage string) { cancel() } - res, err := fx.c.Verify(ctx, "v1", opts) - if !errors.Is(err, context.Canceled) || res.Complete || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { - t.Fatalf("cancelled pass: %v, %+v", err, res) - } - if _, err := fx.c.Verify(context.Background(), "nope", VerifyOptions{}); CodeOf(err) != CodeNotChunkVolume { - t.Fatalf("missing volume: %v", err) - } -} - -// heldReads holds the read of one needle open until the reader's context -// ends (or the test releases it), and counts the reads in progress. -type heldReads struct { - Blobs - fid string - onEnter func() // runs once, when the held read has started - entered chan struct{} // closed when the held read has started - once sync.Once - - released chan struct{} // closed by release: the escape when cancellation fails - releaseOnce sync.Once - - mu sync.Mutex - active int - ended error // the held read's context error, once its context ended -} - -func newHeldReads(b Blobs, fid string) *heldReads { - return &heldReads{Blobs: b, fid: fid, entered: make(chan struct{}), released: make(chan struct{})} -} - -func (h *heldReads) release() { h.releaseOnce.Do(func() { close(h.released) }) } - -// verifyEscape bounds a test's wait for a Verify that should return at -// once; it only turns a hang into a failure, it is not a success criterion. -const verifyEscape = 30 * time.Second - -type verifyOutcome struct { - res VerifyResult - err error -} - -// verifyBounded runs cat.Verify in a goroutine and returns its result, or -// fails the test when it has not returned within verifyEscape. The cleanup, -// registered before the launch, releases the held read and joins the call. -func verifyBounded(t *testing.T, cat *Catalog, ctx context.Context, opts VerifyOptions, held *heldReads) (VerifyResult, error) { - t.Helper() - done := make(chan verifyOutcome, 1) - t.Cleanup(func() { - held.release() - select { - case out := <-done: - done <- out - case <-time.After(verifyEscape): - t.Error("Verify did not return even after its held read was released") - } - }) - go func() { - res, err := cat.Verify(ctx, "v1", opts) - done <- verifyOutcome{res, err} - }() - select { - case out := <-done: - done <- out // for the cleanup's join - return out.res, out.err - case <-time.After(verifyEscape): - t.Fatalf("Verify did not return within %s: the read in progress was not cancelled and joined", verifyEscape) - return VerifyResult{}, nil - } -} - -func (h *heldReads) Get(ctx context.Context, fid string) ([]byte, error) { - h.mu.Lock() - h.active++ - h.mu.Unlock() - defer func() { - h.mu.Lock() - h.active-- - h.mu.Unlock() - }() - if fid != h.fid { - return h.Blobs.Get(ctx, fid) - } - h.once.Do(func() { - close(h.entered) - if h.onEnter != nil { - h.onEnter() - } - }) - select { - case <-ctx.Done(): - case <-h.released: - return nil, fmt.Errorf("chunkstore: read %s: released by the test", fid) - } - h.mu.Lock() - h.ended = ctx.Err() - h.mu.Unlock() - return nil, fmt.Errorf("chunkstore: read %s: %w", fid, ctx.Err()) -} - -func (h *heldReads) state() (active int, ended error) { - h.mu.Lock() - defer h.mu.Unlock() - return h.active, h.ended -} - -var errFilerDown = errors.New("filer: connection refused") - -// tickingClock advances by step at every reading: with a refresh interval -// of step, a pass refreshes HEAD at every opportunity, without waiting. -func tickingClock(step time.Duration) func() time.Time { - var mu sync.Mutex - now := time.Now() - return func() time.Time { - mu.Lock() - defer mu.Unlock() - now = now.Add(step) - return now - } -} - -// headFailsDuringRead fails HEAD reads made while the held read is in -// progress. The first HEAD read after the chunk key listing passes (it is -// the refresh before the first chunk, the held one, is handed to a reader); -// later ones wait until the held read has started, then fail. -type headFailsDuringRead struct { - Filer - root, keys string - entered <-chan struct{} - released <-chan struct{} // the test's escape - - mu sync.Mutex - listed bool - after int // HEAD reads since the listing -} - -func (f *headFailsDuringRead) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { - if dir == f.keys { - f.mu.Lock() - f.listed = true - f.mu.Unlock() - } - return f.Filer.ListEntries(ctx, dir, prefix, after, limit) -} - -func (f *headFailsDuringRead) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { - if dir == f.root && name == headName { - f.mu.Lock() - n := 0 - if f.listed { - f.after++ - n = f.after - } - f.mu.Unlock() - if n >= 2 { - select { - case <-f.entered: - return nil, errFilerDown - case <-ctx.Done(): - return nil, ctx.Err() - case <-f.released: - return nil, errors.New("released by the test") - } - } - } - return f.Filer.LookupEntry(ctx, dir, name) -} - -// A HEAD refresh that fails while a chunk read is in progress stops that -// read at once: Verify returns the filer's error (not the cancellation it -// caused in the reader), incomplete, with no read left running, and long -// before the caller's own deadline. -func TestVerify_FailedRefreshCancelsReadInProgress(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - held := newHeldReads(fx.cb, fx.fid(h.Chunks[0].Key)) - filer := &headFailsDuringRead{Filer: fx.f, root: path.Join(catBase, "v1"), keys: path.Join(catBase, "v1", keysDir), - entered: held.entered, released: held.released} - cat, err := NewCatalog(manifestFilerBlobs{filer, held}, catBase) - if err != nil { - t.Fatal(err) - } - cat.SetClock(tickingClock(time.Minute)) - // The caller's deadline tells a read cancelled by the failed refresh - // from one that ran into it: Verify must end well before it. - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - defer cancel() - res, err := verifyBounded(t, cat, ctx, VerifyOptions{Depth: VerifyData, RefreshInterval: time.Minute, BytesPerSecond: -1}, held) - active, ended := held.state() - if !errors.Is(err, errFilerDown) || !strings.Contains(err.Error(), "refresh HEAD") { - t.Fatalf("verify: %v; want the HEAD refresh error", err) - } - if ctx.Err() != nil || !errors.Is(ended, context.Canceled) { - t.Fatalf("held read ended with %v (caller context %v); want cancelled by the failed refresh", ended, ctx.Err()) - } - if res.Complete || active != 0 { - t.Fatalf("complete %v, %d reads still running; want incomplete, none", res.Complete, active) - } -} - -// Cancelling the caller's context while a chunk read is in progress ends -// that read and the pass: incomplete, the cancellation reported, no read -// left running. -func TestVerify_CancelDuringReadJoinsReaders(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - held := newHeldReads(fx.cb, fx.fid(h.Chunks[0].Key)) - cat, err := NewCatalog(manifestFilerBlobs{fx.f, held}, catBase) - if err != nil { - t.Fatal(err) - } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - held.onEnter = cancel - res, err := verifyBounded(t, cat, ctx, VerifyOptions{Depth: VerifyData, BytesPerSecond: -1}, held) - active, ended := held.state() - select { - case <-held.entered: - default: - t.Fatal("the held read never started") - } - if !errors.Is(err, context.Canceled) || res.Complete || !errors.Is(ended, context.Canceled) || active != 0 { - t.Fatalf("verify: %v, complete %v; held read ended with %v, %d reads still running", err, res.Complete, ended, active) - } - if len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { - t.Fatalf("covered gens %v, want [%d]", res.HeadGens, h.Gen) - } -} - -// republish installs a new HEAD for vol with the current chunk references -// as edit leaves them (keys are not uploaded again). -func (fx *verifyFixture) republish(vol string, edit func(map[uint64]storage.ChunkRef)) storage.ChunkHead { - fx.t.Helper() - ctx := context.Background() - r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) - if err != nil { - fx.t.Fatal(err) - } - cur, err := r.GetHead(ctx) - if err != nil { - fx.t.Fatal(err) - } - next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: cur.RemoteLSN + 1, Chunks: map[uint64]storage.ChunkRef{}} - for idx, ref := range cur.Chunks { - next.Chunks[idx] = ref - } - edit(next.Chunks) - next, ids, err := r.PrepareManifest(ctx, cur, next, verifyChunkBytes) - if err != nil { - fx.t.Fatal(err) - } - gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next) - if err != nil { - fx.t.Fatal(err) - } - next.Gen = gen - for _, id := range ids { - if err := r.DeleteIntent(ctx, id); err != nil { - fx.t.Fatal(err) - } - } - return next -} - -// wrongHash flips the reference SHA-256 of chunk idx, keeping its key. -func wrongHash(idx uint64) func(map[uint64]storage.ChunkRef) { - return func(c map[uint64]storage.ChunkRef) { - ref := c[idx] - ref.SHA256[0] ^= 0xff - c[idx] = ref - } -} - -// beforeRead runs fn once, before the first read of fid. -type beforeRead struct { - Blobs - fid string - fn func() - once sync.Once -} - -func (b *beforeRead) Get(ctx context.Context, fid string) ([]byte, error) { - if fid == b.fid { - b.once.Do(b.fn) - } - return b.Blobs.Get(ctx, fid) -} - -// A final reference to a chunk under the same key but with another SHA-256 -// is a finding: at depth data it is compared with the content read once for -// that chunk (the chunk is not read again), below data with the other final -// references. A reference only an earlier HEAD view carried is not compared -// (detail "": no finding). -func TestVerify_SameKeyWithAnotherHashIsAFinding(t *testing.T) { - for _, tc := range []struct { - name string - depth VerifyDepth - when string // "walked": HEAD changes once the first view is walked; "read": once chunk 0 was read; "snapshot": before the pass - detail string - }{ - {"refreshed HEAD, data, before the read", VerifyData, "walked", "needle SHA-256"}, - {"refreshed HEAD, data, after the read", VerifyData, "read", "needle SHA-256"}, - {"refreshed HEAD, bindings", VerifyBindings, "walked", ""}, - {"snapshot, data", VerifyData, "snapshot", "needle SHA-256"}, - {"snapshot, bindings", VerifyBindings, "snapshot", "disagree"}, - } { - t.Run(tc.name, func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - fid0 := fx.fid(h1.Chunks[0].Key) - var h2 storage.ChunkHead - opts := VerifyOptions{Depth: tc.depth, BytesPerSecond: -1, RefreshInterval: time.Minute, Concurrency: 1} - cat := fx.c - switch tc.when { - case "walked": - opts.hook = func(stage string) { - if stage == verifyHookHeadWalked { - h2 = fx.republish("v1", wrongHash(0)) - } - } - case "read": - // One reader: chunk 0 is read completely before chunk 1 is - // handed out, so its content is known when HEAD changes. - br := &beforeRead{Blobs: fx.cb, fid: fx.fid(h1.Chunks[1].Key), fn: func() { h2 = fx.republish("v1", wrongHash(0)) }} - var err error - if cat, err = NewCatalog(manifestFilerBlobs{fx.f, br}, catBase); err != nil { - t.Fatal(err) - } - case "snapshot": - if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h1); err != nil { - t.Fatal(err) - } - h2 = fx.republish("v1", wrongHash(0)) - opts.AllSnapshots = true - } - cat.SetClock(tickingClock(time.Minute)) - res, err := cat.Verify(ctx, "v1", opts) - if err != nil || !res.Complete { - t.Fatalf("verify: %v, %+v", err, res) - } - if tc.detail == "" { - wantClasses(t, tc.name, res) - return - } - wantClasses(t, tc.name, res, "CONTENT_MISMATCH@0") - f := res.Findings[0] - wantRoot := headLabel(h2.Gen) - if tc.when == "snapshot" && tc.depth != VerifyData { - // HEAD is walked first; the snapshot's reference is the one - // that disagrees with it. - wantRoot = "snapshot s1/" - } - if !strings.HasPrefix(f.Root, wantRoot) || !strings.Contains(f.Detail, tc.detail) || f.Key == "" { - t.Fatalf("finding %+v; want under %q, detail with %q", f, wantRoot, tc.detail) - } - if tc.when != "snapshot" && (len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen) { - t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) - } - if tc.depth == VerifyData && (res.DistinctChunksRead != 2 || fx.cb.reads(fid0) != 1) { - t.Fatalf("read %d chunks, chunk 0 %d times; want 2, chunk 0 once", res.DistinctChunksRead, fx.cb.reads(fid0)) - } - }) - } -} - -// A chunk read once whose final references (HEAD and an active snapshot) -// carry two different wrong SHA-256s is one CONTENT_MISMATCH, under HEAD, -// whose detail counts the other differing reference and names its root. -func TestVerify_TwoWrongReferencesAreOneFinding(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - h2 := fx.republish("v1", wrongHash(0)) // the snapshot keeps this wrong hash - if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h2); err != nil { - t.Fatal(err) - } - h3 := fx.republish("v1", func(c map[uint64]storage.ChunkRef) { // HEAD: another wrong hash, same key - ref := c[0] - ref.SHA256[1] ^= 0xff - c[0] = ref - }) - if h3.Chunks[0].Key != h1.Chunks[0].Key || h3.Chunks[0].SHA256 == h2.Chunks[0].SHA256 || h2.Chunks[0].SHA256 == h1.Chunks[0].SHA256 { - t.Fatal("fixture: one key, three different reference hashes") - } - res := fx.verify("v1", VerifyOptions{Depth: VerifyData, AllSnapshots: true, BytesPerSecond: -1}) - wantClasses(t, "two wrong references", res, "CONTENT_MISMATCH@0") - f := res.Findings[0] - if f.Root != headLabel(h3.Gen) || !strings.Contains(f.Detail, "1 more") || !strings.Contains(f.Detail, "snapshot s1/") { - t.Fatalf("finding %+v; want under %q, detail counting 1 more differing reference under the snapshot", f, headLabel(h3.Gen)) - } - if n := fx.cb.reads(fx.fid(h1.Chunks[0].Key)); n != 1 { - t.Fatalf("chunk read %d times, want once", n) - } -} - -// A schedule point: where a world event lands relative to the pass. -type schedPoint string - -const ( - atWalked schedPoint = "walked" // after the first HEAD view, before any check - atChecked schedPoint = "checked" // after the first batch of checks has settled - atClosing schedPoint = "closing" // just before the first closing read - atDuring schedPoint = "during" // while chunk K's read is in progress -) - -// verifyFixture.schedule runs a data-depth pass over v1 whose owner applies -// steps[i] at points[i] (several steps at one point run in order). HEAD is -// re-read at every opportunity; fidK is the chunk whose read is "during". -func (fx *verifyFixture) schedule(fidK string, steps []func(), points []schedPoint) VerifyResult { - fx.t.Helper() - var mu sync.Mutex - pending := map[schedPoint][]func(){} - for i, p := range points { - pending[p] = append(pending[p], steps[i]) - } - fire := func(p schedPoint) { - mu.Lock() - fs := pending[p] - delete(pending, p) - mu.Unlock() - for _, f := range fs { - f() - } - } - opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1, RefreshInterval: time.Minute, Concurrency: 1} - opts.hook = func(stage string) { - switch stage { - case verifyHookHeadWalked: - fire(atWalked) - case verifyHookBatchChecked: - fire(atChecked) - case verifyHookClosingRead: - fire(atClosing) - } - } - during := &beforeRead{Blobs: fx.cb, fid: fidK, fn: func() { fire(atDuring) }} - cat, err := NewCatalog(manifestFilerBlobs{fx.f, during}, catBase) - if err != nil { - fx.t.Fatal(err) - } - cat.SetClock(tickingClock(time.Minute)) - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - res, err := cat.Verify(ctx, "v1", opts) - if err != nil || !res.Complete { - fx.t.Fatalf("verify: %v, %+v", err, res) - } - if len(pending) != 0 { - fx.t.Fatalf("schedule points never reached: %v", pending) - } - return res -} - -// The same owner events in different interleavings with the pass's checks -// and HEAD reads give the same findings: the findings are computed at the -// end, from each chunk's one outcome and the roots at the final read. K is -// chunk 0 (index 0), L chunk 1; "bad" means K's needle is missing. -func TestVerify_SchedulesGiveTheSameFindings(t *testing.T) { - moveK := func(c map[uint64]storage.ChunkRef) { c[1] = c[0]; delete(c, 0) } - addK1 := func(c map[uint64]storage.ChunkRef) { c[1] = c[0] } - dropK := func(c map[uint64]storage.ChunkRef) { delete(c, 0) } - type edit = func(c map[uint64]storage.ChunkRef) - for _, tc := range []struct { - name string - bad bool - edits []edit // the owner's publishes, in order (nil: restore K at index 0) - interleave [][]schedPoint - want []string - superseded int - finalGenStep int // findings are under the HEAD this many publishes after the first (all of them) - }{ - {"K moves from index 0 to 1, its check fails", true, []edit{moveK}, - [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, []string{"NEEDLE_MISSING@1"}, 0, 1}, - {"a reference to K arrives after K settled bad", true, []edit{addK1, dropK}, - [][]schedPoint{{atWalked, atWalked}, {atWalked, atChecked}, {atChecked, atClosing}}, []string{"NEEDLE_MISSING@1"}, 0, 2}, - {"K is bad, a refresh keeps index 0 and adds index 1", true, []edit{addK1}, - [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, []string{"NEEDLE_MISSING@0"}, 0, 1}, - {"settlement and refresh overlap", true, []edit{moveK}, - [][]schedPoint{{atDuring}, {atWalked}}, []string{"NEEDLE_MISSING@1"}, 0, 1}, - {"K is named, not named, named again (bad)", true, []edit{dropK, nil}, - [][]schedPoint{{atWalked, atChecked}, {atChecked, atClosing}}, []string{"NEEDLE_MISSING@0", "ROOT_INVALID@0"}, 0, 2}, - {"K is named, not named, named again (good)", false, []edit{dropK, nil}, - [][]schedPoint{{atWalked, atChecked}, {atChecked, atClosing}}, []string{"ROOT_INVALID@0"}, 0, 2}, - {"K is bad and the final view does not name it", true, []edit{dropK}, - [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, nil, 1, 1}, - } { - for _, points := range tc.interleave { - t.Run(fmt.Sprintf("%s/%v", tc.name, points), func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - k := h1.Chunks[0] - fidK := fx.fid(k.Key) - if tc.bad { - fx.needle(fidK, dropNeedle) - } - var last storage.ChunkHead - steps := make([]func(), len(tc.edits)) - for i, e := range tc.edits { - if e == nil { - e = func(c map[uint64]storage.ChunkRef) { c[0] = k } - } - steps[i] = func() { last = fx.republish("v1", e) } - } - res := fx.schedule(fidK, steps, points) - wantClasses(t, tc.name, res, tc.want...) - for _, f := range res.Findings { - if f.Root != headLabel(last.Gen) || f.Key == "" { - t.Fatalf("finding %+v; want under %q (the final HEAD view)", f, headLabel(last.Gen)) - } - } - if res.SupersededDuringVerify != tc.superseded || res.RootDeletedDuringVerify != 0 { - t.Fatalf("superseded %d, root deleted %d; want %d, 0", res.SupersededDuringVerify, res.RootDeletedDuringVerify, tc.superseded) - } - if res.HeadGens[len(res.HeadGens)-1] != last.Gen { - t.Fatalf("covered gens %v; want the last one %d", res.HeadGens, last.Gen) - } - // One check per chunk, however often HEAD names it again. - if n := fx.cb.reads(fidK); n != 1 { - t.Fatalf("chunk K read %d times, want once", n) - } - }) - } - } -} - -// A publish that lands while the pass makes its closing read is not missed: -// the read names a chunk not seen before, so the pass checks it and reads -// again; a bad new chunk is a finding, not a clean pass. -func TestVerify_PublishDuringClosingReadIsChecked(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - var h2 storage.ChunkHead - steps := []func(){func() { - h2 = fx.publish("v1", map[uint64][]byte{2: verifyData(3)}, true) - fx.needle(fx.fid(h2.Chunks[2].Key), dropNeedle) - }} - res := fx.schedule(fx.fid(h1.Chunks[0].Key), steps, []schedPoint{atClosing}) - wantClasses(t, "publish during the closing read", res, "NEEDLE_MISSING@2") - if res.Findings[0].Root != headLabel(h2.Gen) || fx.cb.reads(fx.fid(h2.Chunks[2].Key)) != 1 { - t.Fatalf("finding %+v, new chunk read %d times; want under %q, read once", res.Findings[0], fx.cb.reads(fx.fid(h2.Chunks[2].Key)), headLabel(h2.Gen)) - } - if len(res.HeadGens) != 2 || res.HeadGens[1] != h2.Gen { - t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) - } -} - -// An owner that publishes a new chunk before every closing read keeps the -// pass from closing: after ClosingRounds such reads the result is -// incomplete (never clean), with its reason and the findings computed from -// what was checked. -func TestVerify_ClosingRoundsExhaustedIsIncomplete(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) - reads := 0 - opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} - opts.hook = func(stage string) { - if stage == verifyHookClosingRead { - reads++ - fx.publish("v1", map[uint64][]byte{uint64(2 + reads): verifyData(byte(10 + reads))}, true) - } - } - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - res, err := fx.c.Verify(ctx, "v1", opts) - if CodeOf(err) != CodeVerifyIncomplete || res.Complete || res.Incomplete != VerifyIncompleteRounds { - t.Fatalf("verify: %v, complete %v, incomplete %q; want %s, incomplete for the closing rounds", err, res.Complete, res.Incomplete, CodeVerifyIncomplete) - } - if reads != DefaultVerifyClosingRounds { - t.Fatalf("%d closing reads, want %d", reads, DefaultVerifyClosingRounds) - } - wantClasses(t, "partial findings", res, "NEEDLE_MISSING@0") -} - -// retagSnapshot rewrites one field of the document of the attempt snapshot -// name resolves to, leaving it otherwise valid. -func (fx *verifyFixture) retagSnapshot(vol, name, field, value string) string { - fx.t.Helper() - ctx := context.Background() - ref, ok, err := fx.c.resolveSnap(ctx, vol, name) - if err != nil || !ok || ref.entry == nil { - fx.t.Fatalf("snapshot %s/%s: %v %v", vol, name, ok, err) - } - dir := path.Join(catBase, vol, snapsDir, name) - e, err := fx.f.LookupEntry(ctx, dir, ref.rec.Attempt) - if err != nil { - fx.t.Fatal(err) - } - var doc map[string]json.RawMessage - if err := json.Unmarshal(e.Content, &doc); err != nil { - fx.t.Fatal(err) - } - if doc[field], err = json.Marshal(value); err != nil { - fx.t.Fatal(err) - } - if e.Content, err = json.Marshal(doc); err != nil { - fx.t.Fatal(err) - } - if err := fx.f.UpdateEntry(ctx, dir, e, nil); err != nil { - fx.t.Fatal(err) - } - return ref.rec.Attempt -} - -// A snapshot is checked under the name and volume it was found at. A -// document that names another snapshot or volume is ROOT_INVALID, and a -// miss under that still published attempt is reported under the name it -// was found at, never excused as a snapshot deleted during the pass. -func TestVerify_SnapshotDocumentNamingAnotherSnapshot(t *testing.T) { - for _, tc := range []struct { - name, field, value string - opts VerifyOptions - }{ - {"named, another name", "name", "s2", VerifyOptions{Snapshot: "s1"}}, - {"all, another name", "name", "s2", VerifyOptions{AllSnapshots: true}}, - {"named, another volume", "volume_id", "v9", VerifyOptions{Snapshot: "s1"}}, - {"all, another volume", "volume_id", "v9", VerifyOptions{AllSnapshots: true}}, - } { - t.Run(tc.name, func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { - t.Fatal(err) - } - // HEAD moves on: only the snapshot names the old chunk 0, whose binding goes. - fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) - attempt := fx.retagSnapshot("v1", "s1", tc.field, tc.value) - fx.deleteBinding(h.Chunks[0].Key) - res := fx.verify("v1", tc.opts) - wantClasses(t, tc.name, res, "ROOT_INVALID", "BINDING_MISSING@0") - label := "snapshot s1/" + attempt - if res.Findings[0].Root != label || res.Findings[1].Root != label || !strings.Contains(res.Findings[0].Detail, tc.value) { - t.Fatalf("findings %+v; want both under %q", res.Findings, label) - } - if len(res.Snapshots) != 1 || res.Snapshots[0] != "s1/"+attempt || res.RootDeletedDuringVerify != 0 || len(res.SnapshotsDeletedDuringVerify) != 0 { - t.Fatalf("snapshots %v, root deleted %d, deleted %v; want [s1/%s], 0, none", - res.Snapshots, res.RootDeletedDuringVerify, res.SnapshotsDeletedDuringVerify, attempt) - } - }) - } -} - -// The closing read decides the final view: a HEAD that is gone, or that -// does not decode, leaves no HEAD root and makes the pass incomplete; it -// never closes on an earlier view. A bad chunk only that HEAD named is then -// counted as superseded, not reported. -func TestVerify_ClosingReadWithoutUsableHeadIsIncomplete(t *testing.T) { - for _, tc := range []struct { - name string - bad bool // chunk 0's needle is missing - undecoded bool // the closing read finds a HEAD that does not decode (else none) - want []string - reason VerifyIncomplete - superseded int - }{ - {"HEAD gone, bad chunk", true, false, nil, VerifyIncompleteHeadAbsent, 1}, - {"HEAD gone, good chunks", false, false, nil, VerifyIncompleteHeadAbsent, 0}, - {"HEAD does not decode", true, true, []string{"ROOT_INVALID"}, VerifyIncompleteHeadInvalid, 1}, - } { - t.Run(tc.name, func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - if tc.bad { - fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) - } - done := false - opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} - opts.hook = func(stage string) { - if stage != verifyHookClosingRead || done { - return - } - done = true - if tc.undecoded { - fx.f.bumpExtended(path.Join(catBase, "v1", headName), extGen, "999") - } else if err := fx.f.DeleteEntry(ctx, path.Join(catBase, "v1"), headName, nil); err != nil { - t.Error(err) - } - } - res, err := fx.c.Verify(ctx, "v1", opts) - if CodeOf(err) != CodeVerifyIncomplete || res.Complete || res.Incomplete != tc.reason { - t.Fatalf("verify: %v, complete %v, incomplete %q; want incomplete %q", err, res.Complete, res.Incomplete, tc.reason) - } - wantClasses(t, tc.name, res, tc.want...) - for _, f := range res.Findings { - if f.Root == headLabel(h.Gen) { - t.Fatalf("finding %+v under the HEAD the closing read no longer returned", f) - } - } - if res.SupersededDuringVerify != tc.superseded { - t.Fatalf("superseded %d, want %d", res.SupersededDuringVerify, tc.superseded) - } - }) - } -} - -// casHead installs a HEAD whose segment references edit changes, without -// writing segments (the current HEAD is read without resolving them, so it -// may already carry a wrong reference). -func (fx *verifyFixture) casHead(vol string, edit func(segs map[uint64]storage.ChunkSegment)) storage.ChunkHead { - fx.t.Helper() - ctx := context.Background() - r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) - if err != nil { - fx.t.Fatal(err) - } - cur, ok, err := fx.c.ReadHead(ctx, vol) - if err != nil || !ok { - fx.t.Fatalf("HEAD of %s: %v %v", vol, ok, err) - } - next := cur - next.Chunks = nil - next.RemoteLSN = cur.RemoteLSN + 1 - next.Segments = map[uint64]storage.ChunkSegment{} - for g, s := range cur.Segments { - next.Segments[g] = s - } - edit(next.Segments) - next.ManifestChunkCount = 0 - for _, s := range next.Segments { - next.ManifestChunkCount += s.Count - } - if next.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil { - fx.t.Fatal(err) - } - return next -} - -// A segment is one object per (owner, key), read once: HEAD and an active -// snapshot naming one segment key with different reference hashes share its -// one outcome. A failed read is one READ_ERROR, under HEAD, counted once; a -// readable segment is used by the root whose reference matches its content, -// and the other root gets one mismatch finding. -func TestVerify_SegmentIsOneObjectPerKey(t *testing.T) { - for _, readFails := range []bool{true, false} { - t.Run(fmt.Sprintf("read fails=%v", readFails), func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { - t.Fatal(err) - } - // HEAD names the same segment key with another reference hash. - h2 := fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { - s := segs[0] - s.SHA256[0] ^= 0xff - segs[0] = s - }) - segFid := fx.fid(h.Segments[0].Key) - if readFails { - fx.cb.failReads(segFid, -1) - } - res := fx.verify("v1", VerifyOptions{Depth: VerifyBindings, AllSnapshots: true}) - wantReads := 1 - if readFails { - wantClasses(t, "segment read fails", res, "READ_ERROR@seg0") - wantReads = verifyReadAttempts // one read, with its retries - if res.ChunksNotRead != 1 { - t.Fatalf("chunksNotRead %d, want 1", res.ChunksNotRead) - } - } else { - wantClasses(t, "segment matches the snapshot only", res, "CONTENT_MISMATCH@seg0") - // The snapshot's reference matches: its chunks are walked and checked. - if res.ChunksChecked != 2 || res.DistinctChunks != 2 { - t.Fatalf("chunks checked %d, distinct %d; want the snapshot's 2", res.ChunksChecked, res.DistinctChunks) - } - } - if f := res.Findings[0]; f.Root != headLabel(h2.Gen) || f.Key != h.Segments[0].Key { - t.Fatalf("finding %+v; want under %q for the segment key", f, headLabel(h2.Gen)) - } - if n := fx.cb.reads(segFid); n != wantReads { - t.Fatalf("segment read %d times, want %d", n, wantReads) - } - }) - } -} - -// headLookups counts the HEAD reads a pass makes. -type headLookups struct { - Filer - root string - mu sync.Mutex - n int -} - -func (f *headLookups) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { - if dir == f.root && name == headName { - f.mu.Lock() - f.n++ - f.mu.Unlock() - } - return f.Filer.LookupEntry(ctx, dir, name) -} - -func (f *headLookups) count() int { - f.mu.Lock() - defer f.mu.Unlock() - return f.n -} - -// The quiet closing read is the final view: no HEAD read follows it, and a -// publication that lands right after it is not part of this pass. -func TestVerify_QuietClosingReadIsTheFinalView(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - filer := &headLookups{Filer: fx.f, root: path.Join(catBase, "v1")} - cat, err := NewCatalog(manifestFilerBlobs{filer, fx.cb}, catBase) - if err != nil { - t.Fatal(err) - } - beforeRound, atClose := -1, -1 - var h2 storage.ChunkHead - opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} - opts.hook = func(stage string) { - switch stage { - case verifyHookClosingRead: - if beforeRound < 0 { - beforeRound = filer.count() // before the closing round reads anything - } - case verifyHookClosed: - atClose = filer.count() - h2 = fx.publish("v1", map[uint64][]byte{2: verifyData(3)}, true) - fx.needle(fx.fid(h2.Chunks[2].Key), dropNeedle) - } - } - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - res, err := cat.Verify(ctx, "v1", opts) - if err != nil || !res.Complete { - t.Fatalf("verify: %v, %+v", err, res) - } - if beforeRound < 0 || atClose < 0 { - t.Fatal("the quiet closing read was never reached") - } - // The closing round reads HEAD exactly once, and nothing reads it after. - if n := filer.count(); n-beforeRound != 1 { - t.Fatalf("%d HEAD reads from the start of the closing round to the end of the pass, want 1", n-beforeRound) - } - wantClasses(t, "publication after the quiet read", res) - if res.HeadGens[len(res.HeadGens)-1] != h.Gen || h2.Gen <= h.Gen { - t.Fatalf("covered gens %v (published %d after the close); want the quiet read's %d last", res.HeadGens, h2.Gen, h.Gen) - } -} - -// HEAD and an active snapshot name one segment key; the snapshot's reference -// is valid, HEAD's is changed by edit. Whichever reference the pass meets -// first, the findings are the same: each reference is judged against the -// segment's one outcome at the end, nothing about a reference is kept. -func TestVerify_SegmentFindingsDoNotDependOnOrder(t *testing.T) { - for _, tc := range []struct { - name string - edit func(s *storage.ChunkSegment) - want string - }{ - {"HEAD's reference has the right hash and wrong fields", func(s *storage.ChunkSegment) { s.Count++ }, "SEGMENT_UNREADABLE@seg0"}, - {"HEAD's reference has a wrong hash", func(s *storage.ChunkSegment) { s.SHA256[0] ^= 0xff }, "CONTENT_MISMATCH@seg0"}, - } { - for _, headFirst := range []bool{true, false} { - t.Run(fmt.Sprintf("%s/HEAD's reference first=%v", tc.name, headFirst), func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - ctx := context.Background() - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { - t.Fatal(err) - } - var bad storage.ChunkHead - breakHead := func() { - bad = fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { - s := segs[0] - tc.edit(&s) - segs[0] = s - }) - } - opts := VerifyOptions{Depth: VerifyData, AllSnapshots: true, BytesPerSecond: -1} - if headFirst { - breakHead() // the pass starts on HEAD's changed reference - } else { - // The pass first meets the valid reference (HEAD and the - // snapshot share it); the changed one comes at the closing read. - opts.hook = func(stage string) { - if stage == verifyHookRootsWalked { - breakHead() - } - } - } - res := fx.verify("v1", opts) - wantClasses(t, tc.name, res, tc.want) - if f := res.Findings[0]; f.Root != headLabel(bad.Gen) || f.Key != h.Segments[0].Key { - t.Fatalf("finding %+v; want under %q", f, headLabel(bad.Gen)) - } - // The snapshot's valid reference is used: its chunks are checked. - if res.ChunksChecked != 2 || res.DistinctChunks != 2 || res.DistinctChunksRead != 2 { - t.Fatalf("chunks checked %d, distinct %d, read %d; want the snapshot's 2", res.ChunksChecked, res.DistinctChunks, res.DistinctChunksRead) - } - if n := fx.cb.reads(fx.fid(h.Segments[0].Key)); n != 1 { - t.Fatalf("segment read %d times, want once", n) - } - }) - } - } -} - -// A problem under a reference that the final view no longer carries is not -// a finding, but it is counted once (superseded): the segment HEAD named -// with a wrong hash and then dropped; the segment HEAD named with a wrong -// hash and then named again soundly; a chunk read whose content a dropped -// reference did not match. -func TestVerify_DroppedReferenceProblemIsCounted(t *testing.T) { - wrongSegHash := func(segs map[uint64]storage.ChunkSegment) { s := segs[0]; s.SHA256[0] ^= 0xff; segs[0] = s } - for _, tc := range []struct { - name string - setup func(fx *verifyFixture) (before, during func()) - }{ - {"segment with a wrong hash, then dropped", func(fx *verifyFixture) (func(), func()) { - fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2)}, false) - return func() { fx.casHead("v1", wrongSegHash) }, - func() { fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { delete(segs, 0) }) } - }}, - {"segment with a wrong hash, then named soundly", func(fx *verifyFixture) (func(), func()) { - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - return func() { fx.casHead("v1", wrongSegHash) }, - func() { fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { segs[0] = h.Segments[0] }) } - }}, - {"chunk read, a dropped reference did not match it", func(fx *verifyFixture) (func(), func()) { - h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - return func() { fx.republish("v1", wrongHash(0)) }, - func() { fx.republish("v1", func(c map[uint64]storage.ChunkRef) { c[0] = h.Chunks[0] }) } - }}, - } { - t.Run(tc.name, func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - before, during := tc.setup(fx) - before() - opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} - opts.hook = func(stage string) { - if stage == verifyHookHeadWalked { - during() - } - } - res := fx.verify("v1", opts) - wantClasses(t, tc.name, res) - if res.SupersededDuringVerify != 1 || res.RootDeletedDuringVerify != 0 { - t.Fatalf("superseded %d, root deleted %d; want 1, 0", res.SupersededDuringVerify, res.RootDeletedDuringVerify) - } - }) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete.go b/seaweed-block/core/frontend/chunkstore/volume_delete.go deleted file mode 100644 index bfa4b8d787..0000000000 --- a/seaweed-block/core/frontend/chunkstore/volume_delete.go +++ /dev/null @@ -1,502 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "path" - "strconv" - "strings" - - "google.golang.org/protobuf/proto" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Volume delete (no snapshot cascade). -// -// (a) Admission: the caller's Admission (the CLI's: the blockmaster's -// durable deletion reservation, MarkVolumeDeleting; refused while the -// volume has live or pending authority; while held, no new assignment, -// placement or binding is admitted and the id is not created again). -// Every give-back below aborts this delete's admission (restoring the -// volume's usability); the commit point commits it (permanent). -// (b) One HEAD write from the HEAD read (active or detached, NOT held: an -// active HEAD that names a holder belongs to an attached server) to -// state deleting, chunks kept: a new incarnation of the delete mark -// (its generation). ChunkRemote.CASHead refuses to move a deleting, -// purging or deleted HEAD, so no attach, claim or restore can revive -// it; EnsureVolume refuses it; CreateSnapshot and Fork check the -// volume after taking their name or claim and refuse. -// (c) Under that incarnation, the volume must have no snapshot at all: no -// snapshot name record (a published snapshot, one being deleted, or an -// attempt still in flight). Any is volume_has_snapshots: HEAD is -// reverted and the admission given back. The operator deletes the -// snapshots first (DeleteSnapshot); a delete never touches snapshot -// names, attempts or their roots. (A fork claim lives on a named -// snapshot, so it is covered too.) -// (c') The commit point: HEAD deleting -> purging for that same -// incarnation only (conditioned on its generation); if HEAD moved (a -// revert and re-mark by another delete), the check is made again on -// the incarnation found. A revert is bound the same way, so no delete -// can undo another's commit, nor commit an incarnation it did not -// check. Then the admission is committed. -// (e) HEAD becomes deleted (no chunks: nothing it held stays a GC root) and -// VOLUME is marked deleted. GC reclaims. -// -// A call that fails reports what it did (VolumeDeleteResult) with the -// error; a rerun resumes from the state it finds. - -const ( - CodeVolumeInUse = "volume_in_use" - CodeVolumeDeleted = "volume_deleted" - CodeVolumeHasSnapshots = "volume_has_snapshots" - - // VolumeDeleted is the state of a deleted volume's VOLUME entry. - VolumeDeleted = "deleted" - - extVolState = "swb.volume.state" - extVolDeletedNs = "swb.volume.deleted_ns" - - // Test seams (retainHook stages) in a DeleteVolume. - hookHeadMarked = "head-marked" // after (b) - hookBlocked = "blocked" // (c) found a snapshot, before the revert - hookClaimsChecked = "claims-checked" // after (c), before the commit point - hookCommitted = "committed" // after the commit point (HEAD purging) - hookHeadDeleted = "head-deleted" // HEAD deleted, VOLUME not yet marked -) - -// ErrNotAdmitted marks an Admission error that is a definite refusal -// (nothing was recorded). Any other Admission error leaves the outcome -// unknown. -var ErrNotAdmitted = errors.New("chunkstore: volume delete not admitted") - -// Admission is the delete's reservation outside the catalog (the CLI's is -// the blockmaster's). Admit before anything is written; Commit at the -// irreversible boundary; Abort when the delete gives back with no -// irreversible effect. -type Admission interface { - Admit(ctx context.Context, vol string) error - Commit(ctx context.Context, vol string) error - Abort(ctx context.Context, vol string) error -} - -// VolumeDeleteResult is what DeleteVolume did, also on failure. -type VolumeDeleteResult struct { - VolumeID string `json:"volumeID"` - Replayed bool `json:"replayed"` // it was already deleted - Admitted bool `json:"admitted"` // (a) passed - // AdmissionUncertain: the admission call failed with an unknown - // outcome (it may have been recorded); AdmissionAborted: this delete - // gave its admission back; Committed: the admission is permanent. - AdmissionUncertain bool `json:"admissionUncertain"` - AdmissionAborted bool `json:"admissionAborted"` - Committed bool `json:"committed"` - HeadMarked bool `json:"headMarked"` // HEAD is deleting or deleted - Reverted bool `json:"reverted"` // (c) gave the HEAD mark back - Completed bool `json:"completed"` // HEAD and VOLUME are deleted - // Uncertain is set when the failing call was a write whose outcome is - // unknown; a rerun settles it. - Uncertain bool `json:"uncertain"` -} - -// DeleteVolume deletes vol (see the header). admit may be nil (a catalog- -// only delete, e.g. in tests): (b) still refuses a held HEAD. -func (c *Catalog) DeleteVolume(ctx context.Context, vol string, admit Admission) (VolumeDeleteResult, error) { - res := VolumeDeleteResult{VolumeID: vol} - root, err := c.volRoot(vol) - if err != nil { - return res, err - } - v, ok, err := c.ReadVolume(ctx, vol) - if err != nil { - return res, err - } - if !ok { - return res, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol) - } - h, _, err := c.ReadHead(ctx, vol) - if err != nil { - return res, err - } - res.Replayed = v.State == VolumeDeleted && h.State == storage.ChunkHeadDeleted - // (a) Every call takes its own admission (a rerun too: it settles a - // commit an earlier run may have lost). - if admit != nil { - if err := admit.Admit(ctx, vol); err != nil { - if errors.Is(err, ErrNotAdmitted) { - return res, catErr(CodeVolumeInUse, false, err, "volume %s: delete not admitted", vol) - } - res.AdmissionUncertain, res.Uncertain = true, true - return res, catErr(CodeOutcomeUnknown, true, err, "volume %s: delete admission outcome unknown (it may be recorded); rerun the delete", vol) - } - } - res.Admitted = true - giveBack := func(cause error) (VolumeDeleteResult, error) { - if admit != nil { - if err := admit.Abort(ctx, vol); err != nil { - res.Uncertain = true - return res, catErr(CodeOutcomeUnknown, true, err, "volume %s: %v; giving the admission back failed, rerun the delete", vol, cause) - } - res.AdmissionAborted = true - } - return res, cause - } - // (b), (c), (c'), each bound to one deleting incarnation (the HEAD - // generation the mark produced or joined): a claim check is only valid - // for the generation it ran under, so if HEAD moved (another delete - // reverted and re-marked it) the check is run again on the new one. - for incarnation := 0; h.State != storage.ChunkHeadPurging && h.State != storage.ChunkHeadDeleted; incarnation++ { - if incarnation == 5 { - return res, remoteErr(nil, "volume %s: the delete mark kept changing", vol) - } - gen, u, err := c.markHeadDeleting(ctx, vol, root) - if err != nil { - if u { - res.Uncertain = true - return res, err - } - return giveBack(err) - } - res.HeadMarked = true - c.hook(hookHeadMarked, vol) - // (c) - live, err := c.snapshotsBlock(ctx, vol, root) - if err != nil { - return res, err - } - if live != nil { - c.hook(hookBlocked, vol) - out, u, rerr := c.revertHeadDeleting(ctx, vol, root, gen) - switch { - case rerr != nil: - res.Uncertain = u - return res, rerr - case out == incarnationMoved: - if h, _, err = c.ReadHead(ctx, vol); err != nil { - return res, err - } - continue // decide again on what HEAD is now - case out == incarnationCommitted: - // Another delete committed meanwhile: its irreversible steps - // stand; this call neither reverts nor gives back. - return res, catErr(CodeOutcomeUnknown, true, nil, "volume %s: another delete committed while this one found %v; rerun the delete", vol, live) - } - res.Reverted, res.HeadMarked = true, false - return giveBack(live) - } - c.hook(hookClaimsChecked, vol) - // (c') the commit point, on the incarnation the check ran under - out, u, err := c.commitHeadPurging(ctx, vol, root, gen) - if err != nil { - res.Uncertain = u - return res, err - } - if out == incarnationDone { - break - } - if out == incarnationGivenBack { - res.HeadMarked = false - return giveBack(catErr(CodeOutcomeUnknown, true, nil, "volume %s: a concurrent delete gave the mark back; rerun the delete", vol)) - } - if h, _, err = c.ReadHead(ctx, vol); err != nil { // moved: validate again - return res, err - } - } - res.HeadMarked = true - c.hook(hookCommitted, vol) - if admit != nil { - if err := admit.Commit(ctx, vol); err != nil { - res.Uncertain = true - return res, catErr(CodeOutcomeUnknown, true, err, "volume %s: committing the admission failed; rerun the delete", vol) - } - } - res.Committed = true - // (e) - if u, err := c.finishHeadDeleted(ctx, vol, root); err != nil { - res.Uncertain = u - return res, err - } - c.hook(hookHeadDeleted, vol) - if err := c.markVolumeDeleted(ctx, vol, root); err != nil { - res.Uncertain = true - return res, err - } - res.Completed = true - return res, nil -} - -// headHeld: an active HEAD that names a holder belongs to an attached -// volume server (a clean detach publishes state detached). -func headHeld(h storage.ChunkHead) bool { - return (h.State == "" || h.State == storage.ChunkHeadActive) && h.Holder != "" -} - -// headDeletingOrDeleted reports a HEAD a delete has passed its -// linearization point on. -func headDeletingOrDeleted(h storage.ChunkHead) bool { - return h.State == storage.ChunkHeadDeleting || h.State == storage.ChunkHeadPurging || h.State == storage.ChunkHeadDeleted -} - -// writeHead writes next over the HEAD read as cur (an exclusive create when -// there was none), conditioned on cur's generation and epoch. It is the -// catalog's own HEAD write for the delete transitions, which CASHead -// refuses to anyone else. -func (c *Catalog) writeHead(ctx context.Context, root string, cur, next storage.ChunkHead) error { - next.Gen = cur.Gen + 1 - var ids []string - if next.Segments == nil && len(next.Chunks) != 0 { - v, ok, err := c.ReadVolume(ctx, path.Base(root)) - if err != nil { - return err - } - if !ok { - return errors.New("chunkstore: legacy delete needs VOLUME geometry") - } - next, ids, err = c.prepareLegacyHead(ctx, root, cur, next, v.Geometry) - if err != nil { - c.dropManifestIntents(ctx, root, ids) - return err - } - } - e, err := headEntry(next) - if err != nil { - c.dropManifestIntents(ctx, root, ids) - return err - } - if cur.Gen == 0 { - err = c.f.CreateEntry(ctx, root, e, true) - } else { - err = c.f.UpdateEntry(ctx, root, e, map[string][]byte{ - extGen: []byte(strconv.FormatUint(cur.Gen, 10)), extEpoch: []byte(strconv.FormatUint(cur.Epoch, 10)), - }) - } - // Unknown publication retains protection; a later sweep can settle it. - if err == nil || lostCondition(err) { - c.dropManifestIntents(ctx, root, ids) - } - return err -} - -func lostCondition(err error) bool { - return errors.Is(err, ErrPrecondition) || errors.Is(err, ErrExists) || errors.Is(err, ErrNotFound) -} - -// markHeadDeleting is (b): every read decides afresh whether the HEAD is -// held, so an attach that landed before this read is refused, and one that -// lands after it makes the write's condition fail. gen is the generation of -// the deleting HEAD this call produced or joined (its incarnation). -func (c *Catalog) markHeadDeleting(ctx context.Context, vol, root string) (gen uint64, uncertain bool, err error) { - for try := 0; try < 5; try++ { - h, _, err := c.ReadHead(ctx, vol) - if err != nil { - return 0, false, err - } - if h.State == storage.ChunkHeadDeleting { - return h.Gen, false, nil // join this incarnation - } - if headDeletingOrDeleted(h) { - return h.Gen, false, nil - } - if headHeld(h) { - return 0, false, catErr(CodeVolumeInUse, false, nil, "volume %s is attached: HEAD is held by %q at epoch %d; detach it first", vol, h.Holder, h.Epoch) - } - next := h - next.State = storage.ChunkHeadDeleting - if next.Chunks == nil { - next.Chunks = map[uint64]storage.ChunkRef{} - } - err = c.writeHead(ctx, root, h, next) - if lostCondition(err) { - continue - } - if err != nil { - return 0, true, catErr(CodeOutcomeUnknown, true, err, "mark HEAD of %s deleting: outcome unknown; rerun the delete", vol) - } - return h.Gen + 1, false, nil - } - return 0, false, remoteErr(nil, "HEAD of %s kept changing", vol) -} - -// What a revert or commit found of the incarnation it was bound to. -type incarnationOutcome int - -const ( - incarnationDone incarnationOutcome = iota // reverted / committed by this call, or committed already - incarnationMoved // HEAD is another deleting incarnation now: validate again - incarnationCommitted // past the commit point (by another delete) - incarnationGivenBack // active or detached again (another delete reverted) -) - -// revertHeadDeleting gives (b) back for incarnation gen only: deleting -// returns to detached when the HEAD carries its holder's detach record, -// else to active. -func (c *Catalog) revertHeadDeleting(ctx context.Context, vol, root string, gen uint64) (incarnationOutcome, bool, error) { - h, _, err := c.ReadHead(ctx, vol) - if err != nil { - return 0, false, err - } - switch { - case h.State == storage.ChunkHeadPurging || h.State == storage.ChunkHeadDeleted: - return incarnationCommitted, false, nil - case h.State != storage.ChunkHeadDeleting: - return incarnationGivenBack, false, nil // already given back: nothing to do - case h.Gen != gen: - return incarnationMoved, false, nil - } - next := h - next.State = storage.ChunkHeadActive - if h.DetachedBy != nil { - next.State = storage.ChunkHeadDetached - d := *h.DetachedBy - d.Gen = h.Gen + 1 - next.DetachedBy = &d - } - err = c.writeHead(ctx, root, h, next) - if lostCondition(err) { - return incarnationMoved, false, nil // HEAD moved under the write: decide again - } - if err != nil { - return 0, true, catErr(CodeOutcomeUnknown, true, err, "revert the delete mark on HEAD of %s: outcome unknown; rerun the delete", vol) - } - return incarnationDone, false, nil -} - -// commitHeadPurging is the commit point for incarnation gen only: deleting -// -> purging, conditioned on that exact HEAD. -func (c *Catalog) commitHeadPurging(ctx context.Context, vol, root string, gen uint64) (incarnationOutcome, bool, error) { - h, _, err := c.ReadHead(ctx, vol) - if err != nil { - return 0, false, err - } - switch { - case h.State == storage.ChunkHeadPurging || h.State == storage.ChunkHeadDeleted: - return incarnationDone, false, nil // committed (by another delete of the same mark) - case h.State != storage.ChunkHeadDeleting: - return incarnationGivenBack, false, nil - case h.Gen != gen: - return incarnationMoved, false, nil // another incarnation: its claims were not checked here - } - next := h - next.State = storage.ChunkHeadPurging - err = c.writeHead(ctx, root, h, next) - if lostCondition(err) { - return incarnationMoved, false, nil - } - if err != nil { - return 0, true, catErr(CodeOutcomeUnknown, true, err, "commit the delete of %s: outcome unknown; rerun the delete", vol) - } - return incarnationDone, false, nil -} - -// finishHeadDeleted is (e) for HEAD: deleting becomes deleted, no chunks. -func (c *Catalog) finishHeadDeleted(ctx context.Context, vol, root string) (bool, error) { - for try := 0; try < 5; try++ { - h, _, err := c.ReadHead(ctx, vol) - if err != nil { - return false, err - } - if h.State == storage.ChunkHeadDeleted { - return false, nil - } - if h.State != storage.ChunkHeadPurging { - return false, remoteErr(nil, "HEAD of %s is not committed for deletion (%q)", vol, h.State) - } - next := storage.ChunkHead{Epoch: h.Epoch, RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadDeleted} - err = c.writeHead(ctx, root, h, next) - if lostCondition(err) { - continue - } - if err != nil { - return true, catErr(CodeOutcomeUnknown, true, err, "tombstone HEAD of %s: outcome unknown; rerun the delete", vol) - } - return false, nil - } - return false, remoteErr(nil, "HEAD of %s kept changing", vol) -} - -// snapshotsBlock returns volume_has_snapshots when vol has any snapshot -// name record (published, being deleted, or an attempt in flight), or nil. -func (c *Catalog) snapshotsBlock(ctx context.Context, vol, root string) (error, error) { - names, err := c.listNames(ctx, root) - if err != nil { - return nil, err - } - if len(names) > 0 { - return catErr(CodeVolumeHasSnapshots, false, nil, "volume %s has snapshots (%s); delete them first", vol, strings.Join(names, ", ")), nil - } - return nil, nil -} - -// listNames lists every snapshot name record of the volume at root. -func (c *Catalog) listNames(ctx context.Context, root string) ([]string, error) { - dir := path.Join(root, snapNamesDir) - var out []string - after := "" - for { - page, err := c.f.ListEntries(ctx, dir, "", after, listPage) - if err != nil { - return nil, remoteErr(err, "list the snapshot names under %s", root) - } - for _, e := range page { - if e.GetName() <= after { - return nil, errors.New("chunkstore: non-advancing snapshot name listing") - } - after = e.GetName() - if !e.GetIsDirectory() { - out = append(out, e.GetName()) - } - } - if len(page) < listPage { - return out, nil - } - } -} - -// markVolumeDeleted marks vol's VOLUME entry deleted, conditioned on it not -// being marked yet. -func (c *Catalog) markVolumeDeleted(ctx context.Context, vol, root string) error { - e, err := c.f.LookupEntry(ctx, root, volumeName) - if err != nil { - return remoteErr(err, "read VOLUME of %s", vol) - } - if string(e.Extended[extVolState]) == VolumeDeleted { - return nil - } - next := proto.Clone(e).(*filerpb.Entry) - if next.Extended == nil { - next.Extended = map[string][]byte{} - } - next.Extended[extVolState] = []byte(VolumeDeleted) - next.Extended[extVolDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) - err = c.f.UpdateEntry(ctx, root, next, map[string][]byte{extVolState: nil}) - if errors.Is(err, ErrPrecondition) { - return nil // marked by a concurrent delete - } - if err != nil { - return remoteErr(err, "mark VOLUME of %s deleted", vol) - } - return nil -} - -// refuseDeleted is volume_deleted for a deleted (or deleting) volume id. -func refuseDeleted(vol, what string) error { - return catErr(CodeVolumeDeleted, false, nil, "volume %s is deleted or being deleted; %s (a deleted id is never reused)", vol, what) -} - -// volumeGone reports whether vol is being deleted or deleted: its VOLUME -// is marked, or its HEAD is past the delete's linearization point. -func (c *Catalog) volumeGone(ctx context.Context, vol string) (bool, error) { - v, ok, err := c.ReadVolume(ctx, vol) - if err != nil { - return false, err - } - if ok && v.State == VolumeDeleted { - return true, nil - } - h, has, err := c.ReadHead(ctx, vol) - if err != nil { - return false, err - } - return has && headDeletingOrDeleted(h), nil -} diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_crash_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_crash_test.go deleted file mode 100644 index 239abeadcc..0000000000 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_crash_test.go +++ /dev/null @@ -1,172 +0,0 @@ -package chunkstore - -import ( - "context" - "fmt" - "path" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// nthUpdate matches the n-th UpdateEntry (1-based) of the entry at p. -func nthUpdate(p string, n int) func(op, q string) bool { - seen := 0 - return func(op, q string) bool { - if op != "update" || q != p { - return false - } - seen++ - return seen == n - } -} - -// requireVolumeDeleted checks the end state of a completed volume delete: -// HEAD deleted, the VOLUME entry marked deleted, the volume refused for -// ever, the reservation committed. -func requireVolumeDeleted(t *testing.T, c *Catalog, rsv *fakeReservation, vol string) { - t.Helper() - ctx := context.Background() - h, ok, err := c.ReadHead(ctx, vol) - if err != nil || !ok || h.State != storage.ChunkHeadDeleted { - t.Fatalf("HEAD after the delete: %+v ok %v %v; want deleted", h, ok, err) - } - if v, ok, err := c.ReadVolume(ctx, vol); err != nil || !ok || v.State != VolumeDeleted { - t.Fatalf("VOLUME after the delete: %+v ok %v %v; want deleted", v, ok, err) - } - if _, err := c.EnsureVolume(ctx, vol, catGeo); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("attach after the delete: %v; want volume_deleted", err) - } - rsv.mu.Lock() - defer rsv.mu.Unlock() - if rsv.state != reservationCommitted { - t.Fatalf("the reservation is %q after the delete; want committed", rsv.state) - } -} - -// TestCatalogVolumeDeleteCrashAtEachStepThenRerunCompletes: a volume delete -// whose process dies at each of its filer writes (the HEAD mark, the commit -// to purging, the HEAD deleted, the VOLUME deleted), before the write reaches -// the filer or after it applied with its reply lost. A rerun with the same -// request, through a restarted catalog, completes: HEAD deleted, the volume -// refused for ever, the reservation committed. Nothing stays deleting or -// purging. -func TestCatalogVolumeDeleteCrashAtEachStepThenRerunCompletes(t *testing.T) { - headPath := path.Join(catBase, "v1", headName) - volumePath := path.Join(catBase, "v1", volumeName) - // left is the HEAD state each crash leaves for the rerun: before the - // write applied, and after. - steps := []struct { - name string - p string - n int - left [2]string - }{ - {"the HEAD mark (deleting)", headPath, 1, [2]string{storage.ChunkHeadDetached, storage.ChunkHeadDeleting}}, - {"the commit (purging)", headPath, 2, [2]string{storage.ChunkHeadDeleting, storage.ChunkHeadPurging}}, - {"HEAD deleted", headPath, 3, [2]string{storage.ChunkHeadPurging, storage.ChunkHeadDeleted}}, - {"VOLUME deleted", volumePath, 1, [2]string{storage.ChunkHeadDeleted, storage.ChunkHeadDeleted}}, - } - for _, step := range steps { - for _, after := range []bool{false, true} { - name := fmt.Sprintf("%s, %s", step.name, map[bool]string{false: "before it applied", true: "applied, reply lost"}[after]) - t.Run(name, func(t *testing.T) { - f, b, _, _ := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - rsv := &fakeReservation{} - crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: after, match: nthUpdate(step.p, step.n)} - dying, err := NewCatalog(crashed, catBase) - if err != nil { - t.Fatal(err) - } - if res, err := dying.DeleteVolume(ctx, "v1", rsv.admission("d1")); err == nil { - t.Fatalf("the delete returned success although its process died: %+v", res) - } - crashed.mu.Lock() - died := crashed.dead - crashed.mu.Unlock() - if !died { - t.Fatalf("the delete never reached the step %q", name) - } - - c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) // the restarted process - if err != nil { - t.Fatal(err) - } - left := step.left[0] - if after { - left = step.left[1] - } - if got := headState(t, c, "v1"); got.State != left { - t.Fatalf("after the crash HEAD is %q; want %q", got.State, left) - } - if v, _, err := c.ReadVolume(ctx, "v1"); err != nil || (v.State == VolumeDeleted) != (step.p == volumePath && after) { - t.Fatalf("after the crash VOLUME is %q (%v); want deleted only after its own write applied", v.State, err) - } - res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) - if err != nil || !res.Completed { - t.Fatalf("the rerun after a crash at %s: %+v %v; want completed", name, res, err) - } - requireVolumeDeleted(t, c, rsv, "v1") - if res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")); err != nil || !res.Completed || !res.Replayed { - t.Fatalf("a further rerun: %+v %v; want completed and replayed", res, err) - } - }) - } - } -} - -// TestCatalogVolumeDeleteCrashAtTheRevertThenRerunCompletes: a volume delete -// finds a snapshot name and reverts its mark, and its process dies at the -// revert (before it applied, or applied with its reply lost). Through a -// restarted catalog a rerun is refused while the snapshot exists -// (volume_has_snapshots) and leaves HEAD as it was before the delete; once -// the snapshot is deleted a rerun completes. -func TestCatalogVolumeDeleteCrashAtTheRevertThenRerunCompletes(t *testing.T) { - headPath := path.Join(catBase, "v1", headName) - for _, after := range []bool{false, true} { - t.Run(map[bool]string{false: "before it applied", true: "applied, reply lost"}[after], func(t *testing.T) { - f, b, c0, h := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - if _, err := c0.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-s1"}, h); err != nil { - t.Fatal(err) - } - before := headState(t, c0, "v1") - rsv := &fakeReservation{} - crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: after, match: nthUpdate(headPath, 2)} - dying, err := NewCatalog(crashed, catBase) - if err != nil { - t.Fatal(err) - } - if res, err := dying.DeleteVolume(ctx, "v1", rsv.admission("d1")); err == nil { - t.Fatalf("the delete returned success although its process died: %+v", res) - } - crashed.mu.Lock() - died := crashed.dead - crashed.mu.Unlock() - if !died { - t.Fatal("the delete never reached its revert") - } - - c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) - if err != nil { - t.Fatal(err) - } - if _, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")); CodeOf(err) != CodeVolumeHasSnapshots { - t.Fatalf("a rerun while the snapshot exists: %v; want volume_has_snapshots", err) - } - if got := headState(t, c, "v1"); got.State != before.State { - t.Fatalf("HEAD after the refused rerun is %q; want %q as before the delete", got.State, before.State) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - if res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")); err != nil || !res.Completed { - t.Fatalf("the rerun once the snapshot is deleted: %+v %v; want completed", res, err) - } - requireVolumeDeleted(t, c, rsv, "v1") - }) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go deleted file mode 100644 index 90dc6dfab5..0000000000 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go +++ /dev/null @@ -1,163 +0,0 @@ -//go:build chunkstore_integration - -package chunkstore - -import ( - "bytes" - "context" - "fmt" - "path" - "sort" - "strings" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Volume delete against a real SeaweedFS (CHUNKSTORE_WEED), with a real GC -// (the acceptance case): fork w2 from S1, delete w2, -// then DeleteSnapshot S1 succeeds and GC reclaims exactly the chunks only -// w2 and S1 reach, while w1 (HEAD, S2) stays intact; deleting an attached -// volume is refused; a deleted id cannot be recreated. -func TestIntegration_DeleteVolumeThenGC(t *testing.T) { - c := startWeed(t) - ctx := context.Background() - const base = "/swblock/chunks" - geo := Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} - full := int(geo.ChunkBlocks) * int(geo.BlockSize) - cl := c.client(t, base) - cat, err := NewCatalog(cl, base) - if err != nil { - t.Fatal(err) - } - for _, vol := range []string{"w1"} { - if _, err := cat.EnsureVolume(ctx, vol, geo); err != nil { - t.Fatal(err) - } - } - w1 := c.remote(t, path.Join(base, "w1")) - put := func(r *ChunkRemote, key string, b byte) storage.ChunkRef { - t.Helper() - data := bytes.Repeat([]byte{b}, full) - if err := r.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - return ref(key, data) - } - publish := func(r *ChunkRemote, holder string, epoch uint64, chunks map[uint64]storage.ChunkRef) storage.ChunkHead { - t.Helper() - cur, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - next := storage.ChunkHead{Epoch: epoch, Holder: holder, RemoteLSN: cur.RemoteLSN + 1, Chunks: chunks, State: storage.ChunkHeadActive} - return publishIntegrationHead(t, r, cur, next, uint64(full)) - } - detach := func(r *ChunkRemote) { - t.Helper() - cur, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - next := cur - next.State, next.DetachedBy = storage.ChunkHeadDetached, &storage.ChunkDetachedBy{Holder: cur.Holder, Epoch: cur.Epoch, Gen: cur.Gen + 1} - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil { - t.Fatal(err) - } - } - - // w1: S1 = {A, B}; then chunk 0 is rewritten: HEAD = S2 = {C, B}. - a, bb := put(w1, "chunks/e1/c0/a", 1), put(w1, "chunks/e1/c1/b", 2) - h1 := publish(w1, "h1", 1, map[uint64]storage.ChunkRef{0: a, 1: bb}) - if _, err := cat.CreateSnapshot(ctx, "w1", SnapshotRequest{Name: "S1", RequestID: "r1"}, h1); err != nil { - t.Fatal(err) - } - cc := put(w1, "chunks/e1/c0/c", 3) - h2 := publish(w1, "h1", 1, map[uint64]storage.ChunkRef{0: cc, 1: bb}) - if _, err := cat.CreateSnapshot(ctx, "w1", SnapshotRequest{Name: "S2", RequestID: "r2"}, h2); err != nil { - t.Fatal(err) - } - - // w2 = fork of S1, then it writes chunk 2 (D) of its own. - if _, err := cat.Fork(ctx, ForkRequest{Source: "w1", Snapshot: "S1", Target: "w2", RequestID: "f2"}); err != nil { - t.Fatalf("fork w2: %v", err) - } - w2 := c.remote(t, path.Join(base, "w2")) - fh, err := w2.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - d := put(w2, "chunks/e1/c2/d", 4) - chunks := map[uint64]storage.ChunkRef{2: d} - for k, v := range fh.Chunks { - chunks[k] = v - } - h3 := publish(w2, "h2", 1, chunks) - - // An attached volume is refused (w1 is held by h1; w2 by h2). - for _, vol := range []string{"w1", "w2"} { - if _, err := cat.DeleteVolume(ctx, vol, nil); CodeOf(err) != CodeVolumeInUse { - t.Fatalf("delete of attached %s: %v; want volume_in_use", vol, err) - } - } - detach(w2) - res, err := cat.DeleteVolume(ctx, "w2", nil) - if err != nil || res.Replayed { - t.Fatalf("delete w2: %+v %v", res, err) - } - if _, err := cat.EnsureVolume(ctx, "w2", geo); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("recreate w2: %v; want volume_deleted", err) - } - if _, err := cat.Fork(ctx, ForkRequest{Source: "w1", Snapshot: "S2", Target: "w2", RequestID: "again"}); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("fork to deleted w2: %v; want volume_deleted", err) - } - if _, err := cat.DeleteSnapshot(ctx, "w1", "S1"); err != nil { - t.Fatalf("DeleteSnapshot S1 after w2 was deleted: %v", err) - } - - // GC: two marks past grace reclaim exactly A (only S1 and w2 reached - // it) and D (only w2); B and C (w1's HEAD and S2) stay. - grace := 3 * DefaultOpDeadline // >= deadline + skew + CAS apply bound - at := time.Now().Add(3 * grace) - g, err := NewCollector(cat, cl, GCConfig{Grace: grace, IntentTTL: time.Hour, Now: func() time.Time { return at }, - IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) - if err != nil { - t.Fatal(err) - } - if _, err := g.Run(ctx); err != nil { - t.Fatalf("GC mark 1: %v", err) - } - // Reclamation requires strictly more than grace plus the skew bound. - at = at.Add(grace + DefaultGCClockSkew + time.Second) - gr, err := g.Run(ctx) - if err != nil { - t.Fatalf("GC mark 2: %v", err) - } - var got []string - for _, o := range gr.WouldDelete { - got = append(got, o.Volume+":"+o.Key) - } - want := []string{"w1:chunks/e1/c0/a", "w2:chunks/e1/c2/d"} - for _, h := range []storage.ChunkHead{h1, h3} { - for _, segment := range h.Segments { - want = append(want, segment.Owner+":"+strings.TrimPrefix(segment.Key, "@"+segment.Owner+"/")) - } - } - sort.Strings(want) - sort.Strings(got) - if fmt.Sprint(got) != fmt.Sprint(want) || gr.Reclaimed != len(want) { - t.Fatalf("GC reclaimed %v (%d); want exactly w1's A, w2's D and their unreachable manifests; roots=%+v candidates=%d", got, gr.Reclaimed, gr.Roots, gr.Candidates) - } - for _, kept := range []string{bb.Key, cc.Key} { - if _, err := w1.Get(ctx, kept); err != nil { - t.Fatalf("w1 chunk %s after GC: %v; want intact", kept, err) - } - } - if _, err := w1.Get(ctx, a.Key); err == nil { - t.Fatalf("w1 chunk %s still readable after GC reclaimed it", a.Key) - } - if s, err := cat.readSnap(ctx, "w1", "S2"); err != nil || s.State != SnapActive { - t.Fatalf("S2 after GC: %+v %v", s, err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go deleted file mode 100644 index c554bb76f0..0000000000 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go +++ /dev/null @@ -1,550 +0,0 @@ -package chunkstore - -import ( - "context" - "errors" - "fmt" - "path" - "strings" - "sync" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Volume delete: one linearization point, no snapshot cascade. One -// control per review schedule. - -// detachHead publishes vol's HEAD as a clean detach by its holder (what a -// volume server's Detach writes). -func detachHead(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) { - t.Helper() - ctx := context.Background() - r, err := NewChunkRemote(f, b, path.Join(catBase, vol)) - if err != nil { - t.Fatal(err) - } - h, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - next := h - next.State = storage.ChunkHeadDetached - next.DetachedBy = &storage.ChunkDetachedBy{Holder: h.Holder, Epoch: h.Epoch, Gen: h.Gen + 1} - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { - t.Fatal(err) - } -} - -// attachEntry is the HEAD an attaching holder installs over cur. -func attachEntry(t *testing.T, cur storage.ChunkHead, holder string) *filerpb.Entry { - t.Helper() - att := cur - att.Gen, att.Epoch, att.Holder, att.State, att.DetachedBy = cur.Gen+1, cur.Epoch+1, holder, storage.ChunkHeadActive, nil - e, err := headEntry(att) - if err != nil { - t.Fatal(err) - } - return e -} - -// deleteFixture: v1 with an attached HEAD (held by h1) and no snapshots; -// directory entries for v1, w2, w3 (the fake lists only what it holds). -func deleteFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) { - t.Helper() - f, b, c, h := catalogFixture(t) - ctx := context.Background() - for _, vol := range []string{"v1", "w2", "w3"} { - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - } - return f, b, c, h -} - -func headState(t *testing.T, c *Catalog, vol string) storage.ChunkHead { - t.Helper() - h, _, err := c.ReadHead(context.Background(), vol) - if err != nil { - t.Fatal(err) - } - return h -} - -func mustHead(t *testing.T, c *Catalog, vol string) storage.ChunkHead { - t.Helper() - h, has, err := c.ReadHead(context.Background(), vol) - if err != nil || !has { - t.Fatalf("HEAD of %s: has=%t %v", vol, has, err) - } - return h -} - -// fakeReservation mirrors the blockmaster's deletion reservation (tokens, -// admitted/committed) for the catalog's Admission. -type fakeReservation struct { - mu sync.Mutex - state string - holders map[string]bool - refuse bool // Admit refuses (nothing recorded) - loseAdmit bool // Admit records, then its response is lost -} - -const ( - reservationAdmitted = "admitted" - reservationCommitted = "committed" -) - -type fakeAdmit struct { - r *fakeReservation - tok string -} - -func (r *fakeReservation) admission(tok string) Admission { return &fakeAdmit{r, tok} } - -func (a *fakeAdmit) Admit(context.Context, string) error { - a.r.mu.Lock() - defer a.r.mu.Unlock() - if a.r.refuse { - return fmt.Errorf("%w: assigned to r1", ErrNotAdmitted) - } - if a.r.holders == nil { - a.r.holders = map[string]bool{} - } - a.r.holders[a.tok] = true - if a.r.state == "" { - a.r.state = reservationAdmitted - } - if a.r.loseAdmit { - return errors.New("response lost") - } - return nil -} - -func (a *fakeAdmit) Commit(context.Context, string) error { - a.r.mu.Lock() - defer a.r.mu.Unlock() - if a.r.state != reservationCommitted && !a.r.holders[a.tok] { - return errors.New("token holds nothing") - } - a.r.state = reservationCommitted - return nil -} - -func (a *fakeAdmit) Abort(context.Context, string) error { - a.r.mu.Lock() - defer a.r.mu.Unlock() - if a.r.state == reservationCommitted { - return errors.New("committed") - } - delete(a.r.holders, a.tok) - if len(a.r.holders) == 0 { - a.r.state = "" - } - return nil -} - -// An attached volume (HEAD held), or one the admission refuses, is refused -// with volume_in_use and nothing is written; a held HEAD found after the -// admission gives the admission back. -func TestCatalog_DeleteVolumeRefusesAVolumeInUse(t *testing.T) { - f, b, c, _ := deleteFixture(t) - ctx := context.Background() - before := len(f.allWritten()) - rsv := &fakeReservation{} - res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) - if CodeOf(err) != CodeVolumeInUse || !res.AdmissionAborted || rsv.state != "" { - t.Fatalf("delete of an attached volume: %+v %v reservation=%q; want volume_in_use, admission given back", res, err, rsv.state) - } - if got := len(f.allWritten()); got != before { - t.Fatalf("a refused delete wrote %d entries", got-before) - } - detachHead(t, f, b, "v1") - before = len(f.allWritten()) - res, err = c.DeleteVolume(ctx, "v1", (&fakeReservation{refuse: true}).admission("d1")) - var ce *CatalogError - if !errors.As(err, &ce) || ce.Code != CodeVolumeInUse || ce.Retryable || !strings.Contains(ce.Detail(), "assigned to r1") || res.Admitted { - t.Fatalf("delete the admission refuses: %+v %v", res, err) - } - if got := len(f.allWritten()); got != before { - t.Fatalf("a refused delete wrote %d entries", got-before) - } -} - -// Schedule: a holder attaches after the delete's first read, before the -// mark's read; the mark reads the held HEAD and refuses. -func TestCatalog_DeleteVolumeRefusesAnAttachBeforeTheMark(t *testing.T) { - f, b, c, _ := deleteFixture(t) - detachHead(t, f, b, "v1") - headPath := path.Join(catBase, "v1", headName) - lookups := 0 - f.afterLookup = func(p string) { - if p != headPath { - return - } - if lookups++; lookups == 1 { - cur, _ := decodeHead(p, f.entries[p]) - f.entries[p] = attachEntry(t, cur, "h2") - } - } - if _, err := c.DeleteVolume(context.Background(), "v1", nil); CodeOf(err) != CodeVolumeInUse { - t.Fatalf("delete racing an attach: %v; want volume_in_use", err) - } - f.afterLookup = nil - if h := headState(t, c, "v1"); h.Holder != "h2" || h.State != storage.ChunkHeadActive { - t.Fatalf("HEAD after the refused delete: %+v; want h2's", h) - } -} - -// An attach between the mark's read and its write makes the write's -// condition fail; the re-read sees the holder and refuses. -func TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark(t *testing.T) { - f, b, c, _ := deleteFixture(t) - detachHead(t, f, b, "v1") - headPath := path.Join(catBase, "v1", headName) - lookups := 0 - f.afterLookup = func(p string) { - if p != headPath { - return - } - if lookups++; lookups == 2 { - cur, _ := decodeHead(p, f.entries[p]) - f.entries[p] = attachEntry(t, cur, "h2") - } - } - if _, err := c.DeleteVolume(context.Background(), "v1", nil); CodeOf(err) != CodeVolumeInUse { - t.Fatalf("delete losing to an attach: %v; want volume_in_use", err) - } - f.afterLookup = nil - if h := headState(t, c, "v1"); h.Holder != "h2" { - t.Fatalf("HEAD after the lost delete: %+v; want h2's", h) - } -} - -// An attach that passed EnsureVolume before the mark claims HEAD afterwards -// (CASHead from the deleting or deleted HEAD): the remote refuses. -func TestCatalog_DeletedHeadCannotBeRevivedByAClaim(t *testing.T) { - f, b, c, _ := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err != nil { - t.Fatal(err) - } - claim := func(stage string) { - t.Helper() - h, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch + 1, Holder: "late", RemoteLSN: h.RemoteLSN, Chunks: h.Chunks, State: storage.ChunkHeadActive}) - if !errors.Is(err, storage.ErrChunkHeadPrecondition) || !errors.Is(err, storage.ErrChunkHeadDeleted) { - t.Fatalf("claim of a %s HEAD: %v; want a precondition failure (deleted)", stage, err) - } - if _, err := c.EnsureVolume(ctx, "v1", catGeo); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("attach of a %s volume: %v; want volume_deleted", stage, err) - } - } - c.retainHook = func(stage, _ string) { - if stage == hookHeadMarked { - claim("deleting") - } - } - res, err := c.DeleteVolume(ctx, "v1", nil) - c.retainHook = nil - if err != nil || !res.Completed { - t.Fatalf("delete: %+v %v", res, err) - } - claim("deleted") -} - -// The cut: a volume with any snapshot is refused (volume_has_snapshots) -// with HEAD restored and the admission given back; deleting the snapshot -// first lets the delete complete; snapshots are never touched by it. -func TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist(t *testing.T) { - f, b, c, h := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-s1"}, h); err != nil { - t.Fatal(err) - } - before := headState(t, c, "v1") - rsv := &fakeReservation{} - res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) - if CodeOf(err) != CodeVolumeHasSnapshots || !res.Reverted || !res.AdmissionAborted || res.Committed || rsv.state != "" { - t.Fatalf("delete with a snapshot: %+v %v reservation=%q; want volume_has_snapshots, reverted, given back", res, err, rsv.state) - } - after := headState(t, c, "v1") - if after.State != storage.ChunkHeadDetached || after.Holder != before.Holder || len(after.Chunks) != len(before.Chunks) { - t.Fatalf("HEAD after the refusal: %+v; want the detached HEAD with its chunks", after) - } - if s, err := c.readSnap(ctx, "v1", "s1"); err != nil || s.State != SnapActive { - t.Fatalf("s1 after the refusal: %+v %v; want untouched", s, err) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - res, err = c.DeleteVolume(ctx, "v1", rsv.admission("d2")) - if err != nil || !res.Completed || !res.Committed || rsv.state != reservationCommitted { - t.Fatalf("delete after DeleteSnapshot: %+v %v", res, err) - } -} - -// A snapshot attempt in flight (name taken, publication -// held) when the delete marks HEAD: the delete refuses and reverts, and the -// snapshot then publishes cleanly. A snapshot started after the mark -// refuses itself. -func TestCatalog_InFlightSnapshotRefusesTheDelete(t *testing.T) { - f, b, c, h := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - held := catBase + "/v1/" + snapsDir + "/s3/" - f.deferCreate = func(p string, _ *filerpb.Entry) bool { return strings.HasPrefix(p, held) } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s3", RequestID: "r-s3"}, h); err == nil { - t.Fatal("held snapshot publication reported success") - } - f.deferCreate = nil - late := false - c.retainHook = func(stage, _ string) { - if stage == hookHeadMarked && !late { - late = true - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s4", RequestID: "r-s4"}, h); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("snapshot started after the mark: %v; want volume_deleted", err) - } - } - } - res, err := c.DeleteVolume(ctx, "v1", nil) - c.retainHook = nil - if CodeOf(err) != CodeVolumeHasSnapshots || !res.Reverted { - t.Fatalf("delete with an in-flight snapshot: %+v %v; want volume_has_snapshots, reverted", res, err) - } - if n := f.releaseDeferredCreates(); n != 1 { - t.Fatalf("released %d held publications, want 1", n) - } - s, err := c.readSnap(ctx, "v1", "s3") - if err != nil || s.State != SnapActive { - t.Fatalf("s3 after the refused delete: %+v %v; want published", s, err) - } - if hh := headState(t, c, "v1"); hh.State != storage.ChunkHeadDetached { - t.Fatalf("HEAD after the refused delete: %+v", hh) - } -} - -// A fork that reads during the delete mark sees the deleting source and -// refuses before installing anything; the delete refuses too (the forked -// snapshot exists) and reverts. -func TestCatalog_ForkDuringTheDeleteMarkRefuses(t *testing.T) { - f, b, c, h := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-s1"}, h); err != nil { - t.Fatal(err) - } - c.retainHook = func(stage, _ string) { - if stage == hookHeadMarked { - c.retainHook = nil - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "w2", RequestID: "late"}); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("fork during the delete mark: %v; want volume_deleted", err) - } - } - } - if _, err := c.DeleteVolume(ctx, "v1", nil); CodeOf(err) != CodeVolumeHasSnapshots { - t.Fatalf("delete: %v; want volume_has_snapshots", err) - } - if _, ok, _ := c.ReadVolume(ctx, "w2"); ok { - t.Fatal("the refused fork published its VOLUME") - } -} - -// P2 (incarnation): D1 checks under deleting generation G and pauses -// before its commit. A blocker appears, D2 sees it and reverts G, and a -// new delete mark (D3's) installs generation G'. D1 must not commit G' -// (whose snapshots it never checked): it checks again, finds the blocker -// and gives back. -func TestCatalog_DeleteCommitIsBoundToItsIncarnation(t *testing.T) { - f, b, c, h := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - root := path.Join(catBase, "v1") - rsv := &fakeReservation{} - var d2err error - c.retainHook = func(stage, _ string) { - if stage != hookClaimsChecked { - return - } - c.retainHook = nil - // A snapshot name appears (a creator that took its name, then saw - // the mark and refused: its name record stays). - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "late", RequestID: "r-late"}, h); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("snapshot during the mark: %v", err) - } - _, d2err = c.DeleteVolume(ctx, "v1", rsv.admission("d2")) // sees it, reverts G - if _, _, err := c.markHeadDeleting(ctx, "v1", root); err != nil { // D3 re-marks: G' - t.Fatal(err) - } - } - res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) - if CodeOf(d2err) != CodeVolumeHasSnapshots { - t.Fatalf("D2: %v; want volume_has_snapshots", d2err) - } - if CodeOf(err) != CodeVolumeHasSnapshots || res.Committed { - t.Fatalf("D1 after the re-mark: %+v %v; want volume_has_snapshots, not committed", res, err) - } - if hh := headState(t, c, "v1"); hh.State == storage.ChunkHeadPurging || hh.State == storage.ChunkHeadDeleted { - t.Fatalf("HEAD %q: D1 committed an incarnation it did not check", hh.State) - } - if rsv.state == reservationCommitted { - t.Fatal("the reservation was committed") - } -} - -// Concurrent deletes: D1 finds a snapshot and pauses before its revert; -// the snapshot is deleted and D2 joins, commits and completes. D1's revert -// then finds the HEAD committed: it neither reverts nor gives back. -func TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne(t *testing.T) { - f, b, c, h := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-s1"}, h); err != nil { - t.Fatal(err) - } - rsv := &fakeReservation{} - var d2 VolumeDeleteResult - var d2err error - c.retainHook = func(stage, _ string) { - if stage != hookBlocked { - return - } - c.retainHook = nil - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatal(err) - } - d2, d2err = c.DeleteVolume(ctx, "v1", rsv.admission("d2")) - } - d1, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) - if d2err != nil || !d2.Completed { - t.Fatalf("D2: %+v %v; want completed", d2, d2err) - } - if err == nil || d1.Reverted || d1.AdmissionAborted { - t.Fatalf("D1 after D2 committed: %+v %v; want an error, no revert, no give-back", d1, err) - } - if hh := headState(t, c, "v1"); hh.State != storage.ChunkHeadDeleted || rsv.state != reservationCommitted { - t.Fatalf("after both: HEAD %q reservation %q; want deleted, committed", hh.State, rsv.state) - } -} - -// A lost admission response is an unknown outcome (it may be recorded), -// never a refusal, and nothing is written. -func TestCatalog_DeleteVolumeLostAdmissionResponse(t *testing.T) { - f, b, c, _ := deleteFixture(t) - detachHead(t, f, b, "v1") - before := len(f.allWritten()) - rsv := &fakeReservation{loseAdmit: true} - res, err := c.DeleteVolume(context.Background(), "v1", rsv.admission("d1")) - var ce *CatalogError - if !errors.As(err, &ce) || ce.Code != CodeOutcomeUnknown || !ce.Retryable || !res.AdmissionUncertain || !res.Uncertain || res.Admitted { - t.Fatalf("lost admission response: %+v %v", res, err) - } - if got := len(f.allWritten()); got != before || rsv.state != reservationAdmitted { - t.Fatalf("wrote %d entries; reservation %q (the lost admission did land)", got-before, rsv.state) - } -} - -// The acceptance flow on the fake: fork w2 from s1; w2's own snapshot must -// be deleted first; then w2 is deleted, s1 can be deleted, and the id is -// never attached, recreated or forked to again; an incomplete fork w3 is -// deleted too (its claim is then dead); a rerun replays. -func TestCatalog_DeleteVolumeTombstonesAndRefusesReuse(t *testing.T) { - f, _, c, h := deleteFixture(t) - ctx := context.Background() - for _, name := range []string{"s1", "s2"} { - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: "r-" + name}, h); err != nil { - t.Fatal(err) - } - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "w2", RequestID: "f2"}); err != nil { - t.Fatalf("fork w2: %v", err) - } - if _, err := c.CreateSnapshot(ctx, "w2", SnapshotRequest{Name: "w2snap", RequestID: "rw"}, mustHead(t, c, "w2")); err != nil { - t.Fatal(err) - } - if _, err := c.DeleteVolume(ctx, "w2", nil); CodeOf(err) != CodeVolumeHasSnapshots { - t.Fatalf("delete w2 with a snapshot: %v; want volume_has_snapshots", err) - } - if _, err := c.DeleteSnapshot(ctx, "w2", "w2snap"); err != nil { - t.Fatal(err) - } - res, err := c.DeleteVolume(ctx, "w2", nil) - if err != nil || res.Replayed || !res.Completed { - t.Fatalf("delete w2: %+v %v", res, err) - } - if hh := headState(t, c, "w2"); hh.State != storage.ChunkHeadDeleted || len(hh.Chunks) != 0 { - t.Fatalf("w2 HEAD: %+v; want a deleted tombstone with no chunks", hh) - } - if v, _, _ := c.ReadVolume(ctx, "w2"); v.State != VolumeDeleted { - t.Fatalf("w2 VOLUME state %q", v.State) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatalf("delete s1 after its fork was deleted: %v", err) - } - if _, err := c.EnsureVolume(ctx, "w2", catGeo); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("attach/create of deleted w2: %v; want volume_deleted", err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w2", RequestID: "again"}); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("fork to deleted w2: %v; want volume_deleted", err) - } - if res, err := c.DeleteVolume(ctx, "w2", nil); err != nil || !res.Replayed { - t.Fatalf("rerun: %+v %v; want a replay", res, err) - } - holdFirst(f, catBase+"/w3/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w3", RequestID: "f3"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork w3: %v", err) - } - if got, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil || got != SnapDeleting { - t.Fatalf("delete s2 under the incomplete fork: %q %v; forks do not hold their parent", got, err) - } - if res, err := c.DeleteVolume(ctx, "w3", nil); err != nil || !res.Completed { - t.Fatalf("delete w3: %+v %v", res, err) - } - if got, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil || got != SnapAbsent { - t.Fatalf("delete s2 again: %q %v; want absent", got, err) - } -} - -// r4 P2: the original fork request's early replay never reports success -// for a target past the delete mark, in every window (deleting, purging, -// HEAD deleted before VOLUME is marked) and after; a completed fork still -// replays before its delete. -func TestCatalog_ForkReplayRefusesADeletingTarget(t *testing.T) { - _, _, c, h := deleteFixture(t) - ctx := context.Background() - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-s1"}, h); err != nil { - t.Fatal(err) - } - req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "w2", RequestID: "f2"} - if _, err := c.Fork(ctx, req); err != nil { - t.Fatalf("fork w2: %v", err) - } - if res, err := c.Fork(ctx, req); err != nil || !res.Replayed { - t.Fatalf("replay before the delete: %+v %v; want a successful replay", res, err) - } - seen := map[string]bool{} - c.retainHook = func(stage, _ string) { - switch stage { - case hookHeadMarked, hookCommitted, hookHeadDeleted: - seen[stage] = true - if _, err := c.Fork(ctx, req); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("replay at %s: %v; want volume_deleted", stage, err) - } - } - } - res, err := c.DeleteVolume(ctx, "w2", nil) - c.retainHook = nil - if err != nil || !res.Completed || len(seen) != 3 { - t.Fatalf("delete w2: %+v %v; windows seen %v", res, err, seen) - } - if _, err := c.Fork(ctx, req); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("replay after the delete: %v; want volume_deleted", err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go b/seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go deleted file mode 100644 index debc3434e1..0000000000 --- a/seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package chunkstore - -import ( - "context" - "strings" - "testing" -) - -func TestEnsureVolumeRejectsBeyondUint32LBACap(t *testing.T) { - f, b, _, _, _ := gcFixture(t) - c, err := NewCatalog(manifestFilerBlobs{f, b}, catBase) - if err != nil { - t.Fatal(err) - } - ctx := context.Background() - if _, err = c.EnsureVolume(ctx, "at-cap", Geometry{NumBlocks: 4294967295, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { - t.Fatal(err) - } - for _, blocks := range []uint64{4294967296, ^uint64(0)} { - _, err = c.EnsureVolume(ctx, "too-large", Geometry{NumBlocks: blocks, BlockSize: 4096, ChunkBlocks: 1024}) - if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { - t.Fatalf("blocks %d: want capacity refusal, got %v", blocks, err) - } - if _, ok, e := c.ReadVolume(ctx, "too-large"); e != nil || ok { - t.Fatalf("refusal changed catalog: exists=%v err=%v", ok, e) - } - } -} diff --git a/seaweed-block/core/host/master/workspace_cluster_integration_test.go b/seaweed-block/core/frontend/chunkstore/weed_cluster_integration_test.go similarity index 70% rename from seaweed-block/core/host/master/workspace_cluster_integration_test.go rename to seaweed-block/core/frontend/chunkstore/weed_cluster_integration_test.go index 0edb175879..559f82e450 100644 --- a/seaweed-block/core/host/master/workspace_cluster_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/weed_cluster_integration_test.go @@ -1,13 +1,14 @@ //go:build chunkstore_integration -package master +// Real SeaweedFS processes (weed master, volume, filer) started as the +// current user, for the integration tests of this package. Run with: +// +// CHUNKSTORE_WEED=/path/to/weed go test -tags chunkstore_integration -run Integration -v ./core/frontend/chunkstore/ +package chunkstore -// The process helper follows the existing chunkstore integration harness. -// Only real loopback SeaweedFS processes and per-test temporary state are used. import ( "context" "fmt" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "math/rand" "net" "os" @@ -17,13 +18,13 @@ import ( "time" ) -type w4WeedCluster struct { +type weedCluster struct { master, filerHTTP, filerGRPC string dir string weed string } -func w4FreePortPair(t *testing.T, used map[int]bool) int { +func freePortPair(t *testing.T, used map[int]bool) int { t.Helper() for i := 0; i < 200; i++ { p := 20000 + rand.Intn(20000) @@ -48,7 +49,7 @@ func w4FreePortPair(t *testing.T, used map[int]bool) int { return 0 } -func w4WaitTCP(t *testing.T, addr string, d time.Duration) { +func waitTCP(t *testing.T, addr string, d time.Duration) { t.Helper() deadline := time.Now().Add(d) for time.Now().Before(deadline) { @@ -61,7 +62,14 @@ func w4WaitTCP(t *testing.T, addr string, d time.Duration) { t.Fatalf("%s not listening after %v", addr, d) } -func startWorkspaceWeed(t *testing.T) *w4WeedCluster { +func startWeed(t *testing.T) *weedCluster { + t.Helper() + return startWeedWith(t, "") +} + +// startWeedWith starts the cluster with security (the contents of a +// security.toml in its working directory; "" for none). +func startWeedWith(t *testing.T, security string) *weedCluster { t.Helper() weed := os.Getenv("CHUNKSTORE_WEED") if weed == "" { @@ -69,8 +77,8 @@ func startWorkspaceWeed(t *testing.T) *w4WeedCluster { } dir := t.TempDir() used := map[int]bool{} - mp, vp, fp := w4FreePortPair(t, used), w4FreePortPair(t, used), w4FreePortPair(t, used) - c := &w4WeedCluster{ + mp, vp, fp := freePortPair(t, used), freePortPair(t, used), freePortPair(t, used) + c := &weedCluster{ master: fmt.Sprintf("127.0.0.1:%d", mp), filerHTTP: fmt.Sprintf("127.0.0.1:%d", fp), filerGRPC: fmt.Sprintf("127.0.0.1:%d", fp+10000), @@ -90,13 +98,7 @@ func startWorkspaceWeed(t *testing.T) *w4WeedCluster { } t.Cleanup(func() { _ = cmd.Process.Kill() - done := make(chan error, 1) - go func() { done <- cmd.Wait() }() - select { - case <-done: - case <-time.After(5 * time.Second): - t.Errorf("weed %s did not exit after kill", name) - } + _, _ = cmd.Process.Wait() logf.Close() if t.Failed() { b, _ := os.ReadFile(logf.Name()) @@ -112,11 +114,16 @@ func startWorkspaceWeed(t *testing.T) *w4WeedCluster { t.Fatal(err) } } + if security != "" { + if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(security), 0o600); err != nil { + t.Fatal(err) + } + } run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000") - w4WaitTCP(t, c.master, 20*time.Second) + waitTCP(t, c.master, 20*time.Second) run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, "-max=32") run("filer", "filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f")) - w4WaitTCP(t, c.filerGRPC, 30*time.Second) + waitTCP(t, c.filerGRPC, 30*time.Second) // Wait until an assign succeeds (volume registered, volumes growable). cl := c.client(t, "/swblock/vols/probe") @@ -136,21 +143,12 @@ func startWorkspaceWeed(t *testing.T) *w4WeedCluster { return c } -func (c *w4WeedCluster) client(t *testing.T, assignPath string) *chunkstore.SWFS { +func (c *weedCluster) client(t *testing.T, assignPath string) *SWFS { t.Helper() - cl, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: c.filerGRPC, Collection: "swblock", AssignPath: assignPath}) + cl, err := DialSWFS(SWFSConfig{FilerGRPC: c.filerGRPC, Collection: "swblock", AssignPath: assignPath}) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = cl.Close() }) return cl } - -func (c *w4WeedCluster) remote(t *testing.T, root string) *chunkstore.ChunkRemote { - t.Helper() - r, err := chunkstore.NewSWFSChunkRemote(c.client(t, root), root) - if err != nil { - t.Fatal(err) - } - return r -} diff --git a/seaweed-block/core/frontend/durable/checkpoint_status_test.go b/seaweed-block/core/frontend/durable/checkpoint_status_test.go index e3eed2d4f2..321915ad91 100644 --- a/seaweed-block/core/frontend/durable/checkpoint_status_test.go +++ b/seaweed-block/core/frontend/durable/checkpoint_status_test.go @@ -7,16 +7,17 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) func TestDurableProvider_CheckpointPersistenceStatus(t *testing.T) { - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", 64, 4) + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64, ChunkBlocks: 4, ChunkCaptureInterval: 0, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/chunk_settled_cleanup_test.go b/seaweed-block/core/frontend/durable/chunk_settled_cleanup_test.go index 73f7a1987e..1420e6ac91 100644 --- a/seaweed-block/core/frontend/durable/chunk_settled_cleanup_test.go +++ b/seaweed-block/core/frontend/durable/chunk_settled_cleanup_test.go @@ -3,27 +3,27 @@ package durable import ( "context" "errors" - "github.com/seaweedfs/seaweed-block/core/storage" "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" ) -func TestChunkSettledIntentCleanupAfterProviderCancellation(t *testing.T) { +// After the provider is cancelled (Close), an ordinary call through the +// bound remote ends with the provider, while the cut's Abort still reaches +// the remote: a session left open is ended, never stranded. +func TestSession_ProviderCancellationAbortsTheOpenSession(t *testing.T) { inner := storage.NewMemChunkRemote() - id, err := inner.PutIntent(context.Background(), storage.ChunkIntent{Keys: []string{"unpublished"}}) - if err != nil { + if _, err := inner.Begin(context.Background()); err != nil { t.Fatal(err) } done, cancel := context.WithCancel(context.Background()) cancel() bound := &closeBoundRemote{ChunkRemote: inner, done: done} - if err = bound.DeleteIntent(context.Background(), id); !errors.Is(err, context.Canceled) { + if _, err := bound.Begin(context.Background()); !errors.Is(err, context.Canceled) { t.Fatalf("ordinary operation escaped Close: %v", err) } - if err = bound.DeleteSettledIntent(context.Background(), id); err != nil { - t.Fatal(err) - } - left, err := inner.ListIntents(context.Background()) - if err != nil || len(left) != 0 { - t.Fatalf("settled roots=%d err=%v", len(left), err) + bound.Abort() + if s := inner.OpenSession(); s != "" { + t.Fatalf("session %q left open after the provider's Abort", s) } } diff --git a/seaweed-block/core/frontend/durable/cut_durable_before_cas_test.go b/seaweed-block/core/frontend/durable/cut_durable_before_cas_test.go index c79536b7d9..5e6da7e12d 100644 --- a/seaweed-block/core/frontend/durable/cut_durable_before_cas_test.go +++ b/seaweed-block/core/frontend/durable/cut_durable_before_cas_test.go @@ -6,6 +6,9 @@ import ( "runtime" "testing" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -19,6 +22,16 @@ type casObservedRemote struct { reads, cass int } +// The layout adapter supplies content keys as well as the observed CAS path. +type casObservedLayoutRemote struct { + *casObservedRemote + keyer storage.ChunkKeyer +} + +func (r *casObservedLayoutRemote) ChunkKey(index uint64, sum [32]byte) string { + return r.keyer.ChunkKey(index, sum) +} + func (r *casObservedRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { r.reads++ if r.onGetHead != nil { @@ -46,11 +59,11 @@ func TestCutPublishesOnlyLocallyDurableLSN(t *testing.T) { t.Skip("the open store's byte-range lock keeps its files unreadable for the crash image") } ctx := context.Background() - inner := storage.NewMemChunkRemote() + fixture := newLayoutCase(t, pcBlocks, pcChunkBlocks) root, crash := t.TempDir(), t.TempDir() var ws *storage.WALStore var images int - remote := &casObservedRemote{ChunkRemote: inner} + remote := &casObservedRemote{} remote.onCAS = func(next storage.ChunkHead) { if ws == nil || next.RemoteLSN == 0 { return @@ -61,7 +74,16 @@ func TestCutPublishesOnlyLocallyDurableLSN(t *testing.T) { copyRootFiles(t, root, crash) // the root as a crash right after this CAS leaves it images++ } - a := chunkProvider(t, root, remote, v1View(), 0) + a := fixture.provider(t, root, v1View(), "s/r1", func(cfg *durable.ProviderConfig) { + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.cat, fixture.ref, me) + if err != nil { + return nil, err + } + remote.ChunkRemote = inner + return &casObservedLayoutRemote{casObservedRemote: remote, keyer: inner}, nil + } + }) s := openRecovered(t, a) ws = s.(*storage.WALStore) for lba := uint32(0); lba < 3; lba++ { @@ -75,9 +97,9 @@ func TestCutPublishesOnlyLocallyDurableLSN(t *testing.T) { if images == 0 { t.Fatal("no cut published a HEAD") } - head, _ := inner.GetHead(ctx) + head := fixture.head(t) - b := chunkProvider(t, crash, inner, v1View(), 0) + b := fixture.provider(t, crash, v1View(), "s/r1", nil) got := openRecovered(t, b) // the refusal must not fire on the crash image for lba := uint32(0); lba < 3; lba++ { buf, err := got.Read(lba) @@ -85,7 +107,7 @@ func TestCutPublishesOnlyLocallyDurableLSN(t *testing.T) { t.Fatal(err) } if !bytes.Equal(buf, block(byte(lba+1))) { - t.Fatalf("crash image under HEAD remote_lsn %d lost block %d", head.RemoteLSN, lba) + t.Fatalf("crash image under HEAD position %d lost block %d", head.Position, lba) } } } diff --git a/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go b/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go index 50e535ac3b..49c8daaa61 100644 --- a/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go +++ b/seaweed-block/core/frontend/durable/first_cut_known_zero_test.go @@ -15,14 +15,15 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) // fcutChunks is chunkProvider's chunk count: pcBlocks blocks of pcChunkBlocks. const fcutChunks = pcBlocks / pcChunkBlocks -func fcutProvider(t *testing.T, root string, remote storage.ChunkRemote) *durable.DurableProvider { - return chunkProvider(t, root, remote, v1View(), 0) +func fcutProvider(t *testing.T, root string, fixture *testutil.LayoutFixture, view *stubView) *durable.DurableProvider { + return layoutChunkProvider(t, root, fixture, view, 0) } // fcutCheckpointedPast waits until the store's checkpoint has moved past @@ -70,26 +71,6 @@ func fcutWrite(t *testing.T, ctx context.Context, p *durable.DurableProvider, lb return data } -// fcutHeadBlock reads block lba from the published HEAD (zero if its chunk -// is not named). -func fcutHeadBlock(t *testing.T, ctx context.Context, remote *storage.MemChunkRemote, lba int) []byte { - t.Helper() - head, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - ref, ok := head.Chunks[uint64(lba/pcChunkBlocks)] - if !ok { - return make([]byte, 4096) - } - c, err := remote.Get(ctx, ref.Key) - if err != nil { - t.Fatal(err) - } - off := (lba % pcChunkBlocks) * 4096 - return c[off : off+4096] -} - // TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks: a store created // empty against a HEAD never claimed, with two chunks written (one of them // already checkpointed out of the WAL), has two first-cut candidates, and @@ -98,8 +79,8 @@ func fcutHeadBlock(t *testing.T, ctx context.Context, remote *storage.MemChunkRe func TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() - p := fcutProvider(t, t.TempDir(), remote) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := fcutProvider(t, t.TempDir(), fixture, v1View()) st := fcutOpen(t, ctx, p) cp0 := st.(*storage.WALStore).CheckpointLSN() a := fcutWrite(t, ctx, p, pcChunkBlocks*1+1, 0x31) // chunk 1, checkpointed below @@ -114,7 +95,7 @@ func TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks(t *testing.T) { if got := fcutStats(t, p).LastCut.CandidateChunks; got != 2 { t.Errorf("first cut: %d candidate chunks; want 2", got) } - if !bytes.Equal(fcutHeadBlock(t, ctx, remote, pcChunkBlocks*1+1), a) || !bytes.Equal(fcutHeadBlock(t, ctx, remote, pcChunkBlocks*9+3), b) { + if !bytes.Equal(layoutHeadBlock(t, fixture, pcChunkBlocks*1+1), a) || !bytes.Equal(layoutHeadBlock(t, fixture, pcChunkBlocks*9+3), b) { t.Fatal("the first cut did not publish both written blocks") } } @@ -127,16 +108,16 @@ func TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks(t *testing.T) { func TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() - first := fcutProvider(t, t.TempDir(), remote) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + first := fcutProvider(t, t.TempDir(), fixture, v1View()) fcutOpen(t, ctx, first) if err := first.Close(); err != nil { t.Fatal(err) } - if head, err := remote.GetHead(ctx); err != nil || head.Gen == 0 || len(head.Chunks) != 0 { - t.Fatalf("setup: HEAD %+v %v; want a claimed HEAD naming no chunk", head, err) + if head := layoutHead(t, fixture); head.Gen <= 1 || head.Current != nil { + t.Fatalf("setup: HEAD %+v; want a claimed HEAD naming no chunk", head) } - p := fcutProvider(t, t.TempDir(), remote) + p := fcutProvider(t, t.TempDir(), fixture, viewAs("rB", 4)) fcutOpen(t, ctx, p) if got := fcutStats(t, p).DirtyChunks; got != 0 { t.Fatalf("fresh store against a claimed HEAD naming nothing: %d candidate chunks; want 0", got) @@ -150,8 +131,8 @@ func TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks(t *testing.T) { func TestFirstCutOfARestoreTargetKeepsItsHydrationPath(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() - first := fcutProvider(t, t.TempDir(), remote) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + first := fcutProvider(t, t.TempDir(), fixture, v1View()) fcutOpen(t, ctx, first) a := fcutWrite(t, ctx, first, pcChunkBlocks*3, 0x33) b := fcutWrite(t, ctx, first, pcChunkBlocks*7, 0x37) @@ -161,7 +142,7 @@ func TestFirstCutOfARestoreTargetKeepsItsHydrationPath(t *testing.T) { if err := first.Close(); err != nil { t.Fatal(err) } - p := fcutProvider(t, t.TempDir(), remote) + p := fcutProvider(t, t.TempDir(), fixture, viewAs("rB", 4)) fcutOpen(t, ctx, p) if s := fcutStats(t, p); s.AbsentChunks != 2 || s.DirtyChunks != 0 { t.Fatalf("restore target: %d absent, %d candidate chunks; want 2 absent and 0 candidates", s.AbsentChunks, s.DirtyChunks) @@ -180,10 +161,9 @@ func TestFirstCutOfARestoreTargetKeepsItsHydrationPath(t *testing.T) { // store whose marker says none ever did. func TestExplicitWALStoreRefusesAFreshChunkRoot(t *testing.T) { root := t.TempDir() - p := fcutProvider(t, root, storage.NewMemChunkRemote()) - if _, err := p.EnsureStorage("v1"); err != nil { - t.Fatal(err) - } + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := fcutProvider(t, root, fixture, v1View()) + fcutOpen(t, context.Background(), p) if err := p.Close(); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/head_belt_close_test.go b/seaweed-block/core/frontend/durable/head_belt_close_test.go deleted file mode 100644 index 803a34531a..0000000000 --- a/seaweed-block/core/frontend/durable/head_belt_close_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package durable_test - -import ( - "context" - "github.com/seaweedfs/seaweed-block/core/frontend" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" - "sync" - "testing" - "time" -) - -type beltClaimNotice struct { - storage.ChunkRemote - claimed chan struct{} - once sync.Once -} - -func (r *beltClaimNotice) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) { - gen, err := r.ChunkRemote.CASHead(ctx, v, h) - if err == nil { - r.once.Do(func() { close(r.claimed) }) - } - return gen, err -} - -func TestHeadBeltProviderCloseCancelsCooling(t *testing.T) { - r := &beltClaimNotice{ChunkRemote: seededRemote(t), claimed: make(chan struct{})} - view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) - p, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, - NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkHeadCoolingWindow: 3 * time.Second, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }, - }, view) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = p.Close() }) - if _, err := p.EnsureStorage("v1"); err != nil { - t.Fatal(err) - } - backend := p.Backend("v1") - ctx, cancel := context.WithCancel(context.Background()) - recovered := make(chan error, 1) - closed := make(chan error, 1) - closeStarted := false - t.Cleanup(func() { - cancel() - if !closeStarted { - go func() { closed <- p.Close() }() - } - select { - case <-recovered: - case <-time.After(5 * time.Second): - t.Error("recovery did not join") - } - select { - case <-closed: - case <-time.After(5 * time.Second): - t.Error("provider close did not join") - } - }) - go func() { _, err := p.RecoverVolume(ctx, "v1"); recovered <- err }() - select { - case <-r.claimed: - case <-time.After(30 * time.Second): - t.Fatal("takeover did not reach cooling") - } - closeStarted = true - go func() { closed <- p.Close() }() - select { - case err := <-closed: - closed <- err // cleanup joins this completed owner too - if err != nil { - t.Fatal(err) - } - case <-time.After(time.Second): - t.Fatal("provider Close waited for takeover cooling instead of canceling it") - } - if _, err := backend.Read(context.Background(), 0, make([]byte, 4096)); err == nil { - t.Fatal("closed provider served I/O") - } -} diff --git a/seaweed-block/core/frontend/durable/headroom_test.go b/seaweed-block/core/frontend/durable/headroom_test.go index 9f392f9cb3..f11e4a55bd 100644 --- a/seaweed-block/core/frontend/durable/headroom_test.go +++ b/seaweed-block/core/frontend/durable/headroom_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -22,8 +23,14 @@ func TestCreateRefusesWithoutLocalHeadroom(t *testing.T) { root := t.TempDir() cfg := durable.ProviderConfig{Impl: impl, StorageRoot: root, BlockSize: 4096, NumBlocks: 65536} if impl == durable.ImplWALStoreChunk { - remote := storage.NewMemChunkRemote() - cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return remote, nil } + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { + t.Fatal("headroom check must precede layout access") + return nil, nil + } + cfg.ChunkLayoutRemoteFor = func(string, layout.HolderID) (storage.ChunkRemote, error) { + t.Fatal("headroom check must precede layout access") + return nil, nil + } } p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { diff --git a/seaweed-block/core/frontend/durable/host_limit_test.go b/seaweed-block/core/frontend/durable/host_limit_test.go index ba0f09dc02..3feaf6a367 100644 --- a/seaweed-block/core/frontend/durable/host_limit_test.go +++ b/seaweed-block/core/frontend/durable/host_limit_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" "testing" @@ -28,14 +29,19 @@ func TestHostCutLimitDoesNotGateGuestIO(t *testing.T) { t.Fatal(e) } defer lim.Close() - r := storage.NewMemChunkRemote() - p, e := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, v1View()) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim} + fixture.Configure(&cfg) + p, e := durable.NewDurableProvider(cfg, v1View()) if e != nil { t.Fatal(e) } defer p.Close() s := openRecovered(t, p) - claimed := freshV1Claim(t, r) + claimed, found, e := fixture.Catalog.ReadHead(context.Background(), fixture.Ref) + if e != nil || !found { + t.Fatalf("initial layout HEAD: found=%v err=%v", found, e) + } if _, e = s.Write(0, block(0x72)); e != nil { t.Fatal(e) } @@ -54,7 +60,7 @@ func TestHostCutLimitDoesNotGateGuestIO(t *testing.T) { if b, e := s.Read(0); e != nil || b[0] != 0x72 { t.Fatal("limiter blocked read", e) } - h, _ := r.GetHead(context.Background()) + h, _, _ := fixture.Catalog.ReadHead(context.Background(), fixture.Ref) if h.Gen != claimed.Gen { t.Fatal("refused cut published") } @@ -67,8 +73,10 @@ func TestHostUnusablePoolExplicitDurabilityUsesUrgent(t *testing.T) { t.Fatal(err) } defer lim.Close() - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim} + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } @@ -86,8 +94,8 @@ func TestHostUnusablePoolExplicitDurabilityUsesUrgent(t *testing.T) { if err = p.MakeVolumeRemoteDurable(context.Background(), "v1", 1); err != nil { t.Fatalf("explicit durability was not urgent: %v", err) } - head, err := remote.GetHead(context.Background()) - if err != nil || head.RemoteLSN < 1 { + head, found, err := fixture.Catalog.ReadHead(context.Background(), fixture.Ref) + if err != nil || !found || head.Position < 1 { t.Fatalf("explicit durability did not publish: %+v %v", head, err) } if st := lim.Snapshot().(hostlimit.Stats); st.Fallback != 1 || st.SkippedByClass[hostlimit.Normal] != 1 { diff --git a/seaweed-block/core/frontend/durable/host_slot_wait_test.go b/seaweed-block/core/frontend/durable/host_slot_wait_test.go index 212b709562..137dda9e8c 100644 --- a/seaweed-block/core/frontend/durable/host_slot_wait_test.go +++ b/seaweed-block/core/frontend/durable/host_slot_wait_test.go @@ -9,7 +9,6 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/hostlimit" - "github.com/seaweedfs/seaweed-block/core/storage" ) // admitRecorder is the provider's cut budget: the real limiter, with @@ -44,11 +43,11 @@ func (r *admitRecorder) snapshot() []admitEvent { // whose only normal slot another process holds; release frees it. baseGen // is HEAD's generation once the volume is open (opening may publish one // itself, without a cut). -func slotWaitProvider(t *testing.T) (p *durable.DurableProvider, lim *admitRecorder, remote *storage.MemChunkRemote, release func(), baseGen uint64) { +func slotWaitProvider(t *testing.T) (p *durable.DurableProvider, lim *admitRecorder, c *layoutCase, release func(), baseGen uint64) { t.Helper() - c := hostlimit.DefaultConfig(t.TempDir()) - c.NormalSlots, c.UrgentSlots = 1, 1 - holder, err := hostlimit.New(c) + limitCfg := hostlimit.DefaultConfig(t.TempDir()) + limitCfg.NormalSlots, limitCfg.UrgentSlots = 1, 1 + holder, err := hostlimit.New(limitCfg) if err != nil { t.Fatal(err) } @@ -65,20 +64,17 @@ func slotWaitProvider(t *testing.T) (p *durable.DurableProvider, lim *admitRecor } } t.Cleanup(release) - inner, err := hostlimit.New(c) + inner, err := hostlimit.New(limitCfg) if err != nil { t.Fatal(err) } t.Cleanup(inner.Close) lim = &admitRecorder{Limiter: inner} - remote = storage.NewMemChunkRemote() - p, err = durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, - ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkCaptureInterval: 100 * time.Millisecond, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { p.Close() }) + c = newLayoutCase(t, pcBlocks, pcChunkBlocks) + p = c.provider(t, t.TempDir(), v1View(), "s/r1", func(cfg *durable.ProviderConfig) { + cfg.ChunkBudget = lim + cfg.ChunkCaptureInterval = 100 * time.Millisecond + }) s := openRecovered(t, p) if _, err = s.Write(0, block(0x5c)); err != nil { t.Fatal(err) @@ -86,11 +82,7 @@ func slotWaitProvider(t *testing.T) (p *durable.DurableProvider, lim *admitRecor if _, err = s.Sync(); err != nil { t.Fatal(err) } - h, err := remote.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - return p, lim, remote, release, h.Gen + return p, lim, c, release, c.head(t).Gen } // admitted reports whether any recorded Admit call succeeded. @@ -119,7 +111,7 @@ func refusedAt(events []admitEvent) []time.Time { // slot is held; once it frees, the next attempt is admitted within that // bound. Times are the limiter's own Admit calls. func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { - p, lim, remote, release, baseGen := slotWaitProvider(t) + p, lim, c, release, baseGen := slotWaitProvider(t) time.Sleep(2500 * time.Millisecond) refusals := refusedAt(lim.snapshot()) // A failure backoff (1 s, 2 s, ...) allows at most 3 attempts in 2.5 s. @@ -134,7 +126,7 @@ func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { if admitted(lim.snapshot()) { t.Fatal("a cut was admitted while the only slot was held") } - if h, _ := remote.GetHead(context.Background()); h.Gen != baseGen { + if h := c.head(t); h.Gen != baseGen { t.Fatalf("HEAD moved from generation %d to %d while the only slot was held", baseGen, h.Gen) } if cs := chunkStatus(t, p).CutSchedule; cs == nil || cs.HostSlotWaits == 0 || cs.HostSlotWaitSinceNs == 0 { @@ -160,7 +152,7 @@ func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { t.Fatalf("the first admission came %s after the slot freed; want <= 400 ms", d) } for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { - if h, _ := remote.GetHead(context.Background()); h.Gen > baseGen { + if h := c.head(t); h.Gen > baseGen { break } if time.Now().After(deadline) { @@ -180,7 +172,7 @@ func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { // A plain detach stops the timer before its seal; the seal (urgent, so it // takes the urgent slot) succeeds, and status no longer reports a wait. func TestSlotWaitEndsWithASuccessfulDetachSeal(t *testing.T) { - p, lim, remote, _, baseGen := slotWaitProvider(t) + p, lim, c, _, baseGen := slotWaitProvider(t) time.Sleep(600 * time.Millisecond) if len(refusedAt(lim.snapshot())) == 0 { t.Fatal("no refused timer cut while the slot was held") @@ -190,7 +182,7 @@ func TestSlotWaitEndsWithASuccessfulDetachSeal(t *testing.T) { if _, _, err := p.DetachVolumePlain(ctx, "v1"); err != nil { t.Fatalf("plain detach: %v", err) } - if h, _ := remote.GetHead(context.Background()); h.Gen <= baseGen { + if h := c.head(t); h.Gen <= baseGen { t.Fatalf("the seal did not publish: HEAD generation %d, %d at open", h.Gen, baseGen) } cs := chunkStatus(t, p).CutSchedule diff --git a/seaweed-block/core/frontend/durable/hydration_budget_test.go b/seaweed-block/core/frontend/durable/hydration_budget_test.go index f19d4f49c6..bc50ff1a8b 100644 --- a/seaweed-block/core/frontend/durable/hydration_budget_test.go +++ b/seaweed-block/core/frontend/durable/hydration_budget_test.go @@ -11,15 +11,47 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" - "github.com/seaweedfs/seaweed-block/core/storage" ) +func seededHydrationLayout(t *testing.T) *testutil.LayoutFixture { + t.Helper() + f := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkHolder: "old"} + f.Configure(&cfg) + source, err := durable.NewDurableProvider(cfg, viewAs("old", 1)) + if err != nil { + t.Fatal(err) + } + s := openRecovered(t, source) + writeSync(t, s, 33, 0x33) + writeSync(t, s, 100, 0x64) + if _, err := source.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + if err := source.Close(); err != nil { + t.Fatal(err) + } + return f +} + +func hydrationProvider(t *testing.T, f *testutil.LayoutFixture, view *stubView) *durable.DurableProvider { + t.Helper() + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks} + f.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p +} + func TestDurableHydration_ConfiguredLimitsReachStatus(t *testing.T) { for _, configured := range []bool{false, true} { cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks} - r := storage.NewMemChunkRemote() - cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return r, nil } + testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks).Configure(&cfg) wantWorkers, wantDepth := 2, 64 if configured { cfg.ChunkHydrationWorkers, cfg.ChunkHydrationQueueDepth = 3, 17 @@ -43,32 +75,32 @@ func TestDurableHydration_ConfiguredLimitsReachStatus(t *testing.T) { } type faultyHydrationRemote struct { - storage.ChunkRemote fault error corrupt bool } -func (r *faultyHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { +func (r *faultyHydrationRemote) Get(_ context.Context, _ string, b []byte) ([]byte, error) { if r.fault != nil { return nil, r.fault } - b, err := r.ChunkRemote.Get(ctx, key) - if err == nil && r.corrupt && len(b) > 0 { + if r.corrupt && len(b) > 0 { b = append([]byte(nil), b...) b[0] ^= 0xff } - return b, err + return b, nil } func TestDurableHydration_NVMePreservesPhysicalAndHashErrors(t *testing.T) { for _, corrupt := range []bool{false, true} { t.Run(map[bool]string{false: "joined physical", true: "hash"}[corrupt], func(t *testing.T) { - r := &faultyHydrationRemote{ChunkRemote: seededRemote(t), corrupt: corrupt} + f := seededHydrationLayout(t) + r := &faultyHydrationRemote{corrupt: corrupt} if !corrupt { r.fault = errors.Join(context.DeadlineExceeded, errors.New("physical remote read failure")) } - p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + p := hydrationProvider(t, f, v1View()) openRecovered(t, p) + f.Blobs.GetHook = r.Get b, err := p.Open(context.Background(), "v1") if err != nil { t.Fatal(err) @@ -83,14 +115,13 @@ func TestDurableHydration_NVMePreservesPhysicalAndHashErrors(t *testing.T) { } type pacedHydrationRemote struct { - storage.ChunkRemote gets atomic.Int64 second chan struct{} once sync.Once } func (r *pacedHydrationRemote) release() { r.once.Do(func() { close(r.second) }) } -func (r *pacedHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { +func (r *pacedHydrationRemote) Get(ctx context.Context, _ string, data []byte) ([]byte, error) { if r.gets.Add(1) == 1 { timer := time.NewTimer(120 * time.Millisecond) defer timer.Stop() @@ -106,14 +137,16 @@ func (r *pacedHydrationRemote) Get(ctx context.Context, key string) ([]byte, err return nil, ctx.Err() } } - return r.ChunkRemote.Get(ctx, key) + return data, nil } func TestDurableHydration_MultipleChunksShareOneDeadline(t *testing.T) { - r := &pacedHydrationRemote{ChunkRemote: seededRemote(t), second: make(chan struct{})} - p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + f := seededHydrationLayout(t) + r := &pacedHydrationRemote{second: make(chan struct{})} + p := hydrationProvider(t, f, v1View()) t.Cleanup(r.release) openRecovered(t, p) + f.Blobs.GetHook = r.Get b, err := p.Open(context.Background(), "v1") if err != nil { t.Fatal(err) @@ -145,7 +178,6 @@ func TestDurableHydration_MultipleChunksShareOneDeadline(t *testing.T) { } type heldHydrationRemote struct { - storage.ChunkRemote gate chan struct{} once sync.Once gets atomic.Int64 @@ -153,7 +185,7 @@ type heldHydrationRemote struct { } func (r *heldHydrationRemote) release() { r.once.Do(func() { close(r.gate) }) } -func (r *heldHydrationRemote) Get(ctx context.Context, key string) ([]byte, error) { +func (r *heldHydrationRemote) Get(ctx context.Context, _ string, data []byte) ([]byte, error) { r.gets.Add(1) if r.entered != nil { select { @@ -163,17 +195,19 @@ func (r *heldHydrationRemote) Get(ctx context.Context, key string) ([]byte, erro } select { case <-r.gate: - return r.ChunkRemote.Get(ctx, key) + return data, nil case <-ctx.Done(): return nil, ctx.Err() } } func TestDurableHydration_HostRetriesJoinOwnedFetch(t *testing.T) { - r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} - p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + f := seededHydrationLayout(t) + r := &heldHydrationRemote{gate: make(chan struct{}), entered: make(chan struct{}, 1)} + p := hydrationProvider(t, f, v1View()) t.Cleanup(r.release) openRecovered(t, p) + f.Blobs.GetHook = r.Get b, err := p.Open(context.Background(), "v1") if err != nil { t.Fatal(err) @@ -219,11 +253,13 @@ func TestDurableHydration_HostRetriesJoinOwnedFetch(t *testing.T) { } func TestDurableHydration_FenceWinsCallerExpiry(t *testing.T) { - r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + f := seededHydrationLayout(t) + r := &heldHydrationRemote{gate: make(chan struct{}), entered: make(chan struct{}, 1)} view := v1View() - p := chunkProvider(t, t.TempDir(), r, view, 0) + p := hydrationProvider(t, f, view) t.Cleanup(r.release) openRecovered(t, p) + f.Blobs.GetHook = r.Get b, err := p.Open(context.Background(), "v1") if err != nil { t.Fatal(err) @@ -270,8 +306,9 @@ func TestDurableHydration_ReadAndRMWPreserveCallerBudget(t *testing.T) { name = "rmw" } t.Run(name, func(t *testing.T) { - r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{})} - p := chunkProvider(t, t.TempDir(), r, v1View(), 0) + f := seededHydrationLayout(t) + r := &heldHydrationRemote{gate: make(chan struct{})} + p := hydrationProvider(t, f, v1View()) t.Cleanup(r.release) s, err := p.EnsureStorage("v1") if err != nil { @@ -280,6 +317,7 @@ func TestDurableHydration_ReadAndRMWPreserveCallerBudget(t *testing.T) { if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil { t.Fatal(err) } + f.Blobs.GetHook = r.Get b, err := p.Open(context.Background(), "v1") if err != nil { t.Fatal(err) @@ -316,11 +354,13 @@ func TestDurableHydration_ReadAndRMWPreserveCallerBudget(t *testing.T) { } func TestDurableHydration_RMWFenceWinsCallerExpiry(t *testing.T) { - r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + f := seededHydrationLayout(t) + r := &heldHydrationRemote{gate: make(chan struct{}), entered: make(chan struct{}, 1)} view := v1View() - p := chunkProvider(t, t.TempDir(), r, view, 0) + p := hydrationProvider(t, f, view) t.Cleanup(r.release) openRecovered(t, p) + f.Blobs.GetHook = r.Get b, err := p.Open(context.Background(), "v1") if err != nil { t.Fatal(err) @@ -371,11 +411,13 @@ func TestDurableHydration_RMWFenceWinsCallerExpiry(t *testing.T) { } func TestDurableHydration_RMWFenceKeepsCommittedPrefix(t *testing.T) { - r := &heldHydrationRemote{ChunkRemote: seededRemote(t), gate: make(chan struct{}), entered: make(chan struct{}, 1)} + f := seededHydrationLayout(t) + r := &heldHydrationRemote{gate: make(chan struct{}), entered: make(chan struct{}, 1)} view := v1View() - p := chunkProvider(t, t.TempDir(), r, view, 0) + p := hydrationProvider(t, f, view) t.Cleanup(r.release) openRecovered(t, p) + f.Blobs.GetHook = r.Get b, err := p.Open(context.Background(), "v1") if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/frontend/durable/hydration_progress_test.go b/seaweed-block/core/frontend/durable/hydration_progress_test.go index 3841d2b410..dc83c5fa2d 100644 --- a/seaweed-block/core/frontend/durable/hydration_progress_test.go +++ b/seaweed-block/core/frontend/durable/hydration_progress_test.go @@ -5,8 +5,6 @@ import ( "context" "testing" "time" - - "github.com/seaweedfs/seaweed-block/core/storage" ) func hydrationProgress(t *testing.T, p *DurableProvider) (absent int, hydrated uint64) { @@ -29,7 +27,7 @@ func hydrationProgress(t *testing.T, p *DurableProvider) (absent int, hydrated u func TestHydrationProgressCountersFollowFirstReads(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - mem := storage.NewMemChunkRemote() + mem := newKZLayout(t) src := kzProvider(t, t.TempDir(), mem) if _, err := src.EnsureStorage("v1"); err != nil { t.Fatal(err) @@ -53,7 +51,7 @@ func TestHydrationProgressCountersFollowFirstReads(t *testing.T) { t.Fatal(err) } - p := kzProvider(t, t.TempDir(), mem) + p := kzProviderAt(t, t.TempDir(), mem, "r2", 4) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/known_zero_premise_test.go b/seaweed-block/core/frontend/durable/known_zero_premise_test.go index d9d7636534..d6bf882625 100644 --- a/seaweed-block/core/frontend/durable/known_zero_premise_test.go +++ b/seaweed-block/core/frontend/durable/known_zero_premise_test.go @@ -4,23 +4,80 @@ import ( "bytes" "context" "errors" - "os" + "fmt" + "sync" "sync/atomic" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/storage" ) -// kzProvider is a walstore-chunk provider for v1 (256 blocks, 16 per -// chunk: 16 chunks) over root and remote. -func kzProvider(t *testing.T, root string, remote storage.ChunkRemote) *DurableProvider { +type kzLayoutBlobs struct { + sync.Mutex + b map[string][]byte + gets atomic.Int64 +} + +func (b *kzLayoutBlobs) Put(_ context.Context, data []byte) (string, error) { + b.Lock() + defer b.Unlock() + id := fmt.Sprint(len(b.b) + 1) + b.b[id] = append([]byte(nil), data...) + return id, nil +} +func (b *kzLayoutBlobs) Get(_ context.Context, id string) ([]byte, error) { + b.gets.Add(1) + b.Lock() + defer b.Unlock() + v, ok := b.b[id] + if !ok { + return nil, chunkstore.ErrBlobNotFound + } + return append([]byte(nil), v...), nil +} + +type kzLayout struct { + cat *chunkstore.BCatalog + ref chunkstore.VolumeRef + blobs *kzLayoutBlobs +} + +func newKZLayout(t *testing.T) *kzLayout { t.Helper() - id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1} + b := &kzLayoutBlobs{b: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), b, "/kz") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(context.Background(), ref, layout.Geometry{SizeBytes: 256 * 4096, BlockSize: 4096, ChunkBytes: 16 * 4096}); err != nil { + t.Fatal(err) + } + return &kzLayout{cat: cat, ref: ref, blobs: b} +} + +// kzProvider is a B-layout chunk provider for v1 (16 chunks). +func kzProvider(t *testing.T, root string, remote *kzLayout) *DurableProvider { + return kzProviderAt(t, root, remote, "r1", 3) +} + +func kzProviderAt(t *testing.T, root string, remote *kzLayout, replica string, epoch uint64) *DurableProvider { + t.Helper() + id := frontend.Identity{VolumeID: "v1", ReplicaID: replica, Epoch: epoch, EndpointVersion: 1} p, err := NewDurableProvider(ProviderConfig{ Impl: ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return remote.cat.Store(remote.ref) }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(remote.cat, remote.ref, me) + }, }, precopyQueueView{id}) if err != nil { t.Fatal(err) @@ -40,6 +97,20 @@ func kzCandidates(t *testing.T, p *DurableProvider) int { return -1 } +func kzFreshAtRoot(t *testing.T, path string) bool { + t.Helper() + ws, err := storage.OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + defer ws.Close() + _, fresh, ok := ws.LayoutIdentity() + if !ok { + t.Fatal("layout identity missing from durable root") + } + return fresh +} + // The premise of RULE-FRESH-KNOWN-ZERO: until the attach commit retires the // fresh marker, no write reaches the store. Held at that boundary (after the // claim and the certification, before the commit), a frontend write is not @@ -48,7 +119,7 @@ func kzCandidates(t *testing.T, p *DurableProvider) int { func TestNoWriteReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - p := kzProvider(t, t.TempDir(), storage.NewMemChunkRemote()) + p := kzProvider(t, t.TempDir(), newKZLayout(t)) st, err := p.EnsureStorage("v1") if err != nil { t.Fatal(err) @@ -92,7 +163,7 @@ func TestNoWriteReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) { func TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - root, remote := t.TempDir(), storage.NewMemChunkRemote() + root, remote := t.TempDir(), newKZLayout(t) p := kzProvider(t, root, remote) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) @@ -105,8 +176,8 @@ func TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit(t *testing.T) { if err := p.Close(); err != nil { t.Fatal(err) } - if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { - t.Fatalf("fresh marker after the crash: %v; want it kept", err) + if !kzFreshAtRoot(t, p.volumePath("v1")) { + t.Fatal("durable layout identity was not fresh after the crash") } p2 := kzProvider(t, root, remote) if _, err := p2.EnsureStorage("v1"); err != nil { @@ -125,7 +196,7 @@ func TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit(t *testing.T) { func TestFreshKnownZeroNotAfterARestartBeforeAnyAttach(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - root, remote := t.TempDir(), storage.NewMemChunkRemote() + root, remote := t.TempDir(), newKZLayout(t) p := kzProvider(t, root, remote) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) @@ -153,7 +224,7 @@ func TestFreshKnownZeroNotAfterARestartBeforeAnyAttach(t *testing.T) { func TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - root, remote := t.TempDir(), storage.NewMemChunkRemote() + root, remote := t.TempDir(), newKZLayout(t) p := kzProvider(t, root, remote) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) @@ -166,8 +237,8 @@ func TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking(t *testing.T) { if err := p.Close(); err != nil { t.Fatal(err) } - if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); !os.IsNotExist(err) { - t.Fatalf("fresh marker after the crash: %v; want it retired", err) + if kzFreshAtRoot(t, p.volumePath("v1")) { + t.Fatal("durable layout identity remained fresh after its clear") } p2 := kzProvider(t, root, remote) if _, err := p2.EnsureStorage("v1"); err != nil { @@ -183,7 +254,7 @@ func TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking(t *testing.T) { } // kzWriteAndPublish writes chunk 5, cuts, and checks HEAD publishes it. -func kzWriteAndPublish(t *testing.T, ctx context.Context, p *DurableProvider, remote *storage.MemChunkRemote) { +func kzWriteAndPublish(t *testing.T, ctx context.Context, p *DurableProvider, remote *kzLayout) { t.Helper() want := bytes.Repeat([]byte{0x6b}, 4096) if _, err := p.Backend("v1").Write(ctx, 5*16*4096, want); err != nil { @@ -195,16 +266,24 @@ func kzWriteAndPublish(t *testing.T, ctx context.Context, p *DurableProvider, re if _, err := p.CaptureVolume(ctx, "v1"); err != nil { t.Fatal(err) } - head, err := remote.GetHead(ctx) + head, found, err := remote.cat.ReadHead(ctx, remote.ref) + if err != nil || !found || head.Current == nil { + t.Fatalf("the cut did not publish a B root: found=%v err=%v head=%+v", found, err, head) + } + st, err := remote.cat.Store(remote.ref) if err != nil { t.Fatal(err) } - ref, ok := head.Chunks[5] - if !ok { - t.Fatal("the cut did not publish chunk 5") + reader, err := layout.NewReader("/kz", remote.ref.Dir(), st.Fetch) + if err != nil { + t.Fatal(err) } - chunk, err := remote.Get(ctx, ref.Key) - if err != nil || !bytes.Equal(chunk[:4096], want) { + image, err := reader.Open(ctx, *head.Current) + if err != nil { + t.Fatal(err) + } + chunk, err := image.Chunk(ctx, 5) + if err != nil || chunk.Zero || !bytes.Equal(chunk.Data[:4096], want) { t.Fatalf("published chunk 5: %v", err) } if got := kzCandidates(t, p); got != 0 { @@ -212,17 +291,6 @@ func kzWriteAndPublish(t *testing.T, ctx context.Context, p *DurableProvider, re } } -// kzCountingRemote counts chunk reads (Get) of the remote it wraps. -type kzCountingRemote struct { - storage.ChunkRemote - gets atomic.Int64 -} - -func (r *kzCountingRemote) Get(ctx context.Context, key string) ([]byte, error) { - r.gets.Add(1) - return r.ChunkRemote.Get(ctx, key) -} - // The premise again, for fills (test #12): until the attach commit retires // the fresh marker, no fetch and no extent write reaches the store. A restore // target whose HEAD names two chunks is held at the commit boundary; a @@ -233,8 +301,8 @@ func (r *kzCountingRemote) Get(ctx context.Context, key string) ([]byte, error) func TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - mem := storage.NewMemChunkRemote() - src := kzProvider(t, t.TempDir(), mem) + remote := newKZLayout(t) + src := kzProvider(t, t.TempDir(), remote) if _, err := src.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -257,19 +325,18 @@ func TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit(t *testing.T) { t.Fatal(err) } - remote := &kzCountingRemote{ChunkRemote: mem} - p := kzProvider(t, t.TempDir(), remote) + p := kzProviderAt(t, t.TempDir(), remote, "r2", 4) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } var readErr error var getsAtBoundary int64 = -1 p.testBeforeChunkFreshRetire = func() error { - before := remote.gets.Load() + before := remote.blobs.gets.Load() rctx, rcancel := context.WithTimeout(ctx, 300*time.Millisecond) defer rcancel() _, readErr = p.Backend("v1").Read(rctx, 3*16*4096, make([]byte, 4096)) - getsAtBoundary = remote.gets.Load() - before + getsAtBoundary = remote.blobs.gets.Load() - before return nil } if _, err := p.RecoverVolume(ctx, "v1"); err != nil { diff --git a/seaweed-block/core/frontend/durable/m5_sync_bench_test.go b/seaweed-block/core/frontend/durable/m5_sync_bench_test.go index e1a0cf78e5..8c3fe1f46f 100644 --- a/seaweed-block/core/frontend/durable/m5_sync_bench_test.go +++ b/seaweed-block/core/frontend/durable/m5_sync_bench_test.go @@ -7,7 +7,7 @@ import ( "fmt" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "os" "os/exec" "sort" @@ -27,9 +27,8 @@ func BenchmarkQD1PairedBackendSync(b *testing.B) { fmt.Printf("STUDY_FS %s", out) } cfg := durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: 32768, BlockSize: 4096, ChunkBlocks: 1024} - remote := storage.NewMemChunkRemote() if impl == durable.ImplWALStoreChunk { - cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return remote, nil } + testutil.NewLayoutFixture(b, "v1", 32768, 1024).Configure(&cfg) } p, err := durable.NewDurableProvider(cfg, newStubView(healthyProj(id))) if err != nil { diff --git a/seaweed-block/core/frontend/durable/m5_sync_concurrent_bench_test.go b/seaweed-block/core/frontend/durable/m5_sync_concurrent_bench_test.go index 5dd7dc59d8..2567a9d08a 100644 --- a/seaweed-block/core/frontend/durable/m5_sync_concurrent_bench_test.go +++ b/seaweed-block/core/frontend/durable/m5_sync_concurrent_bench_test.go @@ -7,7 +7,7 @@ import ( "fmt" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "os" "runtime" "sync" @@ -22,8 +22,7 @@ func BenchmarkConcurrentBackendSync(b *testing.B) { id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} cfg := durable.ProviderConfig{Impl: impl, StorageRoot: b.TempDir(), NumBlocks: 32768, BlockSize: 4096, ChunkBlocks: 1024} if impl == durable.ImplWALStoreChunk { - r := storage.NewMemChunkRemote() - cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return r, nil } + testutil.NewLayoutFixture(b, "v1", 32768, 1024).Configure(&cfg) } p, err := durable.NewDurableProvider(cfg, newStubView(healthyProj(id))) if err != nil { diff --git a/seaweed-block/core/frontend/durable/m5_sync_crash_layout_integration_test.go b/seaweed-block/core/frontend/durable/m5_sync_crash_layout_integration_test.go new file mode 100644 index 0000000000..e733e6f5e0 --- /dev/null +++ b/seaweed-block/core/frontend/durable/m5_sync_crash_layout_integration_test.go @@ -0,0 +1,216 @@ +//go:build chunkstore_integration + +package durable_test + +import ( + "bytes" + "context" + "fmt" + "math/rand" + "net" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// The B arm uses a real filer so the child and parent observe the same HEAD. +// Run with CHUNKSTORE_WEED=/path/to/weed and -tags chunkstore_integration. +func qd1LayoutWeed(t *testing.T) string { + t.Helper() + weed := os.Getenv("CHUNKSTORE_WEED") + if weed == "" { + t.Skip("CHUNKSTORE_WEED not set") + } + dir := t.TempDir() + used := map[int]bool{} + port := func() int { + t.Helper() + for i := 0; i < 200; i++ { + p := 20000 + rand.Intn(20000) + if used[p] || used[p+10000] { + continue + } + ok := true + for _, n := range []int{p, p + 10000} { + l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", n)) + if err != nil { + ok = false + break + } + l.Close() + } + if ok { + used[p], used[p+10000] = true, true + return p + } + } + t.Fatal("no free local port pair") + return 0 + } + mp, vp, fp := port(), port(), port() + run := func(name string, args ...string) { + t.Helper() + f, err := os.Create(filepath.Join(dir, name+".log")) + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(weed, args...) + cmd.Dir, cmd.Stdout, cmd.Stderr = dir, f, f + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = cmd.Process.Kill() + _, _ = cmd.Process.Wait() + _ = f.Close() + if t.Failed() { + b, _ := os.ReadFile(f.Name()) + if len(b) > 4000 { + b = b[len(b)-4000:] + } + t.Logf("%s log tail:\n%s", name, b) + } + }) + } + wait := func(addr string) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for time.Now().Before(deadline) { + c, err := net.DialTimeout("tcp", addr, 200*time.Millisecond) + if err == nil { + _ = c.Close() + return + } + time.Sleep(100 * time.Millisecond) + } + t.Fatalf("%s did not start", addr) + } + for _, name := range []string{"m", "v", "f"} { + if err := os.Mkdir(filepath.Join(dir, name), 0755); err != nil { + t.Fatal(err) + } + } + master := fmt.Sprintf("127.0.0.1:%d", mp) + run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000") + wait(master) + run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+master, "-max=32") + run("filer", "filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+master, "-defaultStoreDir="+filepath.Join(dir, "f")) + grpc := fmt.Sprintf("127.0.0.1:%d", fp+10000) + wait(grpc) + return grpc +} + +func qd1LayoutProvider(t *testing.T, root, grpc, base, idText string) (*durable.DurableProvider, *durable.StorageBackend) { + t.Helper() + id, err := layout.ParseVolumeID(idText) + if err != nil { + t.Fatal(err) + } + client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: grpc, Collection: "swblock", AssignPath: base}) + if err != nil { + t.Fatal(err) + } + cat, err := chunkstore.NewBCatalog(client, client, base) + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 128, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r1"} + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return cat.Store(ref) } + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + } + identity := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + p, err := durable.NewDurableProvider(cfg, newStubView(healthyProj(identity))) + if err != nil { + t.Fatal(err) + } + raw, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + return p, raw.(*durable.StorageBackend) +} + +func TestQD1LayoutSyncCrashWriter(t *testing.T) { + grpc := os.Getenv("QD1_LAYOUT_GRPC") + if grpc == "" { + t.Skip("subprocess only") + } + p, b := qd1LayoutProvider(t, os.Getenv("QD1_LAYOUT_ROOT"), grpc, os.Getenv("QD1_LAYOUT_BASE"), os.Getenv("QD1_LAYOUT_ID")) + _ = p // Exit without Close; the parent reopens the same root and filer. + before := b.WriteProfile().BackendSyncOps + for i := 0; i < 64; i++ { + data := bytes.Repeat([]byte{byte(i + 1)}, 4096) + if _, err := b.Write(context.Background(), int64(i)*4096, data); err != nil { + t.Fatal(err) + } + for j := 0; j < 2; j++ { + if err := b.Sync(context.Background()); err != nil { + t.Fatal(err) + } + } + } + if n := b.WriteProfile().BackendSyncOps - before; n != 128 { + t.Fatalf("Sync calls=%d", n) + } + fmt.Println("QD1_LAYOUT_CRASH_READY Syncs=128 blocks=64 no_Close=true") + os.Exit(0) +} + +func TestQD1LayoutSyncCrashReopen(t *testing.T) { + grpc := qd1LayoutWeed(t) + base := fmt.Sprintf("/swblock/qd1-%d", time.Now().UnixNano()) + client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: grpc, Collection: "swblock", AssignPath: base}) + if err != nil { + t.Fatal(err) + } + defer client.Close() + cat, err := chunkstore.NewBCatalog(client, client, base) + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + if _, err := cat.CreateVolume(context.Background(), chunkstore.VolumeRef{Name: "v1", ID: id}, layout.Geometry{SizeBytes: 128 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + root := filepath.Join(t.TempDir(), "local") + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestQD1LayoutSyncCrashWriter$", "-test.v") + cmd.WaitDelay = 2 * time.Second + cmd.Env = append(os.Environ(), "QD1_LAYOUT_GRPC="+grpc, "QD1_LAYOUT_ROOT="+root, "QD1_LAYOUT_BASE="+base, "QD1_LAYOUT_ID="+id.String()) + out, err := cmd.CombinedOutput() + t.Logf("%s", out) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(out, []byte("QD1_LAYOUT_CRASH_READY Syncs=128 blocks=64 no_Close=true")) { + t.Fatal("child did not reach acknowledged sync") + } + p, b := qd1LayoutProvider(t, root, grpc, base, id.String()) + defer p.Close() + for i := 0; i < 64; i++ { + got := make([]byte, 4096) + if _, err := b.Read(context.Background(), int64(i)*4096, got); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, bytes.Repeat([]byte{byte(i + 1)}, 4096)) { + t.Fatalf("acknowledged block %d lost after abrupt exit", i) + } + } +} diff --git a/seaweed-block/core/frontend/durable/m5_sync_crash_test.go b/seaweed-block/core/frontend/durable/m5_sync_crash_test.go index c83b890e49..aaee58e60b 100644 --- a/seaweed-block/core/frontend/durable/m5_sync_crash_test.go +++ b/seaweed-block/core/frontend/durable/m5_sync_crash_test.go @@ -11,17 +11,12 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" ) func qd1CrashProvider(t *testing.T, impl durable.ImplName, root string) (*durable.DurableProvider, *durable.StorageBackend) { t.Helper() id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} cfg := durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: 128, BlockSize: 4096, ChunkBlocks: 4} - if impl == durable.ImplWALStoreChunk { - remote := storage.NewMemChunkRemote() - cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return remote, nil } - } p, err := durable.NewDurableProvider(cfg, newStubView(healthyProj(id))) if err != nil { t.Fatal(err) @@ -71,7 +66,7 @@ func TestQD1BackendSyncCrashWriter(t *testing.T) { } func TestQD1BackendSyncCrashReopen(t *testing.T) { - for _, impl := range []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStoreChunk} { + for _, impl := range []durable.ImplName{durable.ImplSmartWAL} { t.Run(string(impl), func(t *testing.T) { root := t.TempDir() childCtx, cancelChild := context.WithTimeout(context.Background(), 30*time.Second) diff --git a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go index d6020247f2..644c405126 100644 --- a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go +++ b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go @@ -2,10 +2,13 @@ package durable import ( "context" - "github.com/seaweedfs/seaweed-block/core/frontend" - "github.com/seaweedfs/seaweed-block/core/storage" + "errors" + "fmt" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" ) type maintenanceStubLayer struct{ storage.ChunkLayer } @@ -90,3 +93,37 @@ func TestMaintenanceSameHandleRearmsAfterJoinedStop(t *testing.T) { } } } + +// observingLayer records what the maintenance loop hands it. +type observingLayer struct { + maintenanceStubLayer + seen chan error +} + +func (l *observingLayer) ObserveRemoteError(err error) error { + select { + case l.seen <- err: + default: + } + return err +} + +// The holder's cleaning may be the first call to see HEAD move away: the +// maintenance loop hands its refusal to the layer, which latches the fence. +func TestMaintenanceRefusalReachesTheLayer(t *testing.T) { + layer := &observingLayer{seen: make(chan error, 1)} + p := &DurableProvider{cfg: ProviderConfig{ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(context.Context, string) error { + return fmt.Errorf("%w: cleaning refused", storage.ErrChunkLayerFenced) + }}} + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + go p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return true }) + select { + case err := <-layer.seen: + if !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("the layer saw %v; want the fence", err) + } + case <-ctx.Done(): + t.Fatal("the cleaning refusal never reached the layer") + } +} diff --git a/seaweed-block/core/frontend/durable/one_process_per_volume_test.go b/seaweed-block/core/frontend/durable/one_process_per_volume_test.go index 05bf01e330..a10e6c1f9a 100644 --- a/seaweed-block/core/frontend/durable/one_process_per_volume_test.go +++ b/seaweed-block/core/frontend/durable/one_process_per_volume_test.go @@ -8,18 +8,20 @@ import ( "testing" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) // lockedProvider is a chunk provider whose host volume-lock directory is dir. -func lockedProvider(t *testing.T, root, lockDir string, remote storage.ChunkRemote) *durable.DurableProvider { +func lockedProvider(t *testing.T, root, lockDir string, fixture *testutil.LayoutFixture) *durable.DurableProvider { t.Helper() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: root, HostVolumeLock: true, VolumeLockDirTestOnly: lockDir, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatalf("NewDurableProvider: %v", err) } @@ -32,9 +34,9 @@ func lockedProvider(t *testing.T, root, lockDir string, remote storage.ChunkRemo // the same host lock directory) is refused before its store opens; once the // first closes, the volume can be opened again. func TestOneLiveProcessPerVolumePerHost(t *testing.T) { - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) lockDir := t.TempDir() - a := lockedProvider(t, t.TempDir(), lockDir, remote) + a := lockedProvider(t, t.TempDir(), lockDir, fixture) if _, err := a.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -43,21 +45,21 @@ func TestOneLiveProcessPerVolumePerHost(t *testing.T) { t.Fatal(err) } bRoot := t.TempDir() - b := lockedProvider(t, bRoot, lockDir, remote) + b := lockedProvider(t, bRoot, lockDir, fixture) if _, err := b.EnsureStorage("v1"); !errors.Is(err, storage.ErrWALStoreLocked) { t.Fatalf("a second provider for the same volume on this host opened: %v; want %v", err, storage.ErrWALStoreLocked) } if left, err := os.ReadDir(bRoot); err != nil || len(left) != 0 { t.Fatalf("the refused second provider touched its root: %v %v", left, err) } - other := lockedProvider(t, t.TempDir(), lockDir, remote) + other := lockedProvider(t, t.TempDir(), lockDir, fixture) if _, err := other.EnsureStorage("v2"); err != nil { t.Fatalf("another volume was refused by v1's lock: %v", err) } if err := a.Close(); err != nil { t.Fatal(err) } - c := lockedProvider(t, t.TempDir(), lockDir, remote) + c := lockedProvider(t, t.TempDir(), lockDir, fixture) if _, err := c.EnsureStorage("v1"); err != nil { t.Fatalf("the volume could not be opened after its first owner closed: %v", err) } @@ -120,17 +122,17 @@ func TestHostVolumeLockRefusesNonDirectoryLockPath(t *testing.T) { // A lock file this process cannot write (one another user created, as the // root ublk unit does) is still taken: the lock opens it read-only. func TestHostVolumeLockTakesReadOnlyLockFile(t *testing.T) { - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) lockDir := t.TempDir() path := filepath.Join(lockDir, "v1.lock") if err := os.WriteFile(path, nil, 0o444); err != nil { t.Fatal(err) } - a := lockedProvider(t, t.TempDir(), lockDir, remote) + a := lockedProvider(t, t.TempDir(), lockDir, fixture) if _, err := a.EnsureStorage("v1"); err != nil { t.Fatalf("a read-only lock file refused the volume: %v", err) } - b := lockedProvider(t, t.TempDir(), lockDir, remote) + b := lockedProvider(t, t.TempDir(), lockDir, fixture) if _, err := b.EnsureStorage("v1"); !errors.Is(err, storage.ErrWALStoreLocked) { t.Fatalf("a second provider on a read-only lock file: %v; want %v", err, storage.ErrWALStoreLocked) } diff --git a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go index b3b7b805da..60feaeee00 100644 --- a/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go +++ b/seaweed-block/core/frontend/durable/precopy_fifty_iops_test.go @@ -12,6 +12,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -38,8 +39,9 @@ func TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing(t *testing.T) { func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool, fixedDelay time.Duration) { t.Helper() - remote := &precopyFixedSampleRemote{MemChunkRemote: storage.NewMemChunkRemote()} - p := precopyProvider(t, remote, &parkView{stubView: v1View()}) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + remote := &precopyLayoutDelayedRemote{} + p := precopyBProvider(t, fixture, &parkView{stubView: v1View()}, remote) openRecovered(t, p) backend, err := p.Open(context.Background(), "v1") if err != nil { @@ -198,7 +200,7 @@ func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool, fixedDelay t // Staging or later rounds may leave an empty tail, which needs // only measured fixed cost. A nonempty first tail still needs // three upload samples; the one-sample fixture cannot supply them. - if err != nil || (len(result.Precopy.Rounds) == 1 && result.Precopy.TailBytes != 0) || guestErrors.Load() != 0 || !bytes.Equal(headBlock(t, remote.MemChunkRemote, 1), block(0x5b)) { + if err != nil || (len(result.Precopy.Rounds) == 1 && result.Precopy.TailBytes != 0) || guestErrors.Load() != 0 || !bytes.Equal(layoutHeadBlock(t, fixture, 1), block(0x5b)) { t.Fatalf("cold samples claimed premature fit: report=%+v guest_errors=%d err=%v", result.Precopy, guestErrors.Load(), err) } return @@ -274,7 +276,7 @@ func precopyFiftyIOPS(t *testing.T, samples byte, wantUnknown bool, fixedDelay t if guestErrors.Load() != 0 { t.Fatalf("guest errors before cutover: %d", guestErrors.Load()) } - if !bytes.Equal(headBlock(t, remote.MemChunkRemote, 1), block(0x5b)) { + if !bytes.Equal(layoutHeadBlock(t, fixture, 1), block(0x5b)) { t.Fatal("final cut lost synchronous writer bytes") } } diff --git a/seaweed-block/core/frontend/durable/precopy_rolling_pause_test.go b/seaweed-block/core/frontend/durable/precopy_rolling_pause_test.go index 47547cfd63..292cf52f86 100644 --- a/seaweed-block/core/frontend/durable/precopy_rolling_pause_test.go +++ b/seaweed-block/core/frontend/durable/precopy_rolling_pause_test.go @@ -6,28 +6,23 @@ import ( "testing" "time" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) -type precopyRollingHeldRemote struct { - *storage.MemChunkRemote - entered, release chan struct{} - once sync.Once -} - -func (r *precopyRollingHeldRemote) Put(ctx context.Context, key string, data []byte) error { - r.once.Do(func() { close(r.entered) }) - select { - case <-r.release: - return r.MemChunkRemote.Put(ctx, key, data) - case <-ctx.Done(): - return ctx.Err() - } -} - func TestPrecopyRollingUploadReopensTentativeAdmission(t *testing.T) { - r := &precopyRollingHeldRemote{MemChunkRemote: storage.NewMemChunkRemote(), entered: make(chan struct{}), release: make(chan struct{})} - p := precopyProvider(t, r, &parkView{stubView: v1View()}) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + entered, release := make(chan struct{}), make(chan struct{}) + var upload sync.Once + fixture.Blobs.PutHook = func(ctx context.Context) error { + upload.Do(func() { close(entered) }) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + } + p := precopyBProvider(t, fixture, &parkView{stubView: v1View()}, nil) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") if err != nil { @@ -38,7 +33,7 @@ func TestPrecopyRollingUploadReopensTentativeAdmission(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) var once sync.Once - unpark := func() { once.Do(func() { close(r.release) }) } + unpark := func() { once.Do(func() { close(release) }) } done := make(chan struct{}) var cutErr error t.Cleanup(func() { @@ -52,7 +47,7 @@ func TestPrecopyRollingUploadReopensTentativeAdmission(t *testing.T) { }) go func() { defer close(done); _, _, cutErr = p.DetachVolume(ctx, "v1") }() select { - case <-r.entered: + case <-entered: case <-ctx.Done(): t.Fatal("cold rolling cut never uploaded") } @@ -72,7 +67,7 @@ func TestPrecopyRollingUploadReopensTentativeAdmission(t *testing.T) { case <-ctx.Done(): t.Fatal("rolling rounds did not converge") } - if headBlock(t, r.MemChunkRemote, 80)[0] != 0x6d { + if layoutHeadBlock(t, fixture, 80)[0] != 0x6d { t.Fatal("later admitted write missing from final image") } } diff --git a/seaweed-block/core/frontend/durable/precopy_stop_boundary_test.go b/seaweed-block/core/frontend/durable/precopy_stop_boundary_test.go index fbd8bb9a41..93580bc50e 100644 --- a/seaweed-block/core/frontend/durable/precopy_stop_boundary_test.go +++ b/seaweed-block/core/frontend/durable/precopy_stop_boundary_test.go @@ -7,11 +7,15 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) type stopBoundaryRemote struct { - storage.ChunkRemote + *chunkstore.LayoutRemote entered chan time.Time release chan struct{} } @@ -25,12 +29,28 @@ func (r *stopBoundaryRemote) CASHead(ctx context.Context, expected storage.Chunk return 0, ctx.Err() } } - return r.ChunkRemote.CASHead(ctx, expected, next) + return r.LayoutRemote.CASHead(ctx, expected, next) } func TestPrecopyStopIOReturnTimestampPrecedesFinalPublication(t *testing.T) { - r := &stopBoundaryRemote{ChunkRemote: storage.NewMemChunkRemote(), entered: make(chan time.Time, 1), release: make(chan struct{})} - p := precopyProvider(t, r, &parkView{stubView: v1View()}) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + r := &stopBoundaryRemote{entered: make(chan time.Time, 1), release: make(chan struct{})} + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkDetachPrecopy: true} + fixture.Configure(&cfg) + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.Catalog, fixture.Ref, me) + if err != nil { + return nil, err + } + r.LayoutRemote = inner + return r, nil + } + var err error + p, err := durable.NewDurableProvider(cfg, &parkView{stubView: v1View()}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") if err != nil { diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 8d7dea1957..eee9cca676 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -38,6 +38,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/storage/parallelwal" @@ -66,12 +67,12 @@ const ( // ImplWALStoreChunk is a walstore volume with an attached chunk layer: // an asynchronous remote copy of immutable chunks published by a HEAD // compare-and-swap. On disk it is a walstore file. Requires - // ProviderConfig.ChunkRemoteFor. Opt-in proof of concept. + // ProviderConfig.ChunkLayoutHeadFor and ChunkLayoutRemoteFor. ImplWALStoreChunk ImplName = "walstore-chunk" ) -// defaultChunkBlocks is 4 MiB chunks of 4 KiB blocks. -const defaultChunkBlocks = 1024 +// DefaultChunkBlocks is 4 MiB chunks of 4 KiB blocks. +const DefaultChunkBlocks = 1024 // ErrImplKindMismatch is returned by Open when the configured // selector does not match the on-disk superblock magic. Named so @@ -152,9 +153,10 @@ type ProviderConfig struct { // restart and prove real replay. Default false. WALRecoveryTestDisableFlusher bool - // ChunkRemoteFor returns the remote that holds volumeID's chunks and - // HEAD. Required for ImplWALStoreChunk, ignored otherwise. - ChunkRemoteFor func(volumeID string) (storage.ChunkRemote, error) + // ChunkLayoutHeadFor and ChunkLayoutRemoteFor select the content-named layout. + // The remote is constructed once, with the identity confirmed by Start. + ChunkLayoutHeadFor func(string) (layout.StartStore, error) + ChunkLayoutRemoteFor func(string, layout.HolderID) (storage.ChunkRemote, error) // ChunkBlocks is the number of blocks per chunk. Zero: 1024. ChunkBlocks uint32 // ChunkAttachCheck, if set, runs before every chunk layer attach, ahead @@ -323,7 +325,10 @@ type volHandle struct { startupEnded uint64 // recovery generation with a terminal startup outcome; guarded by p.mu runtimeFenced bool // the attached layer fenced after startup (HEAD has another owner); guarded by p.mu chunk storage.ChunkLayer // after RecoverVolume - chunkLineage chunkLineage // immutable authority captured by this attachment + layoutHolder layout.HolderID // successful Start identity; guarded by p.mu + layoutHead layout.HeadStore + layoutRemote storage.ChunkRemote // one runtime per attachment, including attach retries + chunkLineage chunkLineage // immutable authority captured by this attachment // Private until the owner commit succeeds; retained for attach retry. chunkPending storage.ChunkLayer // chunkDetach is set (under attachMu) when DetachVolume starts and @@ -403,8 +408,11 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura return nil, fmt.Errorf("durable: unknown impl %q (want auto (empty), %q, %q, %q, or %q)", cfg.Impl, ImplSmartWAL, ImplWALStore, ImplParallelWALStore, ImplWALStoreChunk) } - if cfg.Impl == ImplWALStoreChunk && cfg.ChunkRemoteFor == nil { - return nil, fmt.Errorf("durable: impl %q requires ProviderConfig.ChunkRemoteFor", ImplWALStoreChunk) + if (cfg.ChunkLayoutHeadFor == nil) != (cfg.ChunkLayoutRemoteFor == nil) { + return nil, errors.New("durable: both layout factories are required") + } + if cfg.Impl == ImplWALStoreChunk && cfg.ChunkLayoutHeadFor == nil { + return nil, fmt.Errorf("durable: impl %q requires the layout head and remote factories", ImplWALStoreChunk) } if cfg.ChunkCaptureInterval < 0 || cfg.ChunkCutTimeout < 0 || cfg.ChunkMaintenanceInterval < 0 || cfg.ChunkMaintenanceTimeout < 0 { return nil, fmt.Errorf("durable: chunk schedule durations must not be negative") @@ -424,7 +432,7 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura } } if cfg.ChunkBlocks == 0 { - cfg.ChunkBlocks = defaultChunkBlocks + cfg.ChunkBlocks = DefaultChunkBlocks } if cfg.BlockSize == 0 { cfg.BlockSize = 4096 @@ -848,10 +856,13 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) { if err != nil || p.cfg.Impl != ImplWALStoreChunk { return h, err } - if h.fresh, err = fileExists(chunkFreshMarker(path)); err != nil { - _ = h.storage.Close() - return nil, fmt.Errorf("durable: stat fresh marker: %w", err) + ws := h.storage.(*storage.WALStore) + _, fresh, ok := ws.LayoutIdentity() + if !ok { + _ = ws.Close() + return nil, errors.New("durable: legacy local root has no layout identity; recreate it") } + h.fresh = fresh return h, nil } // Existing storage ignores create geometry; admission precedes all fresh sidecars. @@ -865,13 +876,6 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) { if err := p.refuseCreateWithoutHeadroom(volumeID); err != nil { return nil, err } - if p.cfg.Impl == ImplWALStoreChunk { - // Durable before the volume file exists: a crash anywhere between - // here and the first successful attach leaves a fresh volume. - if err := writeChunkFreshMarker(path); err != nil { - return nil, err - } - } impl := p.cfg.Impl if impl == ImplAuto { impl = ImplWALStore @@ -963,7 +967,7 @@ func (p *DurableProvider) openExisting(volumeID, path string, impl ImplName) (*v // Zero (pre-G6 default) preserves strict checkpoint-driven // recycle. // Defer before Recover can publish a completed BASE away. - if impl == ImplWALStoreChunk && p.cfg.ChunkRemoteFor != nil { + if impl == ImplWALStoreChunk { ws.DeferBaseRetirementV3() } if p.cfg.WALRetentionLSNs > 0 { @@ -1015,9 +1019,15 @@ func (p *DurableProvider) createFresh(volumeID, path string, impl ImplName) (*vo if err != nil { return nil, fmt.Errorf("durable: CreateWALStore %s: %w", path, err) } + if impl == ImplWALStoreChunk { + if err := initializeLayoutRoot(ws); err != nil { + _ = ws.Close() + return nil, err + } + } // G6 §1.A α (see openExisting comment for semantics). // Defer before Recover can publish a completed BASE away. - if impl == ImplWALStoreChunk && p.cfg.ChunkRemoteFor != nil { + if impl == ImplWALStoreChunk { ws.DeferBaseRetirementV3() } if p.cfg.WALRetentionLSNs > 0 { @@ -1207,4 +1217,3 @@ func chunkSidecars(path string) ([]string, error) { // Compile-time check. var _ frontend.Provider = (*DurableProvider)(nil) - diff --git a/seaweed-block/core/frontend/durable/provider_assignment_test.go b/seaweed-block/core/frontend/durable/provider_assignment_test.go index baee18b66f..d700f1d858 100644 --- a/seaweed-block/core/frontend/durable/provider_assignment_test.go +++ b/seaweed-block/core/frontend/durable/provider_assignment_test.go @@ -8,8 +8,9 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) type arrivingAssignment struct { @@ -51,7 +52,7 @@ func TestRestoreWaitsForFirstAssignment(t *testing.T) { defer finishRecovery() done := make(chan error, 1) go func() { _, err := p.RecoverVolume(recoverCtx, "v1"); done <- err }() - <-v.seen // recovery inspected the assignment + <-v.seen // recovery inspected the assignment if err := <-done; err != nil { // local recovery settles before assignment can be applied t.Fatalf("first assignment did not converge: %v", err) } @@ -74,11 +75,12 @@ func TestRestoreWaitsForFirstAssignment(t *testing.T) { func chunkProviderForAssignment(t *testing.T, v frontend.ProjectionView) *durable.DurableProvider { t.Helper() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, - }, v) + } + testutil.NewLayoutFixture(t, "v1", 64, 4).Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v) if err != nil { t.Fatal(err) } @@ -90,14 +92,18 @@ func TestRestoreDeferredAssignmentWaitEndsOnDeadlineAndClose(t *testing.T) { for _, mode := range []string{"limit", "close"} { t.Run(mode, func(t *testing.T) { v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: 40 * time.Millisecond, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { - t.Error("remote reached without assignment") - return storage.NewMemChunkRemote(), nil - }, - }, v) + } + fixture := testutil.NewLayoutFixture(t, "v1", 64, 4) + fixture.Configure(&cfg) + start := cfg.ChunkLayoutHeadFor + cfg.ChunkLayoutHeadFor = func(name string) (layout.StartStore, error) { + t.Error("layout reached without assignment") + return start(name) + } + p, err := durable.NewDurableProvider(cfg, v) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider_auto_chunk_test.go b/seaweed-block/core/frontend/durable/provider_auto_chunk_test.go index 4c0286cb34..73aff5ab78 100644 --- a/seaweed-block/core/frontend/durable/provider_auto_chunk_test.go +++ b/seaweed-block/core/frontend/durable/provider_auto_chunk_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -18,11 +19,11 @@ import ( // serve the local, absent extent). It refuses, and the explicit // walstore-chunk selector with the remote still reads the exact bytes. func TestDurableProvider_AutoRefusesLazyChunkRoot(t *testing.T) { - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) view := v1View() // Host A publishes a nonzero block. - hostA := chunkProvider(t, t.TempDir(), remote, view, 0) + hostA := layoutChunkProvider(t, t.TempDir(), fixture, view, 0) sA := openRecovered(t, hostA) if _, err := sA.Write(33, block(0x33)); err != nil { t.Fatal(err) @@ -33,7 +34,7 @@ func TestDurableProvider_AutoRefusesLazyChunkRoot(t *testing.T) { // Host B attaches lazily from HEAD and closes before LBA 33 is fetched. rootB := t.TempDir() - hostB := chunkProvider(t, rootB, remote, view, 0) + hostB := layoutChunkProvider(t, rootB, fixture, viewAs("rB", 4), 0) openRecovered(t, hostB) if err := hostB.Close(); err != nil { t.Fatalf("close host B: %v", err) @@ -55,7 +56,7 @@ func TestDurableProvider_AutoRefusesLazyChunkRoot(t *testing.T) { _ = auto.Close() // The explicit selector with the remote reopens and reads HEAD's bytes. - explicit := chunkProvider(t, rootB, remote, view, 0) + explicit := layoutChunkProvider(t, rootB, fixture, viewAs("rB", 4), 0) s := openRecovered(t, explicit) if got, err := s.Read(33); err != nil || !bytes.Equal(got, block(0x33)) { t.Fatalf("explicit walstore-chunk reopen read: %v", err) diff --git a/seaweed-block/core/frontend/durable/provider_auto_impl_test.go b/seaweed-block/core/frontend/durable/provider_auto_impl_test.go index 0d60aa8a75..5d2e3112af 100644 --- a/seaweed-block/core/frontend/durable/provider_auto_impl_test.go +++ b/seaweed-block/core/frontend/durable/provider_auto_impl_test.go @@ -71,6 +71,11 @@ func TestDurableProvider_AutoCreatesWALStore(t *testing.T) { if got := statusImpl(t, p); got != string(durable.ImplWALStore) { t.Fatalf("status impl=%q, want walstore", got) } + // Windows keeps the active WALStore file locked; inspect its magic after + // the provider has released the descriptor, as a restart would. + if err := p.Close(); err != nil { + t.Fatal(err) + } if got := onDiskMagic(t, filepath.Join(root, "v1.bin")); got != "SWBK" { t.Fatalf("on-disk magic=%q, want SWBK (walstore)", got) } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index fe0d46cbab..b89e091c0f 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -8,14 +8,13 @@ import ( "fmt" "log" "math/rand/v2" - "os" - "path/filepath" - "runtime" "strings" "sync" "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -125,12 +124,27 @@ func (p *DurableProvider) recoverChunk(ctx context.Context, volumeID string, h * p.startChunkAuthorityWait(volumeID, h, gen) return false, nil } - if errors.Is(err, storage.ErrChunkLayerFenced) && (!errors.Is(err, ErrChunkStaleLocalRoot) || errors.Is(err, errChunkForeignClaim)) { + if (errors.Is(err, storage.ErrChunkLayerFenced) && + (!errors.Is(err, ErrChunkStaleLocalRoot) || errors.Is(err, errChunkForeignClaim))) || + finalLayoutStartRefusal(err) { p.endChunkStartup(h, gen, err) } return err == nil, err } +// finalLayoutStartRefusal distinguishes a store's definite Start refusal +// from an unavailable read or a conditional-write race that may be retried. +// A detached HEAD has its separate replay-retained disposition below. +func finalLayoutStartRefusal(err error) bool { + return errors.Is(err, layout.ErrStaleLocalRoot) || errors.Is(err, layout.ErrMissingLocalRoot) || + errors.Is(err, layout.ErrGeometryMismatch) || errors.Is(err, layout.ErrHeadAbsent) || + errors.Is(err, layout.ErrVolumeDeleting) || errors.Is(err, layout.ErrStaleEpoch) || + errors.Is(err, layout.ErrNotHolder) || errors.Is(err, layout.ErrIdentity) || + errors.Is(err, layout.ErrCorrupt) || errors.Is(err, layout.ErrMalformed) || + errors.Is(err, layout.ErrMissing) || errors.Is(err, layout.ErrHeadTooLarge) || + errors.Is(err, chunkstore.ErrLegacyStore) +} + // startChunkAuthorityWait starts the authority wait of recovery gen, // registered with Close like a recovery. A wait of an earlier recovery // sees it is stale and exits on its own. @@ -268,7 +282,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen case errors.Is(err, errProviderClosed): ended = "provider closed" return - case errors.Is(err, storage.ErrChunkLayerDetached): + case errors.Is(err, storage.ErrChunkLayerDetached), errors.Is(err, layout.ErrDetached): // INV-WS-STARTUP-RETRY-001: an assigned sealed incarnation stays // non-serving for exact seal replay; restarting cannot unseal it. retained = true @@ -289,6 +303,16 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen p.endChunkStartup(h, gen, err) } return + case finalLayoutStartRefusal(err): + ended = "layout Start refused, not serving" + log.Printf("durable: chunk layer for volume=%s: %v (final refusal)", volumeID, err) + h.attachMu.Lock() + if p.current(h, gen) && h.chunk == nil { + h.backend.SetOperational(false, "chunk layer attach refused: "+err.Error()) + p.endChunkStartup(h, gen, err) + } + h.attachMu.Unlock() + return case errors.Is(err, errChunkNoAuthority): log.Printf("durable: chunk layer attach for volume=%s: authority lost before attempt %d (projection lacks %s); waiting", volumeID, attempts, chunkAuthorityGap(p.view.Projection(), volumeID)) @@ -341,12 +365,7 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v } // The owner commit is serialized with a later BASE begin. The callback // does marker I/O only: no store/layer reentry while installMu is held. - commit := func() error { - if h.fresh { - return removeChunkFreshMarker(h.path) - } - return nil - } + commit := func() error { return nil } if h.fresh { if hook := p.testBeforeChunkFreshRetire; hook != nil { if err := hook(); err != nil { @@ -361,6 +380,11 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v } else if err := commit(); err != nil { return err } + ws := h.storage.(*storage.WALStore) + id, _, _ := ws.LayoutIdentity() + if err := ws.SetLayoutIdentity(id, false); err != nil { + return err + } // RULE-FRESH-KNOWN-ZERO order: the marker is retired (above), THEN the // marking is made durable, THEN the volume serves (after this attach). if h.fresh { @@ -444,12 +468,36 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h return nil, fmt.Errorf("durable: chunk attach check for %s: %w", volumeID, err) } } - inner, err := p.cfg.ChunkRemoteFor(volumeID) + lin := chunkLineage{volumeID: proj.VolumeID, replicaID: proj.ReplicaID, epoch: proj.Epoch, endpoint: proj.EndpointVersion} + holder := p.chunkHolder(proj) + var inner storage.ChunkRemote + var layoutHead layout.Head + var err error + st, e := p.cfg.ChunkLayoutHeadFor(volumeID) + if e != nil { + return nil, e + } + layoutHead, err = startLayoutRoot(ctx, ws, st, layout.HolderID{Epoch: proj.Epoch, Holder: holder}) + if err != nil { + return nil, err + } + me := layout.HolderID{Epoch: layoutHead.Epoch, Holder: layoutHead.Holder, ClaimID: layoutHead.ClaimID} + p.mu.Lock() + if h.layoutHolder == me { + inner = h.layoutRemote + } + p.mu.Unlock() + if inner == nil { + inner, err = p.cfg.ChunkLayoutRemoteFor(volumeID, me) + } + if err == nil { + p.mu.Lock() + h.layoutHolder, h.layoutHead, h.layoutRemote = me, st, inner + p.mu.Unlock() + } if err != nil { return nil, fmt.Errorf("durable: chunk remote for %s: %w", volumeID, err) } - lin := chunkLineage{volumeID: proj.VolumeID, replicaID: proj.ReplicaID, epoch: proj.Epoch, endpoint: proj.EndpointVersion} - holder := p.chunkHolder(proj) bound := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx} if pace, ok := p.cfg.ChunkBudget.(interface { WaitUpload(context.Context, int) error @@ -458,10 +506,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h } bound.setAttach(ctx) // the attach's calls also end with the caller's ctx defer bound.setAttach(nil) - var remote storage.ChunkRemote = bound - if builder, ok := inner.(storage.ChunkManifestBuilder); ok { - remote = &manifestBoundRemote{closeBoundRemote: bound, builder: builder} + keyer, ok := inner.(storage.ChunkKeyer) + if !ok { + return nil, errors.New("durable: layout remote lacks content keys") } + var remote storage.ChunkRemote = &layoutBoundRemote{closeBoundRemote: bound, keyer: keyer} cfg := storage.ChunkLayerConfig{ OnPublishSettled: p.publishSettledHook(volumeID), ChunkBlocks: p.cfg.ChunkBlocks, @@ -491,105 +540,27 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h return nil }, } - if !h.fresh { - // An existing local volume is this holder's image only while HEAD is - // still this holder's publication (INV-WS-STALE-LOCAL-ROOT-001). - // Check again on the exact claim image before its CAS. Another holder means the - // workspace moved away and back: refuse rather than serve, or cut - // over, the newer image with the stale one. - head, err := remote.GetHead(ctx) + if p.cfg.ChunkLayoutHeadFor != nil { + // The kernel already claimed and validated this root. Seed only a fresh + // root; an existing root keeps its acknowledged WAL and synced position. + path, err := canStartFrom(ws, h.fresh, layoutHead) if err != nil { - return nil, fmt.Errorf("durable: read HEAD before attaching existing volume %s: %w", volumeID, err) - } - cfg.PrepareRestore = func(head storage.ChunkHead) error { - if head.Gen != 0 && head.Holder != holder { - err := fmt.Errorf("%w: %w: volume %s local root %s, HEAD holder %q gen %d epoch %d, local holder %q; remove or quarantine the local root to attach fresh from HEAD", - ErrChunkStaleLocalRoot, storage.ErrChunkLayerFenced, volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder) - // INV-WS-STARTUP-RETRY-001: at or above this assignment, - // the foreign holder is a supersede proof. A lower epoch is - // the existing move-back/stale-root diagnostic, never 78. - if claimHeadSupersedes(head, cfg) { - err = fmt.Errorf("%w: %w", err, errChunkForeignClaim) - } - log.Printf("durable: refusing to attach volume=%s root=%s: HEAD holder=%q gen=%d epoch=%d is not this holder %q (remove or quarantine the local root)", - volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder) - return err - } - // The durable-reopen rule: HEAD names this holder, but a root whose local - // durable LSN is below HEAD's remote_lsn is a rolled-back copy - // (a backup taken before a later cut). Restarting cannot cure it. - // A crash cannot cause it: a cut syncs its LSN locally before the - // HEAD CAS publishes it (storage chunkLayer capture: the barrier - // syncWithPhases result is next.RemoteLSN). - if durableLSN, _, _ := ws.Boundaries(); head.Gen != 0 && durableLSN < head.RemoteLSN { - log.Printf("durable: refusing to attach volume=%s root=%s: local durable LSN %d is below HEAD gen=%d remote_lsn=%d (remove or quarantine the local root)", - volumeID, h.path, durableLSN, head.Gen, head.RemoteLSN) - return fmt.Errorf("%w: %w: %w: volume %s local root %s, local durable LSN %d below HEAD gen %d remote_lsn %d; remove or quarantine the local root to attach fresh from HEAD", - ErrChunkStaleLocalRoot, storage.ErrChunkLayerFenced, errChunkForeignClaim, volumeID, h.path, durableLSN, head.Gen, head.RemoteLSN) - } - return nil - } - if err := cfg.PrepareRestore(head); err != nil { return nil, err } - } - if h.fresh { - // Attach preparation is gated. Seed the exact observed HEAD before - // its takeover CAS; only then finalize lazy attachment and expose I/O. - cfg.PrepareRestore = func(head storage.ChunkHead) error { - log.Printf("durable: HEAD claim for volume=%s observed HEAD gen=%d epoch=%d holder=%q state=%v remote_lsn=%d; preparing", - volumeID, head.Gen, head.Epoch, head.Holder, head.State, head.RemoteLSN) - if baseLSN, complete := ws.InstalledBaseLSN(); complete { - // The fresh marker can outlive a full local BASE. It is not - // permission to seed backwards or to fill from an older HEAD. - if head.RemoteLSN > baseLSN { - return fmt.Errorf("durable: completed BASE frontier %d is behind HEAD %d", baseLSN, head.RemoteLSN) - } - cfg.FreshFromHead = false - return nil + switch path { + case startAttachBase: + cfg.FreshFromHead = false + case startSeed: + if err := h.backend.seedAndRebase(func() error { return ws.SeedChunkFrontier(layoutHead.Position) }); err != nil { + return nil, err } - // No HEAD is a new lineage; preserve any pre-assignment local - // writes instead of replacing their frontier with zero. - if head.Gen == 0 { - return nil - } - // EnsureVolume's initial ZERO HEAD is not a remote data image. - // A local frontier already advanced before assignment belongs to - // this bootstrap: retain its extent bytes and unknown dirty set, - // rather than seeding backwards or installing lazy absence. - if head.RemoteLSN == 0 && len(head.Chunks) == 0 && head.State != storage.ChunkHeadDetached && head.DetachedBy == nil && ws.NextLSN() > 1 { - cfg.FreshFromHead = false - return nil - } - // Every component that cached the next LSN learns the seeded - // one before the takeover CAS and before the volume serves I/O, - // serialized with observer installs. A refused rebase fails the - // restore here, so HEAD is never claimed for a mis-ordered ship. - return h.backend.seedAndRebase(func() error { return ws.SeedChunkFrontier(head.RemoteLSN) }) } } - // INV-WS-REOPEN-FENCE-001: local-root reopens claim too, without - // reseeding their acknowledged WAL or replacing it with remote absence. - claimStart := time.Now() - log.Printf("durable: HEAD claim for volume=%s starting: target epoch=%d holder=%q", volumeID, cfg.Epoch, cfg.Holder) - head, err := storage.ClaimChunkHead(ctx, remote, cfg) - if err != nil { - // INV-WS-STARTUP-RETRY-001: only the claim's exact foreign-holder - // proof permits no-retry; a higher epoch of our own holder retries. - if errors.Is(err, storage.ErrChunkLayerFenced) && claimHeadSupersedes(head, cfg) { - err = errors.Join(err, errChunkForeignClaim) - } - log.Printf("durable: HEAD claim for volume=%s failed after %s: %v", volumeID, time.Since(claimStart), err) - return nil, fmt.Errorf("durable: restore HEAD claim: %w", err) - } - log.Printf("durable: HEAD claim for volume=%s done in %s: gen=%d epoch=%d holder=%q", volumeID, time.Since(claimStart), head.Gen, head.Epoch, head.Holder) - cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch} - - layer, attachErr := storage.AttachChunkLayer(ws, remote, cfg) - if attachErr == nil { + layer, err := storage.AttachChunkLayer(ws, remote, cfg) + if err == nil { h.chunkLineage = lin } - return layer, attachErr + return layer, err } // closeBoundRemote ends every remote call when the provider closes, so a @@ -676,77 +647,15 @@ func (r *closeBoundRemote) Delete(ctx context.Context, key string) error { return r.ChunkRemote.Delete(c, key) } -func (r *closeBoundRemote) PutIntent(ctx context.Context, in storage.ChunkIntent) (string, error) { +func (r *closeBoundRemote) Begin(ctx context.Context) (string, error) { c, end := r.bind(ctx) defer end() - return r.ChunkRemote.PutIntent(c, in) + return r.ChunkRemote.Begin(c) } -func (r *closeBoundRemote) DeleteIntent(ctx context.Context, id string) error { - c, end := r.bind(ctx) - defer end() - return r.ChunkRemote.DeleteIntent(c, id) -} - -// DeleteSettledIntent is reserved for joined layer shutdown. Provider Close -// has already cancelled ordinary operations; a settled root can still be -// removed using the cleanup caller's bounded context. Unknown CAS roots never -// reach this method: the layer retains them until publication is settled. -func (r *closeBoundRemote) DeleteSettledIntent(ctx context.Context, id string) error { - return r.ChunkRemote.DeleteIntent(ctx, id) -} - -func (r *closeBoundRemote) ListIntents(ctx context.Context) ([]storage.ChunkIntent, error) { - c, end := r.bind(ctx) - defer end() - return r.ChunkRemote.ListIntents(c) -} - -// The fresh marker: .chunkfresh. - -func chunkFreshMarker(path string) string { return path + ".chunkfresh" } - -func writeChunkFreshMarker(path string) error { - m := chunkFreshMarker(path) - f, err := os.OpenFile(m, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644) - if err != nil { - return fmt.Errorf("durable: fresh marker: %w", err) - } - _, werr := f.WriteString("fresh\n") - serr := f.Sync() - cerr := f.Close() - if err := errors.Join(werr, serr, cerr); err != nil { - return fmt.Errorf("durable: fresh marker: %w", err) - } - return syncParentDir(m) -} - -func removeChunkFreshMarker(path string) error { - m := chunkFreshMarker(path) - if err := os.Remove(m); err != nil && !os.IsNotExist(err) { - return fmt.Errorf("durable: remove fresh marker: %w", err) - } - return syncParentDir(m) -} - -// syncParentDir makes a create or remove in path's directory durable. A -// directory cannot be fsynced on Windows; there it is a no-op (no Windows -// crash-durability claim). -func syncParentDir(path string) error { - if runtime.GOOS == "windows" { - return nil - } - d, err := os.Open(filepath.Dir(path)) - if err != nil { - return fmt.Errorf("durable: open directory: %w", err) - } - serr := d.Sync() - cerr := d.Close() - if err := errors.Join(serr, cerr); err != nil { - return fmt.Errorf("durable: fsync directory: %w", err) - } - return nil -} +// Abort never blocks; it is passed through even after Close (a cut left +// open is rolled back at the next HEAD read). +func (r *closeBoundRemote) Abort() { r.ChunkRemote.Abort() } // Cut scheduler constants (B9 W3 ruling). const ( @@ -1052,6 +961,11 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str if err != nil && ctx.Err() == nil { log.Printf("durable: maintenance volume=%s: %v", volumeID, err) } + // The holder's cleaning may be the first call to see HEAD move away + // (an idle volume runs no cut): its refusal latches the layer too. + if obs, ok := layer.(interface{ ObserveRemoteError(error) error }); ok && err != nil { + _ = obs.ObserveRemoteError(err) + } // Completion-relative reset coalesces all elapsed ticks; no catch-up queue. timer.Reset(interval) } @@ -1377,7 +1291,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // Log only after capture releases its barrier; at most five records. for _, a := range r.Precopy.Rounds { p := a.FixedParts - log.Printf("durable: pre-copy fixed spans volume=%s attempt=%d candidate_ms=%.3f window_setup_ms=%.3f publish_prepare_ms=%.3f manifest_ms=%.3f commit_state_ms=%.3f intent_cleanup_ms=%.3f non_payload_copy_ms=%.3f barrier_overage_ms=%.3f live_drain_ms=%.3f live_capture_lock_ms=%.3f live_sync_ms=%.3f live_candidate_ms=%.3f live_other_ms=%.3f live_sync_lifecycle_wait_ms=%.3f live_sync_store_wait_ms=%.3f live_sync_group_commit_ms=%.3f live_sync_completion_wait_ms=%.3f", volumeID, a.Attempt, float64(p.Candidate)/float64(time.Millisecond), float64(p.WindowSetup)/float64(time.Millisecond), float64(p.PublishPrepare)/float64(time.Millisecond), float64(p.Manifest)/float64(time.Millisecond), float64(p.CommitState)/float64(time.Millisecond), float64(p.IntentCleanup)/float64(time.Millisecond), float64(p.NonPayloadCopy)/float64(time.Millisecond), float64(a.BarrierOverage)/float64(time.Millisecond), float64(a.BarrierParts.Drain)/float64(time.Millisecond), float64(a.BarrierParts.StoreLock)/float64(time.Millisecond), float64(a.BarrierParts.DataSync)/float64(time.Millisecond), float64(a.BarrierParts.Candidate)/float64(time.Millisecond), float64(a.BarrierParts.Other)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.LifecycleWaitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.StoreWaitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.GroupCommitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.CompletionWaitNs)/float64(time.Millisecond)) + log.Printf("durable: pre-copy fixed spans volume=%s attempt=%d candidate_ms=%.3f window_setup_ms=%.3f publish_prepare_ms=%.3f manifest_ms=%.3f commit_state_ms=%.3f non_payload_copy_ms=%.3f barrier_overage_ms=%.3f live_drain_ms=%.3f live_capture_lock_ms=%.3f live_sync_ms=%.3f live_candidate_ms=%.3f live_other_ms=%.3f live_sync_lifecycle_wait_ms=%.3f live_sync_store_wait_ms=%.3f live_sync_group_commit_ms=%.3f live_sync_completion_wait_ms=%.3f", volumeID, a.Attempt, float64(p.Candidate)/float64(time.Millisecond), float64(p.WindowSetup)/float64(time.Millisecond), float64(p.PublishPrepare)/float64(time.Millisecond), float64(p.Manifest)/float64(time.Millisecond), float64(p.CommitState)/float64(time.Millisecond), float64(p.NonPayloadCopy)/float64(time.Millisecond), float64(a.BarrierOverage)/float64(time.Millisecond), float64(a.BarrierParts.Drain)/float64(time.Millisecond), float64(a.BarrierParts.StoreLock)/float64(time.Millisecond), float64(a.BarrierParts.DataSync)/float64(time.Millisecond), float64(a.BarrierParts.Candidate)/float64(time.Millisecond), float64(a.BarrierParts.Other)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.LifecycleWaitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.StoreWaitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.GroupCommitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.CompletionWaitNs)/float64(time.Millisecond)) log.Printf("durable: pre-copy attempt volume=%s attempt=%d drain_ms=%.3f barrier_ms=%.3f pause_ms=%.3f reason=%s tail=%d rate_samples=%d estimate_ms=%.3f frozen=%t fixed_ms=%.3f drain_cost_ms=%.3f store_lock_ms=%.3f local_sync_ms=%.3f head_cas_ms=%.3f readback_ms=%.3f map_persist_ms=%.3f other_fixed_ms=%.3f tail_ms=%.3f declared_freeze_ms=%.3f err=%s", volumeID, a.Attempt, float64(a.Drain)/float64(time.Millisecond), float64(a.Barrier)/float64(time.Millisecond), float64(a.Pause)/float64(time.Millisecond), a.Reason, a.TailBytes, a.RateSamples, float64(a.Estimate)/float64(time.Millisecond), a.Frozen, float64(a.Fixed)/float64(time.Millisecond), float64(a.FixedParts.Drain)/float64(time.Millisecond), float64(a.FixedParts.StoreLock)/float64(time.Millisecond), float64(a.FixedParts.DataSync)/float64(time.Millisecond), float64(a.FixedParts.HeadCAS)/float64(time.Millisecond), float64(a.FixedParts.HeadReadback)/float64(time.Millisecond), float64(a.FixedParts.MapPersist)/float64(time.Millisecond), float64(a.FixedParts.Other)/float64(time.Millisecond), float64(a.TailEstimate)/float64(time.Millisecond), float64(a.DeclaredFreeze)/float64(time.Millisecond), a.Error) } log.Printf("durable: pre-copy volume=%s attempts=%d measurement_rounds=%d samples_at_start=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.MeasurementRounds, r.Precopy.SamplesAtStart, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err) @@ -1455,7 +1369,19 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla dl, _ := sctx.Deadline() trace("settle", dl) } - how, dr, serr := layer.SettleDetach(sctx) + var how storage.DetachSettlement + var dr storage.ChunkCutResult + var serr error + if h.layoutHead != nil { + if remote, ok := h.layoutRemote.(layoutStopRemote); ok { + how, dr, serr = settleLayoutStop(sctx, remote, h.layoutHolder) + } else { + serr = errors.New("durable: layout remote cannot settle its open stop session") + } + } else { + how, dr, serr = layer.SettleDetach(sctx) + } + if precopy { attempts := countCAS() - casAtFreeze extra := uint64(0) @@ -1512,19 +1438,6 @@ func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer return fmt.Errorf("%w: %w", ErrDetachAborted, cause) } -// Preserve the optional manifest capability only when the inner remote has it; -// legacy in-memory/flat remotes keep their existing no-op cut behavior. -type manifestBoundRemote struct { - *closeBoundRemote - builder storage.ChunkManifestBuilder -} - -func (r *manifestBoundRemote) PrepareManifest(ctx context.Context, base, next storage.ChunkHead, chunkBytes uint64) (storage.ChunkHead, []string, error) { - c, end := r.bind(ctx) - defer end() - return r.builder.PrepareManifest(c, base, next, chunkBytes) -} - // publishSettledHook adapts ChunkOnPublishSettled to one volume's layer. func (p *DurableProvider) publishSettledHook(volumeID string) func(context.Context, storage.ChunkHead, storage.ChunkHead) { hook := p.cfg.ChunkOnPublishSettled @@ -1567,9 +1480,3 @@ func (w *cutWaitSlot) status(cutSeq uint64) CutScheduleStatus { } return st } - -// INV-WS-STARTUP-RETRY-001: a displaced lower-epoch claim fences this -// attempt, but cannot prove the assigned holder was superseded. -func claimHeadSupersedes(head storage.ChunkHead, cfg storage.ChunkLayerConfig) bool { - return head.Gen != 0 && head.Holder != "" && head.Holder != cfg.Holder && head.Epoch >= cfg.Epoch -} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_attach_check_test.go b/seaweed-block/core/frontend/durable/provider_chunk_attach_check_test.go index 6eaff3c17d..3fd58e61e3 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_attach_check_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_attach_check_test.go @@ -10,8 +10,9 @@ import ( "sync" "testing" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) // orderLog records the hook and the remote calls in the order they ran. @@ -32,32 +33,40 @@ func (l *orderLog) snapshot() []string { return append([]string(nil), l.ops...) } -type loggedRemote struct { - storage.ChunkRemote +type loggedStartStore struct { + layout.StartStore log *orderLog } -func (r loggedRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { - r.log.add("gethead") - return r.ChunkRemote.GetHead(ctx) +func (s loggedStartStore) ReadHead(ctx context.Context) (layout.Head, bool, error) { + s.log.add("readhead") + return s.StartStore.ReadHead(ctx) } -func (r loggedRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { - r.log.add("cas") - return r.ChunkRemote.CASHead(ctx, expected, next) +func (s loggedStartStore) UpdateHead(ctx context.Context, expected uint64, next layout.Head) error { + s.log.add("updatehead") + return s.StartStore.UpdateHead(ctx, expected, next) } -func checkedProvider(t *testing.T, remote storage.ChunkRemote, check func(context.Context, string, durable.ChunkGeometry) error) *durable.DurableProvider { +func checkedProvider(t *testing.T, fixture *testutil.LayoutFixture, log *orderLog, check func(context.Context, string, durable.ChunkGeometry) error) *durable.DurableProvider { t.Helper() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, ChunkAttachCheck: check, - }, v1View()) + } + fixture.Configure(&cfg) + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { + st, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + return nil, err + } + return loggedStartStore{StartStore: st, log: log}, nil + } + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatalf("NewDurableProvider: %v", err) } @@ -68,7 +77,7 @@ func checkedProvider(t *testing.T, remote storage.ChunkRemote, check func(contex func TestWALStoreChunk_AttachCheckRunsFirstWithLocalGeometry(t *testing.T) { log := &orderLog{} var got durable.ChunkGeometry - p := checkedProvider(t, loggedRemote{ChunkRemote: storage.NewMemChunkRemote(), log: log}, + p := checkedProvider(t, testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks), log, func(_ context.Context, vol string, g durable.ChunkGeometry) error { log.add("check:" + vol) got = g @@ -87,7 +96,7 @@ func TestWALStoreChunk_AttachCheckRunsFirstWithLocalGeometry(t *testing.T) { func TestWALStoreChunk_AttachCheckRefusalStopsAttach(t *testing.T) { refused := errors.New("geometry_mismatch") log := &orderLog{} - p := checkedProvider(t, loggedRemote{ChunkRemote: storage.NewMemChunkRemote(), log: log}, + p := checkedProvider(t, testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks), log, func(context.Context, string, durable.ChunkGeometry) error { return refused }) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_authority_log_test.go b/seaweed-block/core/frontend/durable/provider_chunk_authority_log_test.go index 025ddf0fd0..973428c730 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_authority_log_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_authority_log_test.go @@ -10,8 +10,9 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) type lockedLog struct { @@ -67,14 +68,22 @@ next: } // The deferred attach logs its wait (with the projection fields that -// fail), the first attach attempt, the HEAD claim and how the wait ended. -func TestChunkAuthorityWaitLogsTheWaitTheClaimAndTheEnd(t *testing.T) { +// fail), the first attach attempt and how the wait ended. B Start's HEAD +// claim is observed from the catalog rather than a legacy claim log line. +func TestChunkAuthorityWaitLogsTheWaitTheAttachAndTheEnd(t *testing.T) { logs := &lockedLog{} captureWriteLogs(t, logs) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} - p := chunkProviderForAssignment(t, v) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4} + fixture := testutil.NewLayoutFixture(t, "v1", 64, 4) + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -88,11 +97,12 @@ func TestChunkAuthorityWaitLogsTheWaitTheClaimAndTheEnd(t *testing.T) { inOrder(t, got, []string{"volume=v1 waits for master authority (up to 30s): projection lacks healthy=false epoch=0"}, []string{"volume=v1: master authority after", `replica="r1" epoch=3 endpoint=1`, "first attach attempt"}, - []string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`}, - []string{`HEAD claim for volume=v1 observed HEAD gen=0 epoch=0 holder=""`, "; preparing"}, - []string{"HEAD claim for volume=v1 done in ", `gen=1 epoch=3 holder="r1"`}, []string{"chunk authority wait for volume=v1 ended after", ": attached after 1 attempt(s)"}, ) + head, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found || head.Epoch != 3 || head.Holder != "r1" || head.ClaimID == "" { + t.Fatalf("B Start did not claim after the wait: %+v found=%v err=%v", head, found, err) + } if strings.Count(got, "first attach attempt") != 1 { t.Fatalf("first attach attempt logged more than once:\n%s", got) } @@ -110,11 +120,12 @@ func TestChunkAuthorityWaitLogsDeadlineAndClose(t *testing.T) { if mode == "close" { limit = time.Minute } - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: limit, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, - }, v) + } + testutil.NewLayoutFixture(t, "v1", 64, 4).Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v) if err != nil { t.Fatal(err) } @@ -149,22 +160,22 @@ func TestChunkAuthorityWaitLogsDeadlineAndClose(t *testing.T) { } } -// headFailRemote fails GetHead while fails > 0 (forever when < 0). -type headFailRemote struct { - *storage.MemChunkRemote +// headFailStartStore fails the layout HEAD read while fails > 0 (forever when < 0). +type headFailStartStore struct { + layout.StartStore fails atomic.Int32 } var errHeadRead = errors.New("injected HEAD read failure") -func (r *headFailRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { +func (r *headFailStartStore) ReadHead(ctx context.Context) (layout.Head, bool, error) { if n := r.fails.Load(); n != 0 { if n > 0 { r.fails.Add(-1) } - return storage.ChunkHead{}, errHeadRead + return layout.Head{}, false, errHeadRead } - return r.MemChunkRemote.GetHead(ctx) + return r.StartStore.ReadHead(ctx) } // A claim whose first HEAD read fails logs its start and its failure with @@ -175,16 +186,23 @@ func TestChunkAuthorityWaitLogsAFailedClaim(t *testing.T) { t.Run(mode, func(t *testing.T) { logs := &lockedLog{} captureWriteLogs(t, logs) - remote := &headFailRemote{MemChunkRemote: storage.NewMemChunkRemote()} - remote.fails.Store(1) + fixture := testutil.NewLayoutFixture(t, "v1", 64, 4) + st, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + t.Fatal(err) + } + store := &headFailStartStore{StartStore: st} + store.fails.Store(1) if mode != "retried" { - remote.fails.Store(-1) + store.fails.Store(-1) } v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v) + } + fixture.Configure(&cfg) + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return store, nil } + p, err := durable.NewDurableProvider(cfg, v) if err != nil { t.Fatal(err) } @@ -201,14 +219,13 @@ func TestChunkAuthorityWaitLogsAFailedClaim(t *testing.T) { if mode == "retried" { got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after") inOrder(t, got, - []string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`}, - []string{"HEAD claim for volume=v1 failed after ", errHeadRead.Error()}, - []string{"chunk layer attach for volume=v1:", "(retrying)"}, - []string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`}, - []string{"HEAD claim for volume=v1 observed HEAD gen=0"}, - []string{"HEAD claim for volume=v1 done in "}, + []string{"chunk layer attach for volume=v1:", errHeadRead.Error(), "(retrying)"}, []string{"chunk authority wait for volume=v1 ended after", ": attached after 2 attempt(s)"}, ) + head, found, err := fixture.Catalog.ReadHead(context.Background(), fixture.Ref) + if err != nil || !found || head.Epoch != 3 || head.Holder != "r1" { + t.Fatalf("retry did not claim B HEAD: %+v found=%v err=%v", head, found, err) + } return } waitLog(t, logs, "(retrying)") @@ -217,7 +234,7 @@ func TestChunkAuthorityWaitLogsAFailedClaim(t *testing.T) { } got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after") inOrder(t, got, - []string{"HEAD claim for volume=v1 failed after ", errHeadRead.Error()}, + []string{"chunk layer attach for volume=v1:", errHeadRead.Error(), "(retrying)"}, []string{"chunk authority wait for volume=v1 ended after", ": provider closed during the retry backoff"}, ) }) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_burst_test.go b/seaweed-block/core/frontend/durable/provider_chunk_burst_test.go index 903d2242a8..f95058ea77 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_burst_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_burst_test.go @@ -5,8 +5,8 @@ import ( "context" "encoding/binary" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" - "github.com/seaweedfs/seaweed-block/core/storage" "testing" "time" ) @@ -18,12 +18,13 @@ func TestWALStoreChunkV3_SequentialBurstFlush(t *testing.T) { const transfer = 128 * 1024 const flushEvery = 48 * 1024 * 1024 ctx := context.Background() - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", total/4096, 1024) + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: total / 4096, ChunkBlocks: 1024, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider_chunk_control_test.go b/seaweed-block/core/frontend/durable/provider_chunk_control_test.go index 9bd11e8e2d..bdf1aecb48 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_control_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_control_test.go @@ -10,23 +10,25 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) func TestWALStoreChunk_CutVolumeReturnsInstalledHead(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := layoutChunkProvider(t, t.TempDir(), fixture, v1View(), 0) s := openRecovered(t, p) - claimed := freshV1Claim(t, remote) + claimed := layoutHead(t, fixture) if _, err := s.Write(1, block(1)); err != nil { t.Fatal(err) } r, err := p.CutVolume(ctx, "v1", 0) - head, _ := remote.GetHead(ctx) + head := layoutHead(t, fixture) // (r.Stats is W3's: its fields read zero until then.) - if err != nil || r.Noop || head.Gen != claimed.Gen+1 || r.Head.Gen != head.Gen || r.H != s.NextLSN()-1 || r.Head.RemoteLSN != r.H { + if err != nil || r.Noop || head.Gen <= claimed.Gen || r.Head.Gen != head.Gen || r.H != s.NextLSN()-1 || head.Position != r.H || r.Head.RemoteLSN != r.H { t.Fatalf("cut: %+v %v; remote HEAD gen %d", r, err, head.Gen) } again, err := p.CutVolume(ctx, "v1", 0) @@ -40,8 +42,8 @@ func TestWALStoreChunk_CutVolumeReturnsInstalledHead(t *testing.T) { func TestWALStoreChunk_DetachVolumeStopsIOAndPublishesDetached(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - p := chunkProvider(t, t.TempDir(), remote, v1View(), time.Hour) // a periodic loop runs until the detach + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := layoutChunkProvider(t, t.TempDir(), fixture, v1View(), time.Hour) // a periodic loop runs until the detach s := openRecovered(t, p) b, err := p.Open(ctx, "v1") if err != nil { @@ -51,12 +53,12 @@ func TestWALStoreChunk_DetachVolumeStopsIOAndPublishesDetached(t *testing.T) { t.Fatal(err) } r, last, err := p.DetachVolume(ctx, "v1") - head, _ := remote.GetHead(ctx) - if err != nil || r.Head.State != storage.ChunkHeadDetached || head.State != storage.ChunkHeadDetached || r.Head.Gen != head.Gen || + head := layoutHead(t, fixture) + if err != nil || r.Head.State != storage.ChunkHeadDetached || head.State != layout.StateDetached || r.Head.Gen != head.Gen || r.H != s.NextLSN()-1 || last != r.H { t.Fatalf("detach: %+v last %d %v; remote HEAD %+v", r, last, err, head) } - if !bytesEqual(headBlock(t, remote, 1), block(2)) { + if !bytesEqual(layoutHeadBlock(t, fixture, 1), block(2)) { t.Fatal("the detached HEAD lacks the write acknowledged before the detach") } if _, err := b.Write(ctx, 4096, block(3)); err == nil { diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go index ee42037329..46a65126d2 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go @@ -17,13 +17,17 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) // faultRemote injects one fault into the next detach's remote calls. type faultRemote struct { - *storage.MemChunkRemote + *chunkstore.LayoutRemote + fixture *testutil.LayoutFixture mu sync.Mutex putErr error // returned by every Put while set casMode string // "", "precondition", "lost" (not applied, error), "applied-lost" (applied, error), "hold", "hold-detach" @@ -145,18 +149,27 @@ func (r *faultRemote) Put(ctx context.Context, key string, data []byte) error { if err != nil { return err } - return r.MemChunkRemote.Put(ctx, key, data) + return r.LayoutRemote.Put(ctx, key, data) } func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { r.mu.Lock() - hold := r.getHeadHold err := r.getHeadErr if err == nil && r.getHeadFail > 0 { r.getHeadFail-- err = errInjected } r.mu.Unlock() + if err != nil { + return storage.ChunkHead{}, err + } + return r.LayoutRemote.GetHead(ctx) +} + +func (r *faultRemote) AbortOpenSession(ctx context.Context) (string, error) { + r.mu.Lock() + hold, err := r.getHeadHold, r.getHeadErr + r.mu.Unlock() if hold { var mine bool r.set(func(r *faultRemote) { @@ -169,12 +182,12 @@ func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { ended := time.Now() r.set(func(r *faultRemote) { r.heldRead.ended, r.heldRead.cause = ended, context.Cause(ctx) }) } - return storage.ChunkHead{}, ctx.Err() + return "", ctx.Err() } if err != nil { - return storage.ChunkHead{}, err + return "", err } - return r.MemChunkRemote.GetHead(ctx) + return r.LayoutRemote.AbortOpenSession(ctx) } func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { @@ -209,25 +222,40 @@ func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer r.mu.Unlock() go func() { <-release - _, err := r.MemChunkRemote.CASHead(context.Background(), expected, next) + _, err := r.LayoutRemote.CASHead(context.Background(), expected, next) out <- err }() return 0, errInjected case "applied-lost": - if _, err := r.MemChunkRemote.CASHead(ctx, expected, next); err != nil { + if _, err := r.LayoutRemote.CASHead(ctx, expected, next); err != nil { return 0, err } return 0, errInjected } - return r.MemChunkRemote.CASHead(ctx, expected, next) + return r.LayoutRemote.CASHead(ctx, expected, next) } // detachFixture: a chunk volume with one cut published and one more write // (dirty), so the detach's final cut has something to upload. func detachFixture(t *testing.T) (*faultRemote, *durable.DurableProvider, frontend.Backend) { t.Helper() - remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} - p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + remote := &faultRemote{fixture: fixture} + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks} + fixture.Configure(&cfg) + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.Catalog, fixture.Ref, me) + if err != nil { + return nil, err + } + remote.LayoutRemote = inner + return remote, nil + } + p, err := durable.NewDurableProvider(cfg, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") if err != nil { @@ -260,7 +288,7 @@ func assertServing(t *testing.T, p *durable.DurableProvider, b frontend.Backend, if r.Head.State == storage.ChunkHeadDetached { t.Fatal("HEAD is detached after a detach that was reported aborted") } - if !bytesEqual(headBlock(t, remote.MemChunkRemote, 2), block(2)) || !bytesEqual(headBlock(t, remote.MemChunkRemote, 3), block(3)) { + if !bytesEqual(layoutHeadBlock(t, remote.fixture, 2), block(2)) || !bytesEqual(layoutHeadBlock(t, remote.fixture, 3), block(3)) { t.Fatal("the cut after an aborted detach lost the dirty blocks") } } @@ -288,15 +316,15 @@ func TestWALStoreChunk_RefusedDetachCASResumes(t *testing.T) { // with a CAS at the same base, so it can never land, and serving resumes. func TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes(t *testing.T) { remote, p, b := detachFixture(t) - base, _ := remote.MemChunkRemote.GetHead(context.Background()) + base := layoutHead(t, remote.fixture) remote.set(func(r *faultRemote) { r.casMode = "lost" }) if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { t.Fatalf("detach with a lost, unapplied CAS: %v; want ErrDetachAborted after the cancel", err) } - // The cancel is a real CAS at the detach's base: HEAD moved one generation - // and is not detached, so the lost detach CAS can never land afterwards. - if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached || head.Gen != base.Gen+1 { - t.Fatalf("HEAD after the cancel: gen %d state %q; want gen %d, not detached", head.Gen, head.State, base.Gen+1) + // B aborts its open session before serving resumes, so the lost detach + // commit can no longer land; the HEAD remains live. + if head := layoutHead(t, remote.fixture); head.State == layout.StateDetached || head.Gen < base.Gen { + t.Fatalf("HEAD after the abort: gen %d state %q; want live at or after gen %d", head.Gen, head.State, base.Gen) } assertServing(t, p, b, remote) } @@ -365,16 +393,26 @@ func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) { // returns the cut witness's verdict when that sample proved nothing. func detachFreezeAttempt(t *testing.T) error { const freeze = 2 * time.Second - remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + remote := &faultRemote{fixture: fixture} + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, DetachFreezeTimeout: freeze, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) + } + fixture.Configure(&cfg) + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.Catalog, fixture.Ref, me) + if err != nil { + return nil, err + } + remote.LayoutRemote = inner + return remote, nil + } + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } @@ -489,13 +527,14 @@ func TestHeldWitnessVerdict(t *testing.T) { func TestWALStoreChunk_DetachAgainstNewerEpochStaysStopped(t *testing.T) { remote, p, b := detachFixture(t) ctx := context.Background() - cur, err := remote.MemChunkRemote.GetHead(ctx) + cur := layoutHead(t, remote.fixture) + newer := cur + newer.Epoch, newer.Holder, newer.ClaimID = cur.Epoch+1, "another-holder", "foreign-claim" + st, err := remote.fixture.Catalog.Store(remote.fixture.Ref) if err != nil { t.Fatal(err) } - newer := cur - newer.Epoch, newer.Holder = cur.Epoch+1, "another-holder" - if _, err := remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil { + if err := st.UpdateHead(ctx, cur.Gen, newer); err != nil { t.Fatal(err) } if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) || errors.Is(err, durable.ErrDetachAborted) { @@ -564,12 +603,22 @@ func TestWALStoreChunk_DetachFreezeBoundCoversTheSettle(t *testing.T) { func settleBoundAttempt(t *testing.T) error { const freeze = 2 * time.Second - remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + remote := &faultRemote{fixture: fixture} + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, DetachFreezeTimeout: freeze, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) + } + fixture.Configure(&cfg) + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.Catalog, fixture.Ref, me) + if err != nil { + return nil, err + } + remote.LayoutRemote = inner + return remote, nil + } + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } @@ -678,7 +727,7 @@ func TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel(t *testing.T) { if !errors.Is(derr, storage.ErrChunkHeadPrecondition) { t.Fatalf("the delayed detach CAS after the cancel: %v; want a precondition failure", derr) } - if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached { + if head := layoutHead(t, remote.fixture); head.State == layout.StateDetached { t.Fatal("the delayed detach CAS landed after the cancel") } assertServing(t, p, b, remote) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_bounds_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_bounds_test.go index 47b84bd716..3bfdf7abc8 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_bounds_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_bounds_test.go @@ -13,13 +13,14 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) func TestWALStoreChunk_TimedOutDetachRetriesShareOneDrain(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - p, view := parkedProvider(t, remote) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p, view := parkedLayoutProvider(t, fixture) openRecovered(t, p) b, err := p.Open(ctx, "v1") if err != nil { @@ -53,13 +54,13 @@ func TestWALStoreChunk_TimedOutDetachRetriesShareOneDrain(t *testing.T) { if err != nil || r.Head.State != storage.ChunkHeadDetached { t.Fatalf("detach once the write finished: %+v %v", r, err) } - if acked && !bytesEqual(headBlock(t, remote, 1), block(4)) { + if acked && !bytesEqual(layoutHeadBlock(t, fixture, 1), block(4)) { t.Fatal("the held write was acknowledged but is not in the detached HEAD") } } func TestWALStoreChunk_CutVolumeSurvivesCloseAfterResolve(t *testing.T) { - p := chunkProvider(t, t.TempDir(), storage.NewMemChunkRemote(), v1View(), 0) + p := layoutChunkProvider(t, t.TempDir(), testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks), v1View(), 0) s := openRecovered(t, p) if _, err := s.Write(1, block(1)); err != nil { t.Fatal(err) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_hook_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_hook_test.go index fff58df4c8..8a09ddedaf 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_hook_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_hook_test.go @@ -8,7 +8,10 @@ import ( "testing" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -44,18 +47,28 @@ func (k *detachHooks) calls() (started, resumed []string) { // block) with both detach hooks wired. func hookedProvider(t *testing.T) (*faultRemote, *durable.DurableProvider, frontend.Backend, *detachHooks) { t.Helper() - remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + remote := &faultRemote{fixture: fixture} k := &detachHooks{} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, OnChunkDetach: k.detach, OnChunkDetachResumed: k.resume, - }, v1View()) + } + fixture.Configure(&cfg) + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.Catalog, fixture.Ref, me) + if err != nil { + return nil, err + } + remote.LayoutRemote = inner + return remote, nil + } + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatalf("NewDurableProvider: %v", err) } @@ -179,13 +192,14 @@ func TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort(t *testing.T) { }) t.Run("fenced", func(t *testing.T) { remote, p, _, k := hookedProvider(t) - cur, err := remote.MemChunkRemote.GetHead(ctx) + cur := layoutHead(t, remote.fixture) + newer := cur + newer.Epoch, newer.Holder, newer.ClaimID = cur.Epoch+1, "another-holder", "foreign-claim" + st, err := remote.fixture.Catalog.Store(remote.fixture.Ref) if err != nil { t.Fatal(err) } - newer := cur - newer.Epoch, newer.Holder = cur.Epoch+1, "another-holder" - if _, err := remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil { + if err := st.UpdateHead(ctx, cur.Gen, newer); err != nil { t.Fatal(err) } if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) { diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go index d39b1bfe17..54ffc21ac0 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go @@ -7,6 +7,7 @@ package durable_test // a RecoverVolume, whether the detach succeeded or failed. import ( + "bytes" "context" "errors" "sync" @@ -14,7 +15,9 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -51,16 +54,23 @@ func (v *parkView) Projection() frontend.Projection { } func parkedProvider(t *testing.T, remote storage.ChunkRemote) (*durable.DurableProvider, *parkView) { + t.Helper() + _ = remote // Other legacy tests still using this helper migrate separately. + return parkedLayoutProvider(t, testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks)) +} + +func parkedLayoutProvider(t *testing.T, fixture *testutil.LayoutFixture) (*durable.DurableProvider, *parkView) { t.Helper() view := &parkView{stubView: v1View()} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplWALStoreChunk, - StorageRoot: t.TempDir(), - BlockSize: 4096, - NumBlocks: pcBlocks, - ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, view) + cfg := durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, + StorageRoot: t.TempDir(), + BlockSize: 4096, + NumBlocks: pcBlocks, + ChunkBlocks: pcChunkBlocks, + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatalf("NewDurableProvider: %v", err) } @@ -79,8 +89,8 @@ type detachOutcome struct { // detached HEAD. func TestWALStoreChunk_DetachDrainsAdmittedWrite(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - p, view := parkedProvider(t, remote) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p, view := parkedLayoutProvider(t, fixture) openRecovered(t, p) b, err := p.Open(ctx, "v1") if err != nil { @@ -110,7 +120,7 @@ func TestWALStoreChunk_DetachDrainsAdmittedWrite(t *testing.T) { if o.err != nil || o.r.Head.State != storage.ChunkHeadDetached { t.Fatalf("detach: %+v", o) } - if !bytesEqual(headBlock(t, remote, 1), block(7)) || !bytesEqual(headBlock(t, remote, 2), block(8)) { + if !bytes.Equal(layoutHeadBlock(t, fixture, 1), block(7)) || !bytes.Equal(layoutHeadBlock(t, fixture, 2), block(8)) { t.Fatal("a write acknowledged during the detach is not in the detached HEAD") } if _, err := b.Write(ctx, 4096, block(9)); err == nil { @@ -124,8 +134,8 @@ func TestWALStoreChunk_DetachDrainsAdmittedWrite(t *testing.T) { // write finishes, a retry detaches with every acknowledged write. func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - p, view := parkedProvider(t, remote) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p, view := parkedLayoutProvider(t, fixture) openRecovered(t, p) b, err := p.Open(ctx, "v1") if err != nil { @@ -143,7 +153,7 @@ func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { if !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, durable.ErrDetachAborted) { t.Fatalf("detach that cannot drain: %v; want an aborted detach on the context's deadline", err) } - if head, _ := remote.GetHead(ctx); head.State == storage.ChunkHeadDetached { + if head := layoutHead(t, fixture); head.State == layout.StateDetached { t.Fatalf("a detach that did not drain published a detached HEAD: %+v", head) } // Serving resumes: a new write is accepted. The drain still pending from @@ -193,10 +203,10 @@ func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { if o.err != nil || o.r.Head.State != storage.ChunkHeadDetached { t.Fatalf("detach retry: %+v", o) } - if acked && !bytesEqual(headBlock(t, remote, 1), block(5)) { + if acked && !bytes.Equal(layoutHeadBlock(t, fixture, 1), block(5)) { t.Fatal("the write admitted before the stop was acknowledged but is not in the detached HEAD") } - if !bytesEqual(headBlock(t, remote, 2), block(6)) { + if !bytes.Equal(layoutHeadBlock(t, fixture, 2), block(6)) { t.Fatal("the write accepted after the aborted detach is not in the detached HEAD") } } @@ -205,8 +215,8 @@ func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { // detach returns the first result. func TestWALStoreChunk_RecoveryKeepsDetachedVolumeStopped(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := layoutChunkProvider(t, t.TempDir(), fixture, v1View(), 0) openRecovered(t, p) b, err := p.Open(ctx, "v1") if err != nil { @@ -238,10 +248,10 @@ func TestWALStoreChunk_RecoveryKeepsDetachedVolumeStopped(t *testing.T) { // published; a reachable one cuts. func TestWALStoreChunk_CutVolumeRefusesUnwrittenMinLSNBeforePublishing(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := layoutChunkProvider(t, t.TempDir(), fixture, v1View(), 0) s := openRecovered(t, p) - claimed := freshV1Claim(t, remote) + claimed := layoutHead(t, fixture) if _, err := s.Write(1, block(1)); err != nil { t.Fatal(err) } @@ -249,11 +259,11 @@ func TestWALStoreChunk_CutVolumeRefusesUnwrittenMinLSNBeforePublishing(t *testin if _, err := p.CutVolume(ctx, "v1", last+1); err == nil { t.Fatal("a cut to an LSN never written succeeded") } - if head, _ := remote.GetHead(ctx); head.Gen != claimed.Gen || remote.Puts() != 0 { - t.Fatalf("a refused minLSN published: HEAD gen %d, %d chunks stored", head.Gen, remote.Puts()) + if head := layoutHead(t, fixture); head.Gen != claimed.Gen || fixture.Blobs.Puts() != 0 { + t.Fatalf("a refused minLSN published: HEAD gen %d, %d chunks stored", head.Gen, fixture.Blobs.Puts()) } r, err := p.CutVolume(ctx, "v1", last) - if err != nil || r.H != last || r.Head.Gen != claimed.Gen+1 { + if err != nil || r.H != last || r.Head.Gen <= claimed.Gen { t.Fatalf("cut to the last written LSN: %+v %v", r, err) } } diff --git a/seaweed-block/core/frontend/durable/provider_chunk_holder_test.go b/seaweed-block/core/frontend/durable/provider_chunk_holder_test.go index 505410df36..195729e9d5 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_holder_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_holder_test.go @@ -7,6 +7,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -16,17 +17,18 @@ import ( // ruling F2: the earlier surface is canonical). func TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) newHost := func(holder string) *durable.DurableProvider { - p, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplWALStoreChunk, - StorageRoot: t.TempDir(), - BlockSize: 4096, - NumBlocks: pcBlocks, - ChunkBlocks: pcChunkBlocks, - ChunkHolder: holder, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) + cfg := durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, + StorageRoot: t.TempDir(), + BlockSize: 4096, + NumBlocks: pcBlocks, + ChunkBlocks: pcChunkBlocks, + ChunkHolder: holder, + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } @@ -41,7 +43,10 @@ func TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced(t *testing.T) { if _, err := a.CaptureVolume(ctx, "v1"); err != nil { t.Fatal(err) } - head, _ := remote.GetHead(ctx) + head, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found { + t.Fatalf("layout HEAD: found=%v err=%v", found, err) + } b := newHost("s2/r1") if _, err := b.EnsureStorage("v1"); err != nil { @@ -50,7 +55,7 @@ func TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced(t *testing.T) { if _, err := b.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) { t.Fatalf("a second server with the same replica id at the same epoch: RecoverVolume %v; want fenced", err) } - if after, _ := remote.GetHead(ctx); after.Gen != head.Gen || after.Holder != "s1/r1" { + if after, _, _ := fixture.Catalog.ReadHead(ctx, fixture.Ref); after.Gen != head.Gen || after.Holder != "s1/r1" { t.Fatalf("HEAD after the second server's recovery: gen %d holder %q, want gen %d holder s1/r1", after.Gen, after.Holder, head.Gen) } be, err := b.Open(ctx, "v1") @@ -65,7 +70,7 @@ func TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced(t *testing.T) { if _, err := b.CaptureVolume(ctx, "v1"); err == nil { t.Fatal("a cut succeeded after refused recovery") } - if after, _ := remote.GetHead(ctx); after.Gen != head.Gen || after.Holder != head.Holder { + if after, _, _ := fixture.Catalog.ReadHead(ctx, fixture.Ref); after.Gen != head.Gen || after.Holder != head.Holder { t.Fatalf("refused cut changed HEAD: %+v", after) } } diff --git a/seaweed-block/core/frontend/durable/provider_chunk_lifetime_test.go b/seaweed-block/core/frontend/durable/provider_chunk_lifetime_test.go index 246d819d92..cc7c7374a4 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_lifetime_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_lifetime_test.go @@ -19,13 +19,18 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) // gatedRemote wraps a remote with failure and hold points. type gatedRemote struct { storage.ChunkRemote + layout.StartStore + fixture *testutil.LayoutFixture mu sync.Mutex failGetHead int // fail the next N GetHead calls @@ -80,6 +85,38 @@ func (g *gatedRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { return g.ChunkRemote.GetHead(ctx) } +// B Start reads HEAD through StartStore before constructing its content +// remote. Keep the same failure/hold schedule at that earlier seam. +func (g *gatedRemote) ReadHead(ctx context.Context) (layout.Head, bool, error) { + g.mu.Lock() + fail := g.failGetHead > 0 + if fail { + g.failGetHead-- + } + ch := g.holdGetHead + g.mu.Unlock() + if fail { + return layout.Head{}, false, errors.New("injected ReadHead failure") + } + var h layout.Head + var found bool + var err error + if g.holdAfter { + h, found, err = g.StartStore.ReadHead(ctx) + } + if err := g.hold(ctx, "gethead", ch); err != nil { + return layout.Head{}, false, err + } + if !g.holdAfter { + h, found, err = g.StartStore.ReadHead(ctx) + } + return h, found, err +} + +func (g *gatedRemote) ChunkKey(index uint64, sum [32]byte) string { + return g.ChunkRemote.(storage.ChunkKeyer).ChunkKey(index, sum) +} + func (g *gatedRemote) Put(ctx context.Context, key string, data []byte) error { g.mu.Lock() ch := g.holdPut @@ -127,12 +164,12 @@ func recvErr(t *testing.T, ch <-chan error, what string) error { } } -// seededRemote returns a remote whose HEAD publishes 0x33 at LBA 33 +// seededLayoutFixture returns a B HEAD that publishes 0x33 at LBA 33 // (chunk 2) and 0x64 at LBA 100 (chunk 6). -func seededRemote(t *testing.T) *storage.MemChunkRemote { +func seededLayoutFixture(t *testing.T) *testutil.LayoutFixture { t.Helper() - remote := storage.NewMemChunkRemote() - p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := layoutChunkProvider(t, t.TempDir(), fixture, v1View(), 0) s := openRecovered(t, p) for lba, fill := range map[uint32]byte{33: 0x33, 100: 0x64} { if _, err := s.Write(lba, block(fill)); err != nil { @@ -145,7 +182,79 @@ func seededRemote(t *testing.T) *storage.MemChunkRemote { if err := p.Close(); err != nil { t.Fatal(err) } - return remote + return fixture +} + +func nextSeededView() *stubView { + return newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) +} + +type gatedLayoutStartStore struct { + layout.StartStore + mu sync.Mutex + failRead int + holdRead chan struct{} + holdAfter bool + honourCtx bool + entered chan string + once sync.Once +} + +func (g *gatedLayoutStartStore) ReadHead(ctx context.Context) (layout.Head, bool, error) { + g.mu.Lock() + fail := g.failRead > 0 + if fail { + g.failRead-- + } + hold, after, honour := g.holdRead, g.holdAfter, g.honourCtx + g.mu.Unlock() + if fail { + return layout.Head{}, false, errors.New("injected ReadHead failure") + } + read := func() (layout.Head, bool, error) { return g.StartStore.ReadHead(ctx) } + var h layout.Head + var found bool + var err error + if after { + h, found, err = read() + } + if hold != nil { + g.entered <- "readhead" + if honour { + select { + case <-hold: + case <-ctx.Done(): + return layout.Head{}, false, ctx.Err() + } + } else { + <-hold + } + } + if !after { + h, found, err = read() + } + return h, found, err +} + +func (g *gatedLayoutStartStore) release() { + g.once.Do(func() { + if g.holdRead != nil { + close(g.holdRead) + } + }) +} + +func layoutGatedProvider(t *testing.T, root string, fixture *testutil.LayoutFixture, view *stubView, gated *gatedLayoutStartStore) *durable.DurableProvider { + t.Helper() + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks} + fixture.Configure(&cfg) + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return gated, nil } + p, err := durable.NewDurableProvider(cfg, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p } func readEq(t *testing.T, s storage.LogicalStorage, lba uint32, want []byte, what string) { @@ -162,11 +271,14 @@ func readEq(t *testing.T, s storage.LogicalStorage, lba uint32, want []byte, wha // A fresh volume whose first attach fails is still fresh after a normal // close and reopen: it reads HEAD, never the untouched local zeros. func TestWALStoreChunk_FailedFreshAttachThenReopenReadsHead(t *testing.T) { - remote := seededRemote(t) + fixture := seededLayoutFixture(t) root := t.TempDir() - g := newGated(remote) - g.failGetHead = 1 - p := chunkProvider(t, root, g, v1View(), 0) + store, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + t.Fatal(err) + } + g := &gatedLayoutStartStore{StartStore: store, failRead: 1} + p := layoutGatedProvider(t, root, fixture, nextSeededView(), g) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -176,7 +288,7 @@ func TestWALStoreChunk_FailedFreshAttachThenReopenReadsHead(t *testing.T) { if err := p.Close(); err != nil { t.Fatal(err) } - p2 := chunkProvider(t, root, remote, v1View(), 0) + p2 := layoutChunkProvider(t, root, fixture, nextSeededView(), 0) s := openRecovered(t, p2) readEq(t, s, 33, block(0x33), "reopen after a failed fresh attach") readEq(t, s, 100, block(0x64), "reopen after a failed fresh attach") @@ -184,16 +296,16 @@ func TestWALStoreChunk_FailedFreshAttachThenReopenReadsHead(t *testing.T) { // Interrupted before any attach: created, never recovered, closed. func TestWALStoreChunk_CreatedNeverAttachedThenReopenReadsHead(t *testing.T) { - remote := seededRemote(t) + fixture := seededLayoutFixture(t) root := t.TempDir() - p := chunkProvider(t, root, remote, v1View(), 0) + p := layoutChunkProvider(t, root, fixture, nextSeededView(), 0) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } if err := p.Close(); err != nil { t.Fatal(err) } - p2 := chunkProvider(t, root, remote, v1View(), 0) + p2 := layoutChunkProvider(t, root, fixture, nextSeededView(), 0) s := openRecovered(t, p2) readEq(t, s, 33, block(0x33), "reopen of a never-attached fresh volume") } @@ -202,9 +314,9 @@ func TestWALStoreChunk_CreatedNeverAttachedThenReopenReadsHead(t *testing.T) { // keeps its local writes over HEAD and still reads untouched chunks from // HEAD. func TestWALStoreChunk_FreshVolumeKeepsLocalWritesAfterRestart(t *testing.T) { - remote := seededRemote(t) + fixture := seededLayoutFixture(t) root := t.TempDir() - p := chunkProvider(t, root, remote, v1View(), 0) + p := layoutChunkProvider(t, root, fixture, nextSeededView(), 0) s := openRecovered(t, p) if _, err := s.Write(33, block(0x77)); err != nil { t.Fatal(err) @@ -215,7 +327,7 @@ func TestWALStoreChunk_FreshVolumeKeepsLocalWritesAfterRestart(t *testing.T) { if err := p.Close(); err != nil { t.Fatal(err) } - p2 := chunkProvider(t, root, remote, v1View(), 0) + p2 := layoutChunkProvider(t, root, fixture, nextSeededView(), 0) s2 := openRecovered(t, p2) readEq(t, s2, 33, block(0x77), "restart after a fresh attach") readEq(t, s2, 100, block(0x64), "restart after a fresh attach") @@ -233,11 +345,11 @@ func TestWALStoreChunk_LineageDriftRefusesCapture(t *testing.T) { } for name, drift := range cases { t.Run(name, func(t *testing.T) { - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) view := v1View() - p := chunkProvider(t, t.TempDir(), remote, view, 0) + p := layoutChunkProvider(t, t.TempDir(), fixture, view, 0) s := openRecovered(t, p) - claimed := freshV1Claim(t, remote) + claimed := layoutHead(t, fixture) if _, err := s.Write(1, block(1)); err != nil { t.Fatal(err) } @@ -247,18 +359,18 @@ func TestWALStoreChunk_LineageDriftRefusesCapture(t *testing.T) { view.set(proj) } _, err := p.CaptureVolume(context.Background(), "v1") - head, _ := remote.GetHead(context.Background()) + head := layoutHead(t, fixture) if drift == nil { - if err != nil || head.Gen != claimed.Gen+1 { - t.Fatalf("capture under the attach lineage: %v (HEAD gen %d)", err, head.Gen) + if err != nil || head.Current == nil || head.Position <= claimed.Position { + t.Fatalf("capture under the attach lineage: %v (HEAD %+v)", err, head) } return } if !errors.Is(err, storage.ErrChunkCaptureRefused) { t.Fatalf("capture after %s drift: %v; want refused", name, err) } - if head.Gen != claimed.Gen || remote.Puts() != 0 { - t.Fatalf("capture after %s drift published: HEAD gen %d, %d chunks stored", name, head.Gen, remote.Puts()) + if head.Current != nil || head.Position != claimed.Position || fixture.Blobs.Puts() != 0 { + t.Fatalf("capture after %s drift published: HEAD %+v, %d blobs stored", name, head, fixture.Blobs.Puts()) } }) } @@ -274,7 +386,7 @@ func TestWALStoreChunk_LineageDriftDuringHeldUploadRefusesPublication(t *testing view := v1View() p := chunkProvider(t, t.TempDir(), g, view, 0) s := openRecovered(t, p) - claimed := freshV1Claim(t, remote) + claimed := layoutHead(t, g.fixture) if _, err := s.Write(1, block(1)); err != nil { t.Fatal(err) } @@ -288,8 +400,8 @@ func TestWALStoreChunk_LineageDriftDuringHeldUploadRefusesPublication(t *testing if err := recvErr(t, errc, "CaptureVolume"); !errors.Is(err, storage.ErrChunkCaptureRefused) { t.Fatalf("capture whose lineage moved during upload: %v; want refused", err) } - if head, _ := remote.GetHead(context.Background()); head.Gen != claimed.Gen { - t.Fatalf("stale lineage published HEAD gen %d", head.Gen) + if head := layoutHead(t, g.fixture); head.Current != nil || head.Position != claimed.Position { + t.Fatalf("stale lineage published an image: %+v", head) } } @@ -494,9 +606,9 @@ func TestWALStoreChunk_LayerOutlivesRecoveryContext(t *testing.T) { // layer to epoch 0: once the projection carries the assignment, the // volume publishes under it. func TestWALStoreChunk_AttachWaitsForMasterAuthority(t *testing.T) { - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) // pre-assignment - p := chunkProvider(t, t.TempDir(), remote, view, 0) + p := layoutChunkProvider(t, t.TempDir(), fixture, view, 0) s, err := p.EnsureStorage("v1") if err != nil { t.Fatal(err) @@ -504,17 +616,14 @@ func TestWALStoreChunk_AttachWaitsForMasterAuthority(t *testing.T) { if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { t.Fatalf("RecoverVolume before assignment: %v", err) } - if _, err := s.Write(1, block(1)); err != nil { - t.Fatal(err) - } // Healthy but with no master-assigned epoch is not authority either. view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})) time.Sleep(150 * time.Millisecond) if _, err := p.CaptureVolume(context.Background(), "v1"); err == nil { t.Fatal("capture succeeded under a healthy projection with epoch 0") } - if head, _ := remote.GetHead(context.Background()); head.Gen != 0 { - t.Fatalf("published under epoch 0: HEAD gen %d epoch %d", head.Gen, head.Epoch) + if head := layoutHead(t, fixture); head.Epoch != 0 || head.Current != nil { + t.Fatalf("published under epoch 0: HEAD %+v", head) } view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) deadline := time.Now().Add(10 * time.Second) @@ -528,7 +637,13 @@ func TestWALStoreChunk_AttachWaitsForMasterAuthority(t *testing.T) { } time.Sleep(20 * time.Millisecond) } - if head, _ := remote.GetHead(context.Background()); head.Epoch != 4 { + if _, err := s.Write(1, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + if head := layoutHead(t, fixture); head.Epoch != 4 || head.Current == nil { t.Fatalf("HEAD epoch %d, want the assigned 4", head.Epoch) } } @@ -715,13 +830,15 @@ func TestCorruptWALWrite_NoncePayloadOverlap(t *testing.T) { func TestWALStoreChunk_StaleWaiterCannotOverrideFailedRecovery(t *testing.T) { root := t.TempDir() view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + seedPreviouslyServedRoot(t, root, fixture) + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, WALRecoveryTestDisableFlusher: true, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, view) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } @@ -734,9 +851,6 @@ func TestWALStoreChunk_StaleWaiterCannotOverrideFailedRecovery(t *testing.T) { if _, err := p.RecoverVolume(ctx, "v1"); err != nil { // A: ok, no authority t.Fatalf("recovery A: %v", err) } - if _, err := s.Write(5, block(0xA7)); err != nil { - t.Fatal(err) - } // This oracle requires corruption below a persisted W. Default mode C // intentionally permits losing its newest uncheckpointed batch instead. ws, ok := s.(*storage.WALStore) @@ -796,12 +910,15 @@ func TestWALStoreChunk_StaleWaiterCannotOverrideFailedRecovery(t *testing.T) { func TestWALStoreChunk_FailedRecoveryRetiresAuthorityWait(t *testing.T) { root := t.TempDir() view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + seedPreviouslyServedRoot(t, root, fixture) + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, WALRecoveryTestDisableFlusher: true, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, - }, view) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } @@ -817,9 +934,6 @@ func TestWALStoreChunk_FailedRecoveryRetiresAuthorityWait(t *testing.T) { if _, err := p.CaptureVolume(ctx, "v1"); errors.Is(err, durable.ErrNotChunkVolume) || err == nil { t.Fatalf("after recovery without authority: %v; want the volume awaiting authority", err) } - if _, err := s.Write(5, block(0xA7)); err != nil { - t.Fatal(err) - } // This oracle requires corruption below a persisted W. Default mode C // intentionally permits losing its newest uncheckpointed batch instead. ws, ok := s.(*storage.WALStore) @@ -883,13 +997,13 @@ func (v *parkingView) Projection() frontend.Projection { // countingRemote counts HEAD reads (an attach starts with one). type countingRemote struct { - storage.ChunkRemote + *chunkstore.LayoutRemote heads atomic.Int64 } func (c *countingRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { c.heads.Add(1) - return c.ChunkRemote.GetHead(ctx) + return c.LayoutRemote.GetHead(ctx) } // The window the per-tick check cannot cover: wait A has passed its tick @@ -898,13 +1012,24 @@ func (c *countingRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) func TestWALStoreChunk_StaleWaiterPastTickCheckCannotAttach(t *testing.T) { root := t.TempDir() view := &parkingView{stubView: newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"})} - remote := &countingRemote{ChunkRemote: storage.NewMemChunkRemote()} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + seedPreviouslyServedRoot(t, root, fixture) + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, WALRecoveryTestDisableFlusher: true, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, view) + } + fixture.Configure(&cfg) + remote := &countingRemote{} + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.Catalog, fixture.Ref, me) + if err != nil { + return nil, err + } + remote.LayoutRemote = inner + return remote, nil + } + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } @@ -917,9 +1042,6 @@ func TestWALStoreChunk_StaleWaiterPastTickCheckCannotAttach(t *testing.T) { if _, err := p.RecoverVolume(ctx, "v1"); err != nil { // A: ok, no authority t.Fatalf("recovery A: %v", err) } - if _, err := s.Write(5, block(0xA7)); err != nil { - t.Fatal(err) - } // This oracle requires corruption below a persisted W. Default mode C // intentionally permits losing its newest uncheckpointed batch instead. ws, ok := s.(*storage.WALStore) @@ -996,6 +1118,43 @@ func TestWALStoreChunk_StaleWaiterPastTickCheckCannotAttach(t *testing.T) { readEq(t, s, 5, block(0xA7), "repaired WAL record after convergence") } +// Recovery-race fixtures start from a real B root that previously served and +// acknowledged a write. Reopening it without authority then exercises the +// deferred-attach path without fabricating a fresh root's identity. +func seedPreviouslyServedRoot(t *testing.T, root string, fixture *testutil.LayoutFixture) { + t.Helper() + view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, WALRecoveryTestDisableFlusher: true} + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, view) + if err != nil { + t.Fatal(err) + } + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + ws, ok := s.(*storage.WALStore) + if !ok { + t.Fatalf("unexpected native store %T", s) + } + if err := ws.SetWMode(storage.WModeStrict); err != nil { + t.Fatal(err) + } + if _, err := s.Write(5, block(0xA7)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } +} + // captureWhenReconciled cuts once the volume's chunk layer has reconciled // its dirty set: a volume recovered with local writes reconciles first, // and a cut meanwhile is refused as retryable (ErrChunkReconciling). diff --git a/seaweed-block/core/frontend/durable/provider_chunk_moveback_test.go b/seaweed-block/core/frontend/durable/provider_chunk_moveback_test.go index 9ff6c8a33b..c00c6bcabd 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_moveback_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_moveback_test.go @@ -11,7 +11,9 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -41,14 +43,14 @@ func headHolder(t *testing.T, remote *storage.MemChunkRemote) storage.ChunkHead // movedAwayAndBack runs A (epoch 3) cut then uncut synced writes, A lost; // B (epoch 4, fresh) claims, writes LBA 0 = 0xB1, syncs, cuts, closes. It // returns the remote and A's surviving root. -func movedAwayAndBack(t *testing.T) (*storage.MemChunkRemote, string) { +func movedAwayAndBack(t *testing.T) (*testutil.LayoutFixture, string) { t.Helper() ctx := context.Background() - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) rootA, rootB := t.TempDir(), t.TempDir() // 1. A (epoch 3) cuts LBA 0 and LBA 16, then keeps writing without a cut. - pA := chunkProvider(t, rootA, remote, viewAs("rA", 3), 0) + pA := layoutChunkProvider(t, rootA, fixture, viewAs("rA", 3), 0) sA := openRecovered(t, pA) writeSync(t, sA, 0, 0xA1) writeSync(t, sA, 16, 0xA1) @@ -62,7 +64,7 @@ func movedAwayAndBack(t *testing.T) (*storage.MemChunkRemote, string) { // 2. A forced move to B (epoch 4, fresh root): B claims HEAD, writes, // syncs and cuts. - pB := chunkProvider(t, rootB, remote, viewAs("rB", 4), 0) + pB := layoutChunkProvider(t, rootB, fixture, viewAs("rB", 4), 0) sB := openRecovered(t, pB) writeSync(t, sB, 0, 0xB1) if _, err := pB.CaptureVolume(ctx, "v1"); err != nil { @@ -71,7 +73,7 @@ func movedAwayAndBack(t *testing.T) (*storage.MemChunkRemote, string) { if err := pB.Close(); err != nil { t.Fatal(err) } - return remote, rootA + return fixture, rootA } // A workspace moves A -> B -> A, and A's old durable root is still on disk. @@ -81,17 +83,17 @@ func movedAwayAndBack(t *testing.T) (*storage.MemChunkRemote, string) { // from HEAD and reads B's data. func TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused(t *testing.T) { ctx := context.Background() - remote, rootA := movedAwayAndBack(t) - before := headHolder(t, remote) + fixture, rootA := movedAwayAndBack(t) + before := layoutHead(t, fixture) // 3. Back to A (epoch 5) over its old root: refused. - pA2 := chunkProvider(t, rootA, remote, viewAs("rA", 5), 0) + pA2 := layoutChunkProvider(t, rootA, fixture, viewAs("rA", 5), 0) if _, err := pA2.EnsureStorage("v1"); err != nil { t.Fatal(err) } _, err := pA2.RecoverVolume(ctx, "v1") - if !errors.Is(err, durable.ErrChunkStaleLocalRoot) || !errors.Is(err, storage.ErrChunkLayerFenced) { - t.Fatalf("move back onto the old root: %v; want ErrChunkStaleLocalRoot (fenced)", err) + if !errors.Is(err, layout.ErrStaleLocalRoot) || !errors.Is(err, layout.ErrNotHolder) { + t.Fatalf("move back onto the old root: %v; want ErrStaleLocalRoot (fenced)", err) } b, err := pA2.Open(ctx, "v1") if err != nil { @@ -112,13 +114,13 @@ func TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused(t *testing.T) { evidence = st.Evidence } } - if !strings.Contains(evidence, "remove or quarantine the local root") || !strings.Contains(evidence, rootA) { + if !strings.Contains(evidence, layout.StaleLocalRootCure) { t.Errorf("status evidence %q does not tell the operator what to do with root %s", evidence, rootA) } - if after := headHolder(t, remote); after.Gen != before.Gen || after.Holder != before.Holder || after.Epoch != before.Epoch { + if after := layoutHead(t, fixture); after.Gen != before.Gen || after.Holder != before.Holder || after.Epoch != before.Epoch { t.Errorf("HEAD changed by a refused move back: %+v -> %+v", before, after) } - if h := headBlock(t, remote, 0); !bytes.Equal(h, block(0xB1)) { + if h := layoutHeadBlock(t, fixture, 0); !bytes.Equal(h, block(0xB1)) { t.Errorf("HEAD LBA 0 = %02x after a refused move back; want B's %02x", h[0], 0xB1) } if err := pA2.Close(); err != nil { @@ -136,7 +138,7 @@ func TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused(t *testing.T) { t.Fatal(err) } } - pA3 := chunkProvider(t, rootA, remote, viewAs("rA", 5), 0) + pA3 := layoutChunkProvider(t, rootA, fixture, viewAs("rA", 5), 0) sA3 := openRecovered(t, pA3) if got, err := sA3.Read(0); err != nil || !bytes.Equal(got, block(0xB1)) { t.Fatalf("fresh attach after removing the root: LBA 0 err %v; want B's %02x", err, 0xB1) @@ -150,9 +152,9 @@ func TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused(t *testing.T) { // back: it attaches, serves its data and cuts. func TestWALStoreChunk_SameHolderReattachAtNewerEpoch(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) root := t.TempDir() - p := chunkProvider(t, root, remote, viewAs("rA", 3), 0) + p := layoutChunkProvider(t, root, fixture, viewAs("rA", 3), 0) s := openRecovered(t, p) writeSync(t, s, 0, 0xC1) if _, err := p.CaptureVolume(ctx, "v1"); err != nil { @@ -162,7 +164,7 @@ func TestWALStoreChunk_SameHolderReattachAtNewerEpoch(t *testing.T) { if err := p.Close(); err != nil { t.Fatal(err) } - p2 := chunkProvider(t, root, remote, viewAs("rA", 4), 0) + p2 := layoutChunkProvider(t, root, fixture, viewAs("rA", 4), 0) s2 := openRecovered(t, p2) if got, _ := s2.Read(32); !bytes.Equal(got, block(0xC2)) { t.Fatal("same-holder reattach lost its local write") @@ -170,45 +172,24 @@ func TestWALStoreChunk_SameHolderReattachAtNewerEpoch(t *testing.T) { if _, err := p2.CaptureVolume(ctx, "v1"); err != nil { t.Fatalf("same-holder reattach cannot cut: %v", err) } - if !bytes.Equal(headBlock(t, remote, 32), block(0xC2)) { + if !bytes.Equal(layoutHeadBlock(t, fixture, 32), block(0xC2)) { t.Fatal("HEAD lacks the reattached holder's write") } } -// An existing root with no HEAD at all (generation 0) is this holder's own -// image: it attaches. -func TestWALStoreChunk_ExistingRootWithoutHeadAttaches(t *testing.T) { - root := t.TempDir() - p := chunkProvider(t, root, storage.NewMemChunkRemote(), viewAs("rA", 3), 0) - s := openRecovered(t, p) - writeSync(t, s, 0, 0xD1) - if err := p.Close(); err != nil { - t.Fatal(err) - } - empty := storage.NewMemChunkRemote() // no HEAD - if h := headHolder(t, empty); h.Gen != 0 { - t.Fatalf("empty remote HEAD gen %d", h.Gen) - } - p2 := chunkProvider(t, root, empty, viewAs("rA", 3), 0) - s2 := openRecovered(t, p2) - if got, _ := s2.Read(0); !bytes.Equal(got, block(0xD1)) { - t.Fatal("existing root without a HEAD lost its data") - } -} - // A holder whose HEAD a newer epoch has taken over never cuts over it. func TestWALStoreChunk_CutRefusedAfterANewerEpochTakesOver(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - pA := chunkProvider(t, t.TempDir(), remote, viewAs("rA", 3), 0) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + pA := layoutChunkProvider(t, t.TempDir(), fixture, viewAs("rA", 3), 0) sA := openRecovered(t, pA) writeSync(t, sA, 0, 0xE1) if _, err := pA.CaptureVolume(ctx, "v1"); err != nil { t.Fatal(err) } - pB := chunkProvider(t, t.TempDir(), remote, viewAs("rB", 4), 0) + pB := layoutChunkProvider(t, t.TempDir(), fixture, viewAs("rB", 4), 0) openRecovered(t, pB) // takeover raises HEAD to epoch 4 - before := headHolder(t, remote) + before := layoutHead(t, fixture) if before.Epoch != 4 || before.Holder != "rB" { t.Fatalf("takeover HEAD %+v", before) } @@ -216,10 +197,10 @@ func TestWALStoreChunk_CutRefusedAfterANewerEpochTakesOver(t *testing.T) { if _, err := pA.CaptureVolume(ctx, "v1"); err == nil { t.Fatal("the epoch-3 holder cut over the epoch-4 HEAD") } - if after := headHolder(t, remote); after.Gen != before.Gen || after.Holder != "rB" { + if after := layoutHead(t, fixture); after.Gen != before.Gen || after.Holder != "rB" { t.Fatalf("HEAD moved after the stale holder's cut: %+v -> %+v", before, after) } - if !bytes.Equal(headBlock(t, remote, 0), block(0xE1)) { + if !bytes.Equal(layoutHeadBlock(t, fixture, 0), block(0xE1)) { t.Fatal("HEAD lost the published image") } } @@ -229,10 +210,10 @@ func TestWALStoreChunk_CutRefusedAfterANewerEpochTakesOver(t *testing.T) { // with the same evidence. func TestWALStoreChunk_MoveBackRefusedOnDeferredAttach(t *testing.T) { ctx := context.Background() - remote, rootA := movedAwayAndBack(t) - before := headHolder(t, remote) + fixture, rootA := movedAwayAndBack(t) + before := layoutHead(t, fixture) view := newStubView(frontend.Projection{}) - pA2 := chunkProvider(t, rootA, remote, view, 0) + pA2 := layoutChunkProvider(t, rootA, fixture, view, 0) if _, err := pA2.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -248,15 +229,15 @@ func TestWALStoreChunk_MoveBackRefusedOnDeferredAttach(t *testing.T) { st = s } } - if strings.Contains(st.Evidence, "remove or quarantine the local root") { + if strings.Contains(st.Evidence, layout.StaleLocalRootCure) { break } time.Sleep(20 * time.Millisecond) } - if st.Operational || !strings.Contains(st.Evidence, "remove or quarantine the local root") { + if st.Operational || !strings.Contains(st.Evidence, layout.StaleLocalRootCure) { t.Fatalf("deferred attach of the old root: operational %t evidence %q", st.Operational, st.Evidence) } - if after := headHolder(t, remote); after.Gen != before.Gen || after.Holder != before.Holder { + if after := layoutHead(t, fixture); after.Gen != before.Gen || after.Holder != before.Holder { t.Fatalf("HEAD changed by a refused deferred attach: %+v -> %+v", before, after) } } diff --git a/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go b/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go index 1e3e2a9734..f4dec3dd68 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_noflush_test.go @@ -8,9 +8,11 @@ import ( "fmt" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/storage" + "reflect" "runtime" "sort" "testing" @@ -43,12 +45,13 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { const total = 400 * 1024 * 1024 const transfer = 128 * 1024 ctx := context.Background() - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", (1<<30)/4096, 1024) + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: (1 << 30) / 4096, ChunkBlocks: 1024, ChunkCaptureInterval: 0, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } @@ -68,9 +71,9 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { if err != nil { t.Fatal(err) } - before, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) + before, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found { + t.Fatalf("initial layout HEAD: found=%v err=%v", found, err) } ws := s.(*storage.WALStore) if err := ws.SetWMode(mode); err != nil { @@ -79,7 +82,7 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { syncsBefore := ws.WALSyncCount() var durations []time.Duration busyCount := 0 - t.Logf("before HEAD gen=%d remoteLSN=%d cp=%d next=%d retention=%d", before.Gen, before.RemoteLSN, ws.CheckpointLSN(), ws.NextLSN(), ws.RecoveryRetentionLSNs()) + t.Logf("before HEAD gen=%d cp=%d next=%d retention=%d", before.Gen, ws.CheckpointLSN(), ws.NextLSN(), ws.RecoveryRetentionLSNs()) recorded := &noFlushBackend{Backend: be} h := nvme.NewIOHandler(nvme.HandlerConfig{Backend: recorded, BlockSize: 4096, VolumeSize: 1 << 30}) data := make([]byte, transfer) @@ -163,12 +166,12 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { fsyncs *= 2 } t.Logf("COST mode=%d bytes=%d busy=%d pressureBatches=%d internalFsyncsPerGiB=%.2f attemptP99=%v maxAttempt=%v", mode, total, busyCount, batches, float64(fsyncs)/(float64(total)/(1<<30)), durations[(len(durations)-1)*99/100], durations[len(durations)-1]) - after, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) + after, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found { + t.Fatalf("final layout HEAD: found=%v err=%v", found, err) } st := p.DurableStatuses() - if after.Gen != before.Gen || after.RemoteLSN != before.RemoteLSN { + if !reflect.DeepEqual(after, before) { t.Fatalf("remote moved without explicit cut: before=%+v after=%+v", before, after) } if len(st) != 1 || st[0].Chunk == nil || st[0].Chunk.Stats.CutsOK != 0 { @@ -177,7 +180,7 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { if ws.CheckpointLSN() == 0 || st[0].WriteProfile.WALAppendWrapCount == 0 { t.Fatal("no checkpoint or physical wrap observed") } - t.Logf("after HEAD gen=%d remoteLSN=%d cp=%d next=%d wraps=%d cuts=%d", after.Gen, after.RemoteLSN, ws.CheckpointLSN(), ws.NextLSN(), st[0].WriteProfile.WALAppendWrapCount, st[0].Chunk.Stats.CutsOK) + t.Logf("after HEAD gen=%d cp=%d next=%d wraps=%d cuts=%d", after.Gen, ws.CheckpointLSN(), ws.NextLSN(), st[0].WriteProfile.WALAppendWrapCount, st[0].Chunk.Stats.CutsOK) } @@ -185,8 +188,10 @@ func runNoClientFlushBurst(t *testing.T, mode storage.WMode) { // Expiry is retryable; ending the session restores local no-Flush progress. func TestWALStoreChunkV3NoFlushWithActiveRF2CatchupPin(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) + fixture := testutil.NewLayoutFixture(t, "v1", 1<<18, 1024) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024} + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go index 07e2f433f9..fb3e74762f 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_precopy_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "errors" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" "strconv" "strings" "sync" @@ -12,11 +11,15 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) func TestPrecopyFreezeDoesNotWaitForAdmittedIO(t *testing.T) { - p, view := parkedProvider(t, storage.NewMemChunkRemote()) + p, view := parkedLayoutProvider(t, testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks)) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") if err != nil { @@ -74,10 +77,27 @@ func TestPrecopyFreezeDoesNotWaitForAdmittedIO(t *testing.T) { } func precopyProvider(t *testing.T, remote storage.ChunkRemote, view *parkView, hooks ...*detachHooks) *durable.DurableProvider { + t.Helper() + _ = remote // Other legacy callers migrate to the layout fixture separately. + return precopyBProvider(t, testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks), view, nil, hooks...) +} + +func precopyBProvider(t *testing.T, fixture *testutil.LayoutFixture, view *parkView, delayed *precopyLayoutDelayedRemote, hooks ...*detachHooks) *durable.DurableProvider { t.Helper() cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkDetachPrecopy: true, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + ChunkDetachPrecopy: true, + } + fixture.Configure(&cfg) + if delayed != nil { + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.Catalog, fixture.Ref, me) + if err != nil { + return nil, err + } + delayed.LayoutRemote = inner + return delayed, nil + } } if len(hooks) > 0 { cfg.OnChunkDetach = hooks[0].detach @@ -92,13 +112,23 @@ func precopyProvider(t *testing.T, remote storage.ChunkRemote, view *parkView, h } func TestPrecopyProviderPublishesExactDetachedImage(t *testing.T) { - remote := storage.NewMemChunkRemote() - p := precopyProvider(t, remote, &parkView{stubView: v1View()}) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := precopyBProvider(t, fixture, &parkView{stubView: v1View()}, nil) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") if err != nil { t.Fatal(err) } + // Establish the measured upload rate on the B content path before the + // pre-copy admission decision; one dirty chunk alone has no rate window. + for _, lba := range []int64{16, 32, 48} { + if _, err := b.Write(context.Background(), lba*4096, block(byte(lba))); err != nil { + t.Fatal(err) + } + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + } if _, err = b.Write(context.Background(), 4096, block(0x8a)); err != nil { t.Fatal(err) } @@ -106,7 +136,7 @@ func TestPrecopyProviderPublishesExactDetachedImage(t *testing.T) { if err != nil || !r.Precopy.Frozen || r.Head.State != storage.ChunkHeadDetached || r.H != last { t.Fatalf("detach=%+v last=%d err=%v", r, last, err) } - if !bytes.Equal(headBlock(t, remote, 1), block(0x8a)) { + if !bytes.Equal(layoutHeadBlock(t, fixture, 1), block(0x8a)) { t.Fatal("detached image lost write") } if _, err = b.Write(context.Background(), 4096, block(0x9a)); err == nil { @@ -136,6 +166,24 @@ func (r *precopyFixedSampleRemote) CASHead(ctx context.Context, expected storage return r.MemChunkRemote.CASHead(ctx, expected, next) } +type precopyLayoutDelayedRemote struct { + *chunkstore.LayoutRemote + nextDelay atomic.Int64 +} + +func (r *precopyLayoutDelayedRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + if delay := time.Duration(r.nextDelay.Swap(0)); delay > 0 { + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + return 0, ctx.Err() + } + } + return r.LayoutRemote.CASHead(ctx, expected, next) +} + func TestPrecopyProviderBusyOwnerKeepsServing(t *testing.T) { precopyBusyOwnerKeepsServing(t, 0) } @@ -146,10 +194,11 @@ func TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample(t *testing.T) { func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { t.Helper() - remote := &precopyFixedSampleRemote{MemChunkRemote: storage.NewMemChunkRemote()} + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + remote := &precopyLayoutDelayedRemote{} view := &parkView{stubView: v1View()} k := &detachHooks{} - p := precopyProvider(t, remote, view, k) + p := precopyBProvider(t, fixture, view, remote, k) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") if err != nil { @@ -223,7 +272,7 @@ func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { if started, resumed := k.calls(); len(started) != 1 || len(resumed) != 1 { t.Fatalf("nonconverged hooks: started=%v resumed=%v", started, resumed) } - if h, _ := remote.GetHead(ctx); h.State == storage.ChunkHeadDetached { + if h := layoutHead(t, fixture); h.State == layout.StateDetached { t.Fatal("busy owner detached") } if _, err = b.Write(ctx, 8192, block(0x9b)); err != nil { @@ -245,15 +294,17 @@ func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { // Releasing the owner does not erase a slow sample. Admission must // still refuse a tail-bound point; a small stalled tail can now declare // the retained fixed-cost exception instead of recopying indefinitely. - if !errors.Is(err, storage.ErrPrecopyNotConverged) || r.Precopy.Frozen || r.Precopy.Estimate <= 1200*time.Millisecond || (r.Precopy.Reason != "tail_too_large" && r.Precopy.Reason != "barrier_over_budget" && r.Precopy.Reason != "freeze_budget_exceeded") { + unknownRate := r.Precopy.Reason == "samples_unknown" && r.Precopy.RateSamples == 0 + overBudget := r.Precopy.Estimate > 1200*time.Millisecond && (r.Precopy.Reason == "tail_too_large" || r.Precopy.Reason == "barrier_over_budget" || r.Precopy.Reason == "freeze_budget_exceeded") + if r.Precopy.Frozen || !(unknownRate && errors.Is(err, storage.ErrPrecopyUnknown) || overBudget && errors.Is(err, storage.ErrPrecopyNotConverged)) { t.Fatalf("post-release retry violated measured admission: report=%+v err=%v", r.Precopy, err) } if delay > 0 && r.Precopy.Fixed < delay { t.Fatal("retry forgot the controlled slow fixed sample") } resumedCount = 2 - if h, e := remote.GetHead(ctx); e != nil || h.State == storage.ChunkHeadDetached { - t.Fatalf("over-budget retry detached: head=%+v err=%v", h, e) + if h := layoutHead(t, fixture); h.State == layout.StateDetached { + t.Fatalf("over-budget retry detached: head=%+v", h) } buf := make([]byte, 4096) if n, e := b.Read(ctx, 8192, buf); e != nil || n != len(buf) || !bytes.Equal(buf, block(0x9b)) { @@ -267,7 +318,16 @@ func precopyBusyOwnerKeepsServing(t *testing.T, delay time.Duration) { if started, resumed := k.calls(); len(started) != 2 || len(resumed) != resumedCount { t.Fatalf("retry hooks: started=%v resumed=%v", started, resumed) } - if !bytes.Equal(headBlock(t, remote.MemChunkRemote, 1), block(0x8a)) || !bytes.Equal(headBlock(t, remote.MemChunkRemote, 2), block(0x9b)) { + if err != nil { + for lba, want := range map[int64][]byte{1: block(0x8a), 2: block(0x9b)} { + buf := make([]byte, 4096) + if n, readErr := b.Read(ctx, lba*4096, buf); readErr != nil || n != len(buf) || !bytes.Equal(buf, want) { + t.Fatalf("refused retry stopped serving block %d: n=%d err=%v", lba, n, readErr) + } + } + return + } + if !bytes.Equal(layoutHeadBlock(t, fixture, 1), block(0x8a)) || !bytes.Equal(layoutHeadBlock(t, fixture, 2), block(0x9b)) { t.Fatal("retry lost admitted bytes") } } diff --git a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go index 361b8db3be..20375d5e5e 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go @@ -5,24 +5,39 @@ package durable_test import ( "context" "fmt" + "strings" "sync" "sync/atomic" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) -func schedProvider(t *testing.T, remote storage.ChunkRemote, interval time.Duration) *durable.DurableProvider { +func schedProvider(t *testing.T, fixture *testutil.LayoutFixture, interval time.Duration, gate *gatedCASRemote) *durable.DurableProvider { t.Helper() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkCaptureInterval: interval, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) + } + fixture.Configure(&cfg) + if gate != nil { + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.Catalog, fixture.Ref, me) + if err != nil { + return nil, err + } + gate.LayoutRemote = inner + return gate, nil + } + } + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } @@ -30,22 +45,13 @@ func schedProvider(t *testing.T, remote storage.ChunkRemote, interval time.Durat return p } -func headGen(t *testing.T, remote storage.ChunkRemote) storage.ChunkHead { - t.Helper() - h, err := remote.GetHead(context.Background()) - if err != nil { - t.Fatal(err) - } - return h -} - // The remote holds snapshots: with the timer off, no number of dirty // chunks publishes a cut on its own. func TestWALStoreChunk_DirtyChunksNeverTriggerCut(t *testing.T) { - remote := storage.NewMemChunkRemote() - p := schedProvider(t, remote, 0) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := schedProvider(t, fixture, 0, nil) s := openRecovered(t, p) - claimed := freshV1Claim(t, remote) + claimed := layoutHead(t, fixture) for c := uint32(0); c < 4; c++ { // four dirty chunks if _, err := s.Write(c*pcChunkBlocks+1, block(byte(c+1))); err != nil { t.Fatal(err) @@ -53,8 +59,8 @@ func TestWALStoreChunk_DirtyChunksNeverTriggerCut(t *testing.T) { } // A negative invariant: checked repeatedly over several scheduler polls. for i := 0; i < 15; i++ { - if h := headGen(t, remote); h.Gen != claimed.Gen { - t.Fatalf("a cut was published with the timer off (HEAD gen %d, %d chunks)", h.Gen, len(h.Chunks)) + if h := layoutHead(t, fixture); h.Gen != claimed.Gen { + t.Fatalf("a cut was published with the timer off (HEAD gen %d)", h.Gen) } time.Sleep(100 * time.Millisecond) } @@ -62,8 +68,8 @@ func TestWALStoreChunk_DirtyChunksNeverTriggerCut(t *testing.T) { if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { t.Fatal(err) } - if h := headGen(t, remote); h.Gen != claimed.Gen+1 || len(h.Chunks) != 4 { - t.Fatalf("explicit cut HEAD gen %d with %d chunks, want 4", h.Gen, len(h.Chunks)) + if h := layoutHead(t, fixture); h.Gen <= claimed.Gen || len(layoutHeadRefs(t, fixture)) != 4 { + t.Fatalf("explicit cut HEAD gen %d with %d chunks, want 4", h.Gen, len(layoutHeadRefs(t, fixture))) } } @@ -71,10 +77,10 @@ func TestWALStoreChunk_DirtyChunksNeverTriggerCut(t *testing.T) { // cut comes one interval after it, not one interval after the loop began. func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) { const interval = 3 * time.Second - remote := storage.NewMemChunkRemote() - p := schedProvider(t, remote, interval) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := schedProvider(t, fixture, interval, nil) s := openRecovered(t, p) - claimed := freshV1Claim(t, remote) + claimed := layoutHead(t, fixture) begin := time.Now() time.Sleep(2 * time.Second) @@ -85,8 +91,9 @@ func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) { t.Fatal(err) } explicit := time.Now() - if h := headGen(t, remote); h.Gen != claimed.Gen+1 { - t.Fatalf("explicit cut: HEAD gen %d, want open claim + 1", h.Gen) + explicitHead := layoutHead(t, fixture) + if explicitHead.Gen <= claimed.Gen { + t.Fatalf("explicit cut: HEAD gen %d did not advance past claim %d", explicitHead.Gen, claimed.Gen) } if _, err := s.Write(pcChunkBlocks+1, block(0x02)); err != nil { t.Fatal(err) @@ -97,26 +104,27 @@ func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) { if time.Now().After(explicit.Add(interval - 300*time.Millisecond)) { t.Skip("scheduling too slow to separate the two deadlines on this host") } - if h := headGen(t, remote); h.Gen != claimed.Gen+1 { + if h := layoutHead(t, fixture); h.Gen != explicitHead.Gen { t.Fatalf("automatic cut %s after the explicit one (HEAD gen %d): the timer did not restart", time.Since(explicit), h.Gen) } // Progress, no timer (#227): the automatic cut follows; a loaded host only // delays it (the early-cut check above is the timing assertion, and it // skips when the host cannot separate the two deadlines). - for headGen(t, remote).Gen < claimed.Gen+2 { + for layoutHead(t, fixture).Gen <= explicitHead.Gen { time.Sleep(50 * time.Millisecond) } } // The volume status carries the chunk layer's state and cut counters. func TestWALStoreChunk_StatusCarriesChunkLayer(t *testing.T) { - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) // pre-assignment - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, view) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } @@ -133,11 +141,18 @@ func TestWALStoreChunk_StatusCarriesChunkLayer(t *testing.T) { t.Fatalf("status before authority: %+v", st) } view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1})) + deadline := time.Now().Add(10 * time.Second) + for !p.DurableStatuses()[0].Chunk.Attached { + if time.Now().After(deadline) { + t.Fatal("layout attach never completed after authority arrived") + } + time.Sleep(20 * time.Millisecond) + } if _, err := s.Write(1, block(1)); err != nil { t.Fatal(err) } var lsn uint64 - deadline := time.Now().Add(10 * time.Second) + deadline = time.Now().Add(10 * time.Second) for { if lsn, err = p.CaptureVolume(context.Background(), "v1"); err == nil { break @@ -170,25 +185,26 @@ func TestWALStoreChunk_StatusHasNoChunkSectionForWALStore(t *testing.T) { // ChunkOnPublishSettled sees every confirmed publication of a volume, with // its volume id and the HEAD before and after it; a no-op capture is not one. func TestWALStoreChunk_PublishSettledHook(t *testing.T) { - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) var mu sync.Mutex var got []string - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, ChunkOnPublishSettled: func(_ context.Context, volumeID string, prev, next storage.ChunkHead) { mu.Lock() got = append(got, fmt.Sprintf("%s:%d->%d", volumeID, prev.Gen, next.Gen)) mu.Unlock() }, - }, v1View()) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = p.Close() }) s := openRecovered(t, p) - claimed := freshV1Claim(t, remote) + claimed := layoutHead(t, fixture) for i, lba := range []uint32{1, 0, pcChunkBlocks + 1} { if lba != 0 { if _, err := s.Write(lba, block(byte(i+1))); err != nil { @@ -201,17 +217,15 @@ func TestWALStoreChunk_PublishSettledHook(t *testing.T) { } mu.Lock() defer mu.Unlock() - wantFirst := fmt.Sprintf("v1:%d->%d", claimed.Gen, claimed.Gen+1) - wantSecond := fmt.Sprintf("v1:%d->%d", claimed.Gen+1, claimed.Gen+2) - if len(got) != 2 || got[0] != wantFirst || got[1] != wantSecond { - t.Fatalf("reports %v; want [%s %s] (the middle capture changed nothing)", got, wantFirst, wantSecond) + if len(got) != 2 || !strings.HasPrefix(got[0], fmt.Sprintf("v1:%d->", claimed.Gen)) || got[0] == got[1] { + t.Fatalf("reports %v; want two distinct B publications (the middle capture changed nothing)", got) } } -// gatedCASRemote holds the next HEAD CAS, once armed, until it is released +// gatedCASRemote holds the next B HEAD CAS, once armed, until it is released // (or its context ends), and reports when that CAS started. type gatedCASRemote struct { - *storage.MemChunkRemote + *chunkstore.LayoutRemote armed atomic.Bool entered chan struct{} release chan struct{} @@ -226,7 +240,7 @@ func (r *gatedCASRemote) CASHead(ctx context.Context, expected storage.ChunkHead return 0, ctx.Err() } } - return r.MemChunkRemote.CASHead(ctx, expected, next) + return r.LayoutRemote.CASHead(ctx, expected, next) } type loopEvent struct { @@ -243,11 +257,12 @@ type loopEvent struct { // decision is made from the explicit cut, a whole interval after it. func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) { const interval = 3 * time.Second - remote := &gatedCASRemote{MemChunkRemote: storage.NewMemChunkRemote(), entered: make(chan struct{}), release: make(chan struct{})} + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + remote := &gatedCASRemote{entered: make(chan struct{}), release: make(chan struct{})} var releaseOnce sync.Once release := func() { releaseOnce.Do(func() { close(remote.release) }) } t.Cleanup(release) - p := schedProvider(t, remote, interval) + p := schedProvider(t, fixture, interval, remote) events := make(chan loopEvent, 64) durable.SetTestChunkLoopTrace(p, func(event string, lastCutNs int64, skipped bool) { select { @@ -266,7 +281,7 @@ func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) { return loopEvent{} } s := openRecovered(t, p) - claimed := freshV1Claim(t, remote.MemChunkRemote) + claimed := layoutHead(t, fixture) begin := time.Now() // the loop started during open: its first deadline is at most begin + interval if _, err := s.Write(1, block(0x01)); err != nil { t.Fatal(err) @@ -313,8 +328,9 @@ func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) { t.Fatal("the explicit cut did not finish") } explicitAt := time.Now() - if h := headGen(t, remote); h.Gen != claimed.Gen+1 { - t.Fatalf("explicit cut: HEAD gen %d, want open claim + 1", h.Gen) + explicitHead := layoutHead(t, fixture) + if explicitHead.Gen <= claimed.Gen { + t.Fatalf("explicit cut: HEAD gen %d did not advance past claim %d", explicitHead.Gen, claimed.Gen) } if _, err := s.Write(pcChunkBlocks+1, block(0x02)); err != nil { t.Fatal(err) @@ -341,7 +357,7 @@ func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) { if cut2.event != "cut" || cut2.skipped { t.Fatalf("loop event %+v; want the next periodic cut taken", cut2) } - if h := headGen(t, remote); h.Gen != claimed.Gen+2 { - t.Fatalf("after the next periodic cut: HEAD gen %d, want open claim + 2", h.Gen) + if h := layoutHead(t, fixture); h.Gen <= explicitHead.Gen { + t.Fatalf("after the next periodic cut: HEAD gen %d did not advance past explicit cut %d", h.Gen, explicitHead.Gen) } } diff --git a/seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go b/seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go index 336c6ee039..979bb760fc 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go @@ -9,7 +9,9 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -42,15 +44,16 @@ func (c *snapCalls) count() int { return len(c.heads) } -func snapScheduleProvider(t *testing.T, remote storage.ChunkRemote, period time.Duration, calls *snapCalls) *durable.DurableProvider { +func snapScheduleProvider(t *testing.T, fixture *testutil.LayoutFixture, period time.Duration, calls *snapCalls) *durable.DurableProvider { t.Helper() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkSnapshotPeriod: period, ChunkScheduledSnapshot: calls.take, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } @@ -85,9 +88,9 @@ func waitFor(t *testing.T, d time.Duration, what string, ok func() bool) { // is visible in the status with its code. func TestWALStoreChunk_ScheduledSnapshotCutsAndReports(t *testing.T) { const period = 2 * time.Second - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) calls := &snapCalls{} - p := snapScheduleProvider(t, remote, period, calls) + p := snapScheduleProvider(t, fixture, period, calls) s := openRecovered(t, p) if _, err := s.Write(1, block(0x5A)); err != nil { t.Fatal(err) @@ -96,7 +99,7 @@ func TestWALStoreChunk_ScheduledSnapshotCutsAndReports(t *testing.T) { calls.mu.Lock() h := calls.heads[0] calls.mu.Unlock() - if remoteHead := headGen(t, remote); h.Gen == 0 || h.Gen > remoteHead.Gen || len(h.Chunks) == 0 { + if remoteHead := layoutHead(t, fixture); h.Gen == 0 || h.Gen > remoteHead.Gen || len(layoutHeadRefs(t, fixture)) == 0 { t.Fatalf("snapshot HEAD gen %d with %d chunks (remote gen %d); want the cut that published the write", h.Gen, len(h.Chunks), remoteHead.Gen) } waitFor(t, time.Second, "the success in the status", func() bool { @@ -123,9 +126,9 @@ func TestWALStoreChunk_ScheduledSnapshotCutsAndReports(t *testing.T) { // With the schedule off (period zero), no snapshot is attempted and the // status has no scheduled-snapshot section. func TestWALStoreChunk_ScheduledSnapshotOffTakesNone(t *testing.T) { - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) calls := &snapCalls{} - p := snapScheduleProvider(t, remote, 0, calls) + p := snapScheduleProvider(t, fixture, 0, calls) s := openRecovered(t, p) if _, err := s.Write(1, block(0x01)); err != nil { t.Fatal(err) @@ -140,11 +143,12 @@ func TestWALStoreChunk_ScheduledSnapshotOffTakesNone(t *testing.T) { // A snapshot period without its callback is refused. func TestWALStoreChunk_ScheduledSnapshotNeedsItsCallback(t *testing.T) { - _, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkSnapshotPeriod: time.Hour, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, - }, v1View()) + } + testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks).Configure(&cfg) + _, err := durable.NewDurableProvider(cfg, v1View()) if err == nil { t.Fatal("a snapshot period without its callback was accepted") } @@ -155,9 +159,9 @@ func TestWALStoreChunk_ScheduledSnapshotNeedsItsCallback(t *testing.T) { // counted by reason, and no snapshot is taken. func TestWALStoreChunk_ScheduledSnapshotSkipsARestoringVolume(t *testing.T) { const period = 2 * time.Second - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) view := v1View() - first := chunkProvider(t, t.TempDir(), remote, view, 0) + first := layoutChunkProvider(t, t.TempDir(), fixture, view, 0) s := openRecovered(t, first) if _, err := s.Write(33, block(0x33)); err != nil { t.Fatal(err) @@ -167,12 +171,14 @@ func TestWALStoreChunk_ScheduledSnapshotSkipsARestoringVolume(t *testing.T) { } _ = first.Close() calls := &snapCalls{} - fresh, err := durable.NewDurableProvider(durable.ProviderConfig{ + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkSnapshotPeriod: period, ChunkScheduledSnapshot: calls.take, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, view) + } + fixture.Configure(&cfg) + fresh, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider_chunk_test.go b/seaweed-block/core/frontend/durable/provider_chunk_test.go index c80c1d8f38..b5756737d6 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_test.go @@ -9,11 +9,15 @@ import ( "bytes" "context" "errors" + "reflect" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -24,17 +28,48 @@ const ( func chunkProvider(t *testing.T, root string, remote storage.ChunkRemote, view *stubView, interval time.Duration) *durable.DurableProvider { t.Helper() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + if gated, ok := remote.(*gatedRemote); ok { + gated.fixture = fixture + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkCaptureInterval: interval} + fixture.Configure(&cfg) + st, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + t.Fatal(err) + } + gated.StartStore = st + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return gated, nil } + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.Catalog, fixture.Ref, me) + if err != nil { + return nil, err + } + gated.ChunkRemote = inner + return gated, nil + } + p, err := durable.NewDurableProvider(cfg, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p + } + _ = remote // plain legacy callers migrate to explicit shared fixtures. + return layoutChunkProvider(t, root, fixture, view, interval) +} + +func layoutChunkProvider(t *testing.T, root string, fixture *testutil.LayoutFixture, view *stubView, interval time.Duration) *durable.DurableProvider { + t.Helper() + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkCaptureInterval: interval, - ChunkRemoteFor: func(volumeID string) (storage.ChunkRemote, error) { - return remote, nil - }, - }, view) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatalf("NewDurableProvider: %v", err) } @@ -88,16 +123,85 @@ func headBlock(t *testing.T, remote *storage.MemChunkRemote, lba uint32) []byte return b[off : off+4096] } +func layoutHead(t *testing.T, fixture *testutil.LayoutFixture) layout.Head { + t.Helper() + h, found, err := fixture.Catalog.ReadHead(context.Background(), fixture.Ref) + if err != nil || !found { + t.Fatalf("layout HEAD: found=%v err=%v", found, err) + } + return h +} + +func layoutHeadBlock(t *testing.T, fixture *testutil.LayoutFixture, lba uint32) []byte { + t.Helper() + h := layoutHead(t, fixture) + if h.Current == nil { + return make([]byte, 4096) + } + store, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + t.Fatal(err) + } + reader, err := layout.NewReader("/provider-test", fixture.Ref.Dir(), store.Fetch) + if err != nil { + t.Fatal(err) + } + image, err := reader.Open(context.Background(), *h.Current) + if err != nil { + t.Fatal(err) + } + chunk, err := image.Chunk(context.Background(), uint64(lba/pcChunkBlocks)) + if err != nil { + t.Fatal(err) + } + if chunk.Zero { + return make([]byte, 4096) + } + off := int(lba%pcChunkBlocks) * 4096 + return chunk.Data[off : off+4096] +} + +func layoutHeadRefs(t *testing.T, fixture *testutil.LayoutFixture) map[uint64]layout.Ref { + t.Helper() + h := layoutHead(t, fixture) + refs := make(map[uint64]layout.Ref) + if h.Current == nil { + return refs + } + store, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + t.Fatal(err) + } + reader, err := layout.NewReader("/provider-test", fixture.Ref.Dir(), store.Fetch) + if err != nil { + t.Fatal(err) + } + image, err := reader.Open(context.Background(), *h.Current) + if err != nil { + t.Fatal(err) + } + for i := uint64(0); i < pcBlocks/pcChunkBlocks; i++ { + ref, zero, err := image.Resolve(context.Background(), i) + if err != nil { + t.Fatal(err) + } + if !zero { + refs[i] = ref + } + } + return refs +} + func v1View() *stubView { return newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1})) } -func TestWALStoreChunk_RequiresRemote(t *testing.T) { +func TestWALStoreChunk_RequiresLayoutFactories(t *testing.T) { _, err := durable.NewDurableProvider(durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, }, v1View()) if err == nil { - t.Fatal("walstore-chunk without ChunkRemoteFor was accepted") + t.Fatal("walstore-chunk without layout factories was accepted") } } @@ -106,9 +210,9 @@ func TestWALStoreChunk_RequiresRemote(t *testing.T) { // incremental. func TestWALStoreChunk_CaptureAndRestart(t *testing.T) { root := t.TempDir() - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) view := v1View() - p := chunkProvider(t, root, remote, view, 0) + p := layoutChunkProvider(t, root, fixture, view, 0) s := openRecovered(t, p) for lba := uint32(0); lba < 40; lba += 8 { // chunks 0, 0, 1, 1, 2 if _, err := s.Write(lba, block(byte(lba+1))); err != nil { @@ -119,12 +223,12 @@ func TestWALStoreChunk_CaptureAndRestart(t *testing.T) { if err != nil { t.Fatalf("CaptureVolume: %v", err) } - head, _ := remote.GetHead(context.Background()) - if head.RemoteLSN != h || head.Epoch != 3 || head.Holder != "r1" || len(head.Chunks) != 3 { - t.Fatalf("HEAD after capture: remote_lsn %d (want %d) epoch %d holder %q chunks %d", head.RemoteLSN, h, head.Epoch, head.Holder, len(head.Chunks)) + head := layoutHead(t, fixture) + if head.Position != h || head.Epoch != 3 || head.Holder != "r1" || head.Current == nil { + t.Fatalf("HEAD after capture: position %d (want %d) epoch %d holder %q root %v", head.Position, h, head.Epoch, head.Holder, head.Current) } for lba := uint32(0); lba < 40; lba += 8 { - if !bytes.Equal(headBlock(t, remote, lba), block(byte(lba+1))) { + if !bytes.Equal(layoutHeadBlock(t, fixture, lba), block(byte(lba+1))) { t.Fatalf("HEAD LBA %d differs", lba) } } @@ -132,7 +236,7 @@ func TestWALStoreChunk_CaptureAndRestart(t *testing.T) { t.Fatal(err) } - p2 := chunkProvider(t, root, remote, view, 0) + p2 := layoutChunkProvider(t, root, fixture, view, 0) s2 := openRecovered(t, p2) if got, _ := s2.Read(16); !bytes.Equal(got, block(17)) { t.Fatal("restarted volume lost local data") @@ -140,14 +244,24 @@ func TestWALStoreChunk_CaptureAndRestart(t *testing.T) { if _, err := s2.Write(100, block(0xAB)); err != nil { // chunk 6 t.Fatal(err) } - before := remote.Puts() + before := layoutHeadRefs(t, fixture) if _, err := p2.CaptureVolume(context.Background(), "v1"); err != nil { t.Fatalf("CaptureVolume after restart: %v", err) } - if n := remote.Puts() - before; n != 1 { - t.Fatalf("cut after restart stored %d chunks, want 1 (incremental)", n) + after := layoutHeadRefs(t, fixture) + changed := 0 + for i := uint64(0); i < pcBlocks/pcChunkBlocks; i++ { + if !reflect.DeepEqual(before[i], after[i]) { + changed++ + if i != 6 { + t.Fatalf("cut after restart changed chunk %d, want only 6", i) + } + } } - if !bytes.Equal(headBlock(t, remote, 100), block(0xAB)) { + if changed != 1 { + t.Fatalf("cut after restart changed %d chunk refs, want 1", changed) + } + if !bytes.Equal(layoutHeadBlock(t, fixture, 100), block(0xAB)) { t.Fatal("HEAD lacks the post-restart write") } } @@ -155,9 +269,9 @@ func TestWALStoreChunk_CaptureAndRestart(t *testing.T) { // A provider that creates the volume (a new host) starts from the remote // HEAD and reads lazily. func TestWALStoreChunk_FreshHostReadsFromHead(t *testing.T) { - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) view := v1View() - p := chunkProvider(t, t.TempDir(), remote, view, 0) + p := layoutChunkProvider(t, t.TempDir(), fixture, view, 0) s := openRecovered(t, p) if _, err := s.Write(33, block(0x33)); err != nil { t.Fatal(err) @@ -165,7 +279,11 @@ func TestWALStoreChunk_FreshHostReadsFromHead(t *testing.T) { if err := p.MakeVolumeRemoteDurable(context.Background(), "v1", 1); err != nil { t.Fatalf("MakeVolumeRemoteDurable: %v", err) } - fresh := chunkProvider(t, t.TempDir(), remote, view, 0) // empty local root + if err := p.Close(); err != nil { + t.Fatal(err) + } + next := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + fresh := layoutChunkProvider(t, t.TempDir(), fixture, next, 0) // empty local root at a new grant s2 := openRecovered(t, fresh) if got, err := s2.Read(33); err != nil || !bytes.Equal(got, block(0x33)) { t.Fatalf("fresh host read: %v", err) @@ -173,9 +291,9 @@ func TestWALStoreChunk_FreshHostReadsFromHead(t *testing.T) { } func TestWALStoreChunk_CaptureNeedsHealthyProjection(t *testing.T) { - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) view := v1View() - p := chunkProvider(t, t.TempDir(), remote, view, 0) + p := layoutChunkProvider(t, t.TempDir(), fixture, view, 0) s := openRecovered(t, p) if _, err := s.Write(1, block(1)); err != nil { t.Fatal(err) @@ -186,14 +304,14 @@ func TestWALStoreChunk_CaptureNeedsHealthyProjection(t *testing.T) { if _, err := p.CaptureVolume(context.Background(), "v1"); !errors.Is(err, storage.ErrChunkCaptureRefused) { t.Fatalf("capture with an unhealthy projection: got %v, want refused", err) } - if remote.Puts() != 0 { + if fixture.Blobs.Puts() != 0 { t.Fatal("a refused capture stored chunks") } } func TestWALStoreChunk_PeriodicCut(t *testing.T) { - remote := storage.NewMemChunkRemote() - p := chunkProvider(t, t.TempDir(), remote, v1View(), 20*time.Millisecond) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := layoutChunkProvider(t, t.TempDir(), fixture, v1View(), 20*time.Millisecond) s := openRecovered(t, p) lsn, err := s.Write(50, block(0x50)) if err != nil { @@ -201,16 +319,16 @@ func TestWALStoreChunk_PeriodicCut(t *testing.T) { } deadline := time.Now().Add(5 * time.Second) for { - head, _ := remote.GetHead(context.Background()) - if head.RemoteLSN >= lsn { + head := layoutHead(t, fixture) + if head.Position >= lsn { break } if time.Now().After(deadline) { - t.Fatalf("periodic cut never published LSN %d (HEAD remote_lsn %d)", lsn, head.RemoteLSN) + t.Fatalf("periodic cut never published LSN %d (HEAD position %d)", lsn, head.Position) } time.Sleep(10 * time.Millisecond) } - if !bytes.Equal(headBlock(t, remote, 50), block(0x50)) { + if !bytes.Equal(layoutHeadBlock(t, fixture, 50), block(0x50)) { t.Fatal("periodic cut published the wrong bytes") } } @@ -237,7 +355,7 @@ func TestWALStoreChunk_SelectorRules(t *testing.T) { t.Fatal(err) } _ = sw.Close() - p := chunkProvider(t, root, storage.NewMemChunkRemote(), view, 0) + p := layoutChunkProvider(t, root, testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks), view, 0) if _, err := p.EnsureStorage("v1"); !errors.Is(err, durable.ErrImplKindMismatch) { t.Fatalf("walstore-chunk over a smartwal file: got %v, want ErrImplKindMismatch", err) } diff --git a/seaweed-block/core/frontend/durable/provider_format_v3_base_test.go b/seaweed-block/core/frontend/durable/provider_format_v3_base_test.go index 96ea3a6d40..eb55e04511 100644 --- a/seaweed-block/core/frontend/durable/provider_format_v3_base_test.go +++ b/seaweed-block/core/frontend/durable/provider_format_v3_base_test.go @@ -13,8 +13,8 @@ import ( func TestDurableProviderV3_AttachedChunkBASEInstallAndCapture(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() - p := mappedProviderV3(t, t.TempDir(), remote) + fixture := newFormatV3Fixture(t) + p := mappedProviderV3(t, t.TempDir(), fixture, formatV3View{}) st, e := p.EnsureStorage("v1") if e != nil { t.Fatal(e) @@ -41,24 +41,18 @@ func TestDurableProviderV3_AttachedChunkBASEInstallAndCapture(t *testing.T) { if _, e = p.CaptureVolume(ctx, "v1"); e != nil { t.Fatalf("completed BASE capture refused: %v", e) } - head, e := remote.GetHead(ctx) - if e != nil { - t.Fatal(e) - } - ref, ok := head.Chunks[1] - if !ok { + if fixture.head(t).Current == nil { t.Fatal("completed BASE chunk omitted") } - chunk, e := remote.Get(ctx, ref.Key) - if e != nil || len(chunk) < 8192 || !bytes.Equal(chunk[4096:8192], want) { - t.Fatalf("captured BASE mismatch: %v", e) + if !bytes.Equal(fixture.block(t, 5), want) { + t.Fatal("captured BASE mismatch") } } func TestDurableProviderV3_AttachesCompletedChunkBASE(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - p := mappedProviderV3(t, t.TempDir(), storage.NewMemChunkRemote()) + p := mappedProviderV3(t, t.TempDir(), newFormatV3Fixture(t), formatV3View{}) st, e := p.EnsureStorage("v1") if e != nil { t.Fatal(e) @@ -101,8 +95,8 @@ func completedBASEDoesNotRestoreOlderHEAD(t *testing.T, retire bool) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() - source := mappedProviderV3(t, t.TempDir(), remote) + fixture := newFormatV3Fixture(t) + source := mappedProviderV3(t, t.TempDir(), fixture, formatV3View{}) if _, e := source.EnsureStorage("v1"); e != nil { t.Fatal(e) } @@ -124,7 +118,7 @@ func completedBASEDoesNotRestoreOlderHEAD(t *testing.T, retire bool) { t.Fatal(e) } root := t.TempDir() - target := mappedProviderV3(t, root, remote) + target := mappedProviderV3(t, root, fixture, formatV3TakeoverView{}) st, e := target.EnsureStorage("v1") if e != nil { t.Fatal(e) @@ -169,7 +163,7 @@ func completedBASEDoesNotRestoreOlderHEAD(t *testing.T, retire bool) { if e = target.Close(); e != nil { t.Fatal(e) } - target = mappedProviderV3(t, root, remote) + target = mappedProviderV3(t, root, fixture, formatV3TakeoverView{}) st, e = target.EnsureStorage("v1") if e != nil { t.Fatal(e) @@ -204,7 +198,7 @@ func completedBASEDoesNotRestoreOlderHEAD(t *testing.T, retire bool) { if e = target.Close(); e != nil { t.Fatal(e) } - target = mappedProviderV3(t, root, remote) + target = mappedProviderV3(t, root, fixture, formatV3TakeoverView{}) if _, e = target.EnsureStorage("v1"); e != nil { t.Fatal(e) } @@ -218,8 +212,8 @@ func completedBASEDoesNotRestoreOlderHEAD(t *testing.T, retire bool) { func TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() - source := mappedProviderV3(t, t.TempDir(), remote) + fixture := newFormatV3Fixture(t) + source := mappedProviderV3(t, t.TempDir(), fixture, formatV3View{}) if _, err := source.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -239,11 +233,8 @@ func TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD(t *testing.T) { if err := source.Close(); err != nil { t.Fatal(err) } - head, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - target := mappedProviderV3(t, t.TempDir(), remote) + head := fixture.head(t) + target := mappedProviderV3(t, t.TempDir(), fixture, formatV3TakeoverView{}) st, err := target.EnsureStorage("v1") if err != nil { t.Fatal(err) @@ -251,7 +242,7 @@ func TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD(t *testing.T) { if _, err = st.Recover(); err != nil { t.Fatal(err) } - if err = st.(*storage.WALStore).SeedChunkFrontier(head.RemoteLSN); err != nil { + if err = st.(*storage.WALStore).SeedChunkFrontier(head.Position); err != nil { t.Fatal(err) } if st.(*storage.WALStore).CheckpointLSN() == 0 || st.NextLSN() <= 1 { diff --git a/seaweed-block/core/frontend/durable/provider_format_v3_fresh_crash_test.go b/seaweed-block/core/frontend/durable/provider_format_v3_fresh_crash_test.go index f450ad17e2..1dc1345a75 100644 --- a/seaweed-block/core/frontend/durable/provider_format_v3_fresh_crash_test.go +++ b/seaweed-block/core/frontend/durable/provider_format_v3_fresh_crash_test.go @@ -14,41 +14,21 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/storage" ) -type freshCrashImage struct { - Head storage.ChunkHead - Objects map[string][]byte -} - -func freshCrashRemote(t *testing.T, path string) *storage.MemChunkRemote { +func freshCrashFixture(t *testing.T, path string) *formatV3Fixture { t.Helper() raw, err := os.ReadFile(path) if err != nil { t.Fatal(err) } - var img freshCrashImage + var img formatV3Image if err = json.Unmarshal(raw, &img); err != nil { t.Fatal(err) } - remote := storage.NewMemChunkRemote() - ctx := context.Background() - for key, data := range img.Objects { - if err = remote.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - } - for gen := uint64(0); gen < img.Head.Gen; gen++ { - current, e := remote.GetHead(ctx) - if e != nil { - t.Fatal(e) - } - if _, e = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: current.Gen, Epoch: current.Epoch}, img.Head); e != nil { - t.Fatal(e) - } - } - return remote + return restoreFormatV3Image(t, img) } // The child exits after presence is durable but before the fresh marker is @@ -70,8 +50,8 @@ func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if root := os.Getenv("SWBLOCK_V3_FRESH_CRASH_ROOT"); root != "" { - remote := freshCrashRemote(t, filepath.Join(root, "remote.json")) - p := mappedProviderV3(t, root, remote) + fixture := freshCrashFixture(t, filepath.Join(root, "layout.json")) + p := mappedProviderV3(t, root, fixture, formatV3TakeoverView{}) if os.Getenv("SWBLOCK_V3_FRESH_CRASH_MODE") == "capture" { p.cfg.ChunkCaptureInterval = time.Hour } @@ -119,8 +99,8 @@ func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { if mode == "complete" { install() } - if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { - t.Fatal(err) + if id, fresh, ok := ws.LayoutIdentity(); !ok || !fresh || id == "" { + t.Fatalf("local layout identity was not durably fresh: id=%q fresh=%v ok=%v", id, fresh, ok) } if err := h.ApplyInstallEntry(5, bytes.Repeat([]byte{0x79}, 4096), 9); err != nil { t.Fatal(err) @@ -129,15 +109,10 @@ func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { t.Fatal(err) } if mode == "capture" { - before, err := remote.GetHead(ctx) + beforeBytes, err := json.Marshal(fixture.image(t)) if err != nil { t.Fatal(err) } - beforeBytes, err := json.Marshal(before) - if err != nil { - t.Fatal(err) - } - puts := remote.Puts() if _, err := p.CaptureVolume(ctx, "v1"); !errors.Is(err, ErrNotChunkVolume) { t.Fatal("precommit CaptureVolume published before durable owner commit") } @@ -147,19 +122,11 @@ func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { if err := p.MakeVolumeRemoteDurable(ctx, "v1", 9); !errors.Is(err, ErrNotChunkVolume) { t.Fatal("precommit MakeVolumeRemoteDurable was admitted") } - after, err := remote.GetHead(ctx) + afterBytes, err := json.Marshal(fixture.image(t)) if err != nil { t.Fatal(err) } - afterBytes, err := json.Marshal(after) - if err != nil { - t.Fatal(err) - } - intents, err := remote.ListIntents(ctx) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(beforeBytes, afterBytes) || remote.Puts() != puts || len(intents) != 0 { + if !bytes.Equal(beforeBytes, afterBytes) || fixture.head(t).Activity != (layout.Activity{Kind: layout.ActIdle}) { t.Fatal("refused precommit publication changed remote state") } p.mu.Lock() @@ -171,7 +138,7 @@ func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { } fmt.Println("FRESH_CAPTURE_REFUSED no_remote_effect=true scheduler_hidden=true") } - fmt.Println("FRESH_CRASH_READY presence_saved=true marker_present=true ack=9 no_Close=true") + fmt.Println("FRESH_CRASH_READY presence_saved=true descriptor_fresh=true ack=9 no_Close=true") os.Exit(0) return nil } @@ -181,8 +148,8 @@ func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { t.Fatal("crash boundary not reached") } root := t.TempDir() - remote := storage.NewMemChunkRemote() - source := mappedProviderV3(t, t.TempDir(), remote) + fixture := newFormatV3Fixture(t) + source := mappedProviderV3(t, t.TempDir(), fixture, formatV3View{}) if _, err := source.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -203,23 +170,11 @@ func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { if err := source.Close(); err != nil { t.Fatal(err) } - head, err := remote.GetHead(ctx) + raw, err := json.Marshal(fixture.image(t)) if err != nil { t.Fatal(err) } - img := freshCrashImage{Head: head, Objects: map[string][]byte{}} - for _, ref := range head.Chunks { - data, e := remote.Get(ctx, ref.Key) - if e != nil { - t.Fatal(e) - } - img.Objects[ref.Key] = data - } - raw, err := json.Marshal(img) - if err != nil { - t.Fatal(err) - } - if err = os.WriteFile(filepath.Join(root, "remote.json"), raw, 0600); err != nil { + if err = os.WriteFile(filepath.Join(root, "layout.json"), raw, 0600); err != nil { t.Fatal(err) } cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE$", "-test.v") @@ -230,16 +185,17 @@ func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { if err != nil { t.Fatal(err) } - if !bytes.Contains(out, []byte("FRESH_CRASH_READY presence_saved=true marker_present=true ack=9 no_Close=true")) { + if !bytes.Contains(out, []byte("FRESH_CRASH_READY presence_saved=true descriptor_fresh=true ack=9 no_Close=true")) { t.Fatal("child missed crash boundary") } - p := mappedProviderV3(t, root, freshCrashRemote(t, filepath.Join(root, "remote.json"))) - if _, err = os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { - t.Fatal("crash marker missing", err) - } - if _, err = p.EnsureStorage("v1"); err != nil { + p := mappedProviderV3(t, root, freshCrashFixture(t, filepath.Join(root, "layout.json")), formatV3TakeoverView{}) + st, err := p.EnsureStorage("v1") + if err != nil { t.Fatal(err) } + if id, fresh, ok := st.(*storage.WALStore).LayoutIdentity(); !ok || !fresh || id == "" { + t.Fatalf("crash lost fresh descriptor: id=%q fresh=%v ok=%v", id, fresh, ok) + } if _, err = p.RecoverVolume(ctx, "v1"); err != nil { t.Fatalf("post-presence/pre-marker crash lost completed BASE recovery: %v", err) } @@ -256,8 +212,7 @@ func freshMarkerCrashKeepsCompletedBASE(t *testing.T, mode string) { func TestDurableProviderV3_AttachCommitRetryKeepsLayerPrivate(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() - p := mappedProviderV3(t, t.TempDir(), remote) + p := mappedProviderV3(t, t.TempDir(), newFormatV3Fixture(t), formatV3View{}) p.cfg.ChunkCaptureInterval = time.Hour if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) @@ -278,8 +233,8 @@ func TestDurableProviderV3_AttachCommitRetryKeepsLayerPrivate(t *testing.T) { if _, err := p.CaptureVolume(ctx, "v1"); !errors.Is(err, ErrNotChunkVolume) { t.Fatal("failed commit capture", err) } - if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); err != nil { - t.Fatal(err) + if id, fresh, ok := p.volumes["v1"].storage.(*storage.WALStore).LayoutIdentity(); !ok || !fresh || id == "" { + t.Fatalf("failed owner commit lost fresh descriptor: id=%q fresh=%v ok=%v", id, fresh, ok) } p.testBeforeChunkFreshRetire = nil if _, err := p.RecoverVolume(ctx, "v1"); err != nil { @@ -291,8 +246,8 @@ func TestDurableProviderV3_AttachCommitRetryKeepsLayerPrivate(t *testing.T) { if !correct { t.Fatal("commit did not publish the same pending layer and scheduler") } - if _, err := os.Stat(chunkFreshMarker(p.volumePath("v1"))); !os.IsNotExist(err) { - t.Fatal("committed marker remains", err) + if id, fresh, ok := p.volumes["v1"].storage.(*storage.WALStore).LayoutIdentity(); !ok || fresh || id == "" { + t.Fatalf("successful commit retained fresh descriptor: id=%q fresh=%v ok=%v", id, fresh, ok) } if _, err := p.CaptureVolume(ctx, "v1"); err != nil { t.Fatal("postcommit capture", err) diff --git a/seaweed-block/core/frontend/durable/provider_format_v3_test.go b/seaweed-block/core/frontend/durable/provider_format_v3_test.go index f9602b79f0..b3e65f2feb 100644 --- a/seaweed-block/core/frontend/durable/provider_format_v3_test.go +++ b/seaweed-block/core/frontend/durable/provider_format_v3_test.go @@ -8,11 +8,17 @@ import ( "encoding/binary" "errors" "os" + "path" + "strconv" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/protobuf/proto" ) type formatV3View struct{} @@ -21,13 +27,151 @@ func (formatV3View) Projection() frontend.Projection { return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true} } -func mappedProviderV3(t *testing.T, root string, remote storage.ChunkRemote) *DurableProvider { +type formatV3Fixture struct { + filer *chunkstore.MemFiler + cat *chunkstore.BCatalog + ref chunkstore.VolumeRef + blobs *layoutCrashBlobs +} + +func newFormatV3Fixture(t *testing.T) *formatV3Fixture { t.Helper() + blobs := &layoutCrashBlobs{b: map[string][]byte{}} + filer := chunkstore.NewMemFiler() + cat, err := chunkstore.NewBCatalog(filer, blobs, "/format-v3") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(context.Background(), ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + return &formatV3Fixture{filer: filer, cat: cat, ref: ref, blobs: blobs} +} + +func (f *formatV3Fixture) head(t *testing.T) layout.Head { + t.Helper() + h, found, err := f.cat.ReadHead(context.Background(), f.ref) + if err != nil || !found { + t.Fatalf("B HEAD: found=%v err=%v", found, err) + } + return h +} + +func (f *formatV3Fixture) block(t *testing.T, lba uint64) []byte { + t.Helper() + h := f.head(t) + if h.Current == nil { + return make([]byte, 4096) + } + st, err := f.cat.Store(f.ref) + if err != nil { + t.Fatal(err) + } + r, err := layout.NewReader("/format-v3", f.ref.Dir(), st.Fetch) + if err != nil { + t.Fatal(err) + } + img, err := r.Open(context.Background(), *h.Current) + if err != nil { + t.Fatal(err) + } + chunk, err := img.Chunk(context.Background(), lba/4) + if err != nil { + t.Fatal(err) + } + if chunk.Zero { + return make([]byte, 4096) + } + off := int(lba%4) * 4096 + return chunk.Data[off : off+4096] +} + +func (f *formatV3Fixture) puts() int { + f.blobs.Lock() + defer f.blobs.Unlock() + return len(f.blobs.b) +} + +func (f *formatV3Fixture) chunkPuts() int { + f.blobs.Lock() + defer f.blobs.Unlock() + count := 0 + for _, data := range f.blobs.b { + if len(data) == 4*4096 { + count++ + } + } + return count +} + +type formatV3Entry struct { + Dir string + Entry *filerpb.Entry +} + +type formatV3Image struct { + Ref chunkstore.VolumeRef + Entries []formatV3Entry + Blobs map[string][]byte +} + +func (f *formatV3Fixture) image(t *testing.T) formatV3Image { + t.Helper() + img := formatV3Image{Ref: f.ref, Blobs: map[string][]byte{}} + base := path.Join("/format-v3", f.ref.Dir()) + for _, suffix := range []string{"", layout.RootDir, layout.SegDir, path.Join(layout.PoolDir, "0")} { + dir := path.Join(base, suffix) + entries, err := f.filer.ListEntries(context.Background(), dir, "", "", 0) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + img.Entries = append(img.Entries, formatV3Entry{Dir: dir, Entry: entry}) + } + } + f.blobs.Lock() + for name, data := range f.blobs.b { + img.Blobs[name] = append([]byte(nil), data...) + } + f.blobs.Unlock() + return img +} + +func restoreFormatV3Image(t *testing.T, img formatV3Image) *formatV3Fixture { + t.Helper() + filer := chunkstore.NewMemFiler() + for _, item := range img.Entries { + if err := filer.CreateEntry(context.Background(), item.Dir, item.Entry, true); err != nil { + t.Fatal(err) + } + } + blobs := &layoutCrashBlobs{b: img.Blobs} + cat, err := chunkstore.NewBCatalog(filer, blobs, "/format-v3") + if err != nil { + t.Fatal(err) + } + return &formatV3Fixture{filer: filer, cat: cat, ref: img.Ref, blobs: blobs} +} + +func mappedProviderV3(t *testing.T, root string, fixture *formatV3Fixture, view frontend.ProjectionView, override ...layout.StartStore) *DurableProvider { + t.Helper() + headFor := func(string) (layout.StartStore, error) { return fixture.cat.Store(fixture.ref) } + if len(override) > 0 { + headFor = func(string) (layout.StartStore, error) { return override[0], nil } + } p, err := NewDurableProvider(ProviderConfig{ Impl: ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, WALRecoveryTestDisableFlusher: true, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, formatV3View{}) + ChunkLayoutHeadFor: headFor, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(fixture.cat, fixture.ref, me) + }, + }, view) if err != nil { t.Fatal(err) } @@ -40,8 +184,8 @@ func TestDurableProviderV3_MappedCheckpointCaptureAndReopen(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() root := t.TempDir() - remote := storage.NewMemChunkRemote() - p := mappedProviderV3(t, root, remote) + fixture := newFormatV3Fixture(t) + p := mappedProviderV3(t, root, fixture, formatV3View{}) st, err := p.EnsureStorage("v1") if err != nil { t.Fatal(err) @@ -65,23 +209,17 @@ func TestDurableProviderV3_MappedCheckpointCaptureAndReopen(t *testing.T) { } check := func(want []byte) { t.Helper() - head, e := remote.GetHead(ctx) - if e != nil { - t.Fatal(e) - } - ref, ok := head.Chunks[1] - if !ok { + if fixture.head(t).Current == nil { t.Fatal("capture omitted checkpointed chunk") } - chunk, e := remote.Get(ctx, ref.Key) - if e != nil { - t.Fatal(e) - } - if !bytes.Equal(chunk[4096:8192], want) { + if !bytes.Equal(fixture.block(t, 5), want) { t.Fatal("published chunk bytes differ") } } check(data) + if err = p.Close(); err != nil { + t.Fatal(err) + } raw, err := os.ReadFile(p.volumePath("v1")) if err != nil { t.Fatal(err) @@ -92,10 +230,7 @@ func TestDurableProviderV3_MappedCheckpointCaptureAndReopen(t *testing.T) { if _, err = os.Stat(p.volumePath("v1") + ".chunkbitmap"); !os.IsNotExist(err) { t.Fatalf("legacy bitmap exists: %v", err) } - if err = p.Close(); err != nil { - t.Fatal(err) - } - p2 := mappedProviderV3(t, root, remote) + p2 := mappedProviderV3(t, root, fixture, formatV3View{}) st2, err := p2.EnsureStorage("v1") if err != nil { t.Fatal(err) @@ -118,12 +253,12 @@ func TestDurableProviderV3_MappedCheckpointCaptureAndReopen(t *testing.T) { if err = storage.FlushMappedWALStoreV3Test(st2.(*storage.WALStore)); err != nil { t.Fatal(err) } - before := remote.Puts() + before := fixture.chunkPuts() if _, err = p2.CaptureVolume(ctx, "v1"); err != nil { t.Fatal(err) } - if remote.Puts()-before != 1 { - t.Fatalf("incremental capture uploaded %d chunks", remote.Puts()-before) + if fixture.chunkPuts()-before != 1 { + t.Fatalf("incremental capture uploaded %d chunks", fixture.chunkPuts()-before) } check(next) } @@ -133,8 +268,8 @@ func TestDurableProviderV3_MissingMapRefusesBeforeBackend(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() root := t.TempDir() - remote := storage.NewMemChunkRemote() - p := mappedProviderV3(t, root, remote) + fixture := newFormatV3Fixture(t) + p := mappedProviderV3(t, root, fixture, formatV3View{}) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -148,7 +283,7 @@ func TestDurableProviderV3_MissingMapRefusesBeforeBackend(t *testing.T) { if err := os.Remove(path + ".chunkmap"); err != nil { t.Fatal(err) } - p2 := mappedProviderV3(t, root, remote) + p2 := mappedProviderV3(t, root, fixture, formatV3View{}) if st, err := p2.EnsureStorage("v1"); err == nil || st != nil { t.Fatalf("accepted missing map: store=%v err=%v", st, err) } @@ -169,6 +304,9 @@ func TestDurableProviderV3_DefaultSelectorCreatesV3(t *testing.T) { if _, err = p.EnsureStorage("v1"); err != nil { t.Fatal(err) } + if err = p.Close(); err != nil { + t.Fatal(err) + } f, err := os.Open(p.volumePath("v1")) if err != nil { t.Fatal(err) @@ -187,31 +325,69 @@ func TestDurableProviderV3_DefaultSelectorCreatesV3(t *testing.T) { func TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: "old", RemoteLSN: ^uint64(0)}); err != nil { - t.Fatal(err) - } - before, err := remote.GetHead(ctx) + fixture := newFormatV3Fixture(t) + store, err := fixture.cat.Store(fixture.ref) if err != nil { t.Fatal(err) } - p := mappedProviderV3(t, t.TempDir(), remote) + bad := fixture.head(t) + bad.Epoch, bad.Holder, bad.ClaimID = 2, "old", "old-claim" + if err := store.UpdateHead(ctx, bad.Gen, bad); err != nil { + t.Fatal(err) + } + // An old writer could leave a HEAD with no next LSN. The current kernel + // refuses to write it, so inject its canonical bytes through the filer. + dir := path.Join("/format-v3", fixture.ref.Dir()) + entry, err := fixture.filer.LookupEntry(ctx, dir, layout.HeadName) + if err != nil { + t.Fatal(err) + } + oldPosition := []byte(`"position":` + strconv.FormatUint(bad.Position, 10)) + if bytes.Count(entry.Content, oldPosition) != 1 { + t.Fatalf("HEAD position field not unique: %s", entry.Content) + } + entry.Content = bytes.Replace(entry.Content, oldPosition, []byte(`"position":`+strconv.FormatUint(^uint64(0), 10)), 1) + entry.Attributes.FileSize = uint64(len(entry.Content)) + if err := fixture.filer.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + before, err := fixture.filer.LookupEntry(ctx, dir, layout.HeadName) + if err != nil { + t.Fatal(err) + } + root := t.TempDir() + p := mappedProviderV3(t, root, fixture, formatV3View{}) if _, err = p.EnsureStorage("v1"); err != nil { t.Fatal(err) } + if err = p.Close(); err != nil { + t.Fatal(err) + } raw, err := os.ReadFile(p.volumePath("v1")) if err != nil { t.Fatal(err) } - if _, err = p.RecoverVolume(ctx, "v1"); err == nil { + p = mappedProviderV3(t, root, fixture, formatV3View{}) + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + _, recoverErr := p.RecoverVolume(ctx, "v1") + if recoverErr == nil { t.Fatal("invalid HEAD frontier accepted") } - after, err := remote.GetHead(ctx) + after, err := fixture.filer.LookupEntry(ctx, dir, layout.HeadName) if err != nil { t.Fatal(err) } - if after.Gen != before.Gen || after.Epoch != before.Epoch || after.Holder != before.Holder { - t.Fatal("failed seed claimed HEAD") + if !proto.Equal(after, before) { + t.Fatalf("failed seed claimed HEAD: before=%+v after=%+v recovery=%v", before, after, recoverErr) + } + var buf [4096]byte + if _, err := p.Backend("v1").Read(ctx, 0, buf[:]); err == nil { + t.Fatal("failed restore left backend operational") + } + if err = p.Close(); err != nil { + t.Fatal(err) } now, err := os.ReadFile(p.volumePath("v1")) if err != nil { @@ -222,10 +398,6 @@ func TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim(t *testing.T) { if binary.LittleEndian.Uint16(now[4:6]) != 3 || binary.LittleEndian.Uint16(raw[4:6]) != 3 { t.Fatal("restore serialized a legacy header") } - var buf [4096]byte - if _, err := p.Backend("v1").Read(ctx, 0, buf[:]); err == nil { - t.Fatal("failed restore left backend operational") - } } // This exercises the row7 caller seam without enabling production v3. The @@ -237,22 +409,22 @@ func (formatV3TakeoverView) Projection() frontend.Projection { } type formatV3RestoreRemote struct { - storage.ChunkRemote + layout.StartStore beforeClaim func() error loseClaimResponse bool } -func (r *formatV3RestoreRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { - if expected.Epoch == 3 { +func (r *formatV3RestoreRemote) UpdateHead(ctx context.Context, expected uint64, next layout.Head) error { + if next.Epoch == 4 { if err := r.beforeClaim(); err != nil { - return 0, err + return err } } - gen, err := r.ChunkRemote.CASHead(ctx, expected, next) - if err == nil && expected.Epoch == 3 && r.loseClaimResponse { - return 0, errors.New("claim response lost after commit") + err := r.StartStore.UpdateHead(ctx, expected, next) + if err == nil && next.Epoch == 4 && r.loseClaimResponse { + return errors.New("claim response lost after commit") } - return gen, err + return err } func TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN(t *testing.T) { exerciseMappedHEADRestoreV3(t, false) @@ -263,8 +435,8 @@ func TestDurableProviderV3_HEADRestoreAfterLostClaimResponse(t *testing.T) { func exerciseMappedHEADRestoreV3(t *testing.T, loseClaimResponse bool) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() - source := mappedProviderV3(t, t.TempDir(), remote) + fixture := newFormatV3Fixture(t) + source := mappedProviderV3(t, t.TempDir(), fixture, formatV3View{}) st, err := source.EnsureStorage("v1") if err != nil { t.Fatal(err) @@ -291,33 +463,39 @@ func exerciseMappedHEADRestoreV3(t *testing.T, loseClaimResponse bool) { t.Fatal(err) } root := t.TempDir() - probe := &formatV3RestoreRemote{ChunkRemote: remote, loseClaimResponse: loseClaimResponse} - target := mappedProviderV3(t, root, probe) - target.view = formatV3TakeoverView{} + store, err := fixture.cat.Store(fixture.ref) + if err != nil { + t.Fatal(err) + } + probe := &formatV3RestoreRemote{StartStore: store, loseClaimResponse: loseClaimResponse} + target := mappedProviderV3(t, root, fixture, formatV3TakeoverView{}, probe) restored, err := target.EnsureStorage("v1") if err != nil { t.Fatal(err) } probe.beforeClaim = func() error { - if restored.NextLSN() != 3 { - return errors.New("HEAD takeover attempted before durable seed/rebase") + if id, _, ok := restored.(*storage.WALStore).LayoutIdentity(); !ok || id == "" { + return errors.New("HEAD takeover attempted before durable local identity") } return nil } + if loseClaimResponse { + if _, err = target.RecoverVolume(ctx, "v1"); err == nil { + t.Fatal("lost B claim reply was treated as an acknowledged claim") + } + probe.loseClaimResponse = false + } if _, err = target.RecoverVolume(ctx, "v1"); err != nil { t.Fatalf("actual mapped HEAD restore refused: %v", err) } if restored.NextLSN() != 3 { t.Fatalf("restored nextLSN=%d want3", restored.NextLSN()) } - head, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if head.RemoteLSN != 2 || head.Epoch != 4 || head.Holder != "r2" { + head := fixture.head(t) + if head.Position != 2 || head.Epoch != 4 || head.Holder != "r2" { t.Fatalf("takeover changed image/frontier: %+v", head) } - before := remote.Puts() + before := fixture.puts() check := func(p *DurableProvider, lba int64, want []byte) { t.Helper() got := make([]byte, 4096) @@ -328,7 +506,7 @@ func exerciseMappedHEADRestoreV3(t *testing.T, loseClaimResponse bool) { check(target, 5, first) check(target, 12, second) check(target, 0, make([]byte, 4096)) - if remote.Puts() != before { + if fixture.puts() != before { t.Fatal("lazy read uploaded remote chunks") } next := bytes.Repeat([]byte{0x83}, 4096) @@ -353,8 +531,7 @@ func exerciseMappedHEADRestoreV3(t *testing.T, loseClaimResponse bool) { if err = target.Close(); err != nil { t.Fatal(err) } - reopened := mappedProviderV3(t, root, remote) - reopened.view = formatV3TakeoverView{} + reopened := mappedProviderV3(t, root, fixture, formatV3TakeoverView{}) if _, err = reopened.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -370,7 +547,7 @@ func exerciseMappedHEADRestoreV3(t *testing.T, loseClaimResponse bool) { func TestDurableProviderV3_StatusTracksRecoverSyncAndCapture(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - p := mappedProviderV3(t, t.TempDir(), storage.NewMemChunkRemote()) + p := mappedProviderV3(t, t.TempDir(), newFormatV3Fixture(t), formatV3View{}) st, err := p.EnsureStorage("v1") if err != nil { t.Fatal(err) @@ -420,8 +597,8 @@ func TestDurableProviderV3_ContiguousWriteSurvivesCheckpointAndReopen(t *testing ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() root := t.TempDir() - remote := storage.NewMemChunkRemote() - p := mappedProviderV3(t, root, remote) + fixture := newFormatV3Fixture(t) + p := mappedProviderV3(t, root, fixture, formatV3View{}) st, e := p.EnsureStorage("v1") if e != nil { t.Fatal(e) @@ -445,7 +622,7 @@ func TestDurableProviderV3_ContiguousWriteSurvivesCheckpointAndReopen(t *testing if e = p.Close(); e != nil { t.Fatal(e) } - q := mappedProviderV3(t, root, remote) + q := mappedProviderV3(t, root, fixture, formatV3View{}) if _, e = q.EnsureStorage("v1"); e != nil { t.Fatal(e) } diff --git a/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go b/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go index 2f9e9ef024..0cf8072033 100644 --- a/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go +++ b/seaweed-block/core/frontend/durable/provider_frozen_budget_test.go @@ -5,25 +5,15 @@ import ( "context" "encoding/json" "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" - "sync/atomic" "testing" "time" ) -type frozenCountRemote struct { - storage.ChunkRemote - puts atomic.Int64 -} - -func (r *frozenCountRemote) Put(ctx context.Context, key string, p []byte) error { - r.puts.Add(1) - return r.ChunkRemote.Put(ctx, key, p) -} func TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits(t *testing.T) { - mem := storage.NewMemChunkRemote() - remote := &frozenCountRemote{ChunkRemote: mem} - p, _ := parkedProvider(t, remote) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p, _ := parkedLayoutProvider(t, fixture) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") if err != nil { @@ -32,12 +22,12 @@ func TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits(t *testing.T) if _, err = b.Write(context.Background(), 4096, block(0x77)); err != nil { t.Fatal(err) } - before, _ := remote.GetHead(context.Background()) - puts := remote.puts.Load() + before := layoutHead(t, fixture) + puts := fixture.Blobs.Puts() r, _, err := p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now().Add(-6 * time.Second)}) - after, _ := remote.GetHead(context.Background()) - if !errors.Is(err, storage.ErrFrozenTailTooLarge) || r.Precopy.Frozen || puts != remote.puts.Load() || before.Gen != after.Gen { - t.Fatalf("frozen refusal mutated remote: %+v %v puts=%d/%d", r.Precopy, err, puts, remote.puts.Load()) + after := layoutHead(t, fixture) + if !errors.Is(err, storage.ErrFrozenTailTooLarge) || r.Precopy.Frozen || puts != fixture.Blobs.Puts() || before.Gen != after.Gen { + t.Fatalf("frozen refusal mutated remote: %+v %v puts=%d/%d", r.Precopy, err, puts, fixture.Blobs.Puts()) } if _, err = b.Write(context.Background(), 8192, block(0x88)); err != nil { t.Fatalf("refusal stopped serving before thaw: %v", err) @@ -48,13 +38,13 @@ func TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits(t *testing.T) } original, _ := json.Marshal(r.Precopy) originalHead := r.Head.Gen - puts = remote.puts.Load() + puts = fixture.Blobs.Puts() replay, _, replayErr := p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now()}) replayJSON, _ := json.Marshal(replay.Precopy) - if replayErr != nil || replay.Head.Gen != originalHead || !bytes.Equal(original, replayJSON) || remote.puts.Load() != puts { + if replayErr != nil || replay.Head.Gen != originalHead || !bytes.Equal(original, replayJSON) || fixture.Blobs.Puts() != puts { t.Fatalf("provider replay changed original freeze report or re-uploaded: original=%s replay=%s err=%v", original, replayJSON, replayErr) } - if headBlock(t, mem, 1)[0] != 0x77 || headBlock(t, mem, 2)[0] != 0x88 { + if layoutHeadBlock(t, fixture, 1)[0] != 0x77 || layoutHeadBlock(t, fixture, 2)[0] != 0x88 { t.Fatal("final detached point lost writes") } } diff --git a/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go b/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go index 5fd481e6d3..929017059e 100644 --- a/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go +++ b/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go @@ -20,22 +20,44 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) -// Payloads live on disk so the remote fixture cannot account for a volume's +// Payloads live on disk so the B blob fixture cannot account for a volume's // worth of anonymous RSS in the process under measurement. type memoryDiskRemote struct { - *storage.MemChunkRemote dir string mu sync.Mutex - head storage.ChunkHead hashes map[string][32]byte + next uint64 firstPut sync.Once atFirstPut func() } +func memoryLayout(t *testing.T, cfg *durable.ProviderConfig, blobs *memoryDiskRemote) (*chunkstore.BCatalog, chunkstore.VolumeRef) { + t.Helper() + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), blobs, "/memory") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(context.Background(), ref, layout.Geometry{SizeBytes: uint64(cfg.NumBlocks) * uint64(cfg.BlockSize), BlockSize: uint32(cfg.BlockSize), ChunkBytes: uint64(cfg.ChunkBlocks) * uint64(cfg.BlockSize)}); err != nil { + t.Fatal(err) + } + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return cat.Store(ref) } + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + } + return cat, ref +} + // The ledger uses alternating hot/cold 4 KiB blocks and fsync after EVERY // block, not once per eight-block acknowledgement batch. Omit the packet's // 500 ms pacing so two volume-equivalents finish in a bounded diagnostic run. @@ -45,8 +67,9 @@ func TestWALStoreChunk_LedgerWriteAnonymousMemory(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 25*time.Minute) defer cancel() - r := &memoryDiskRemote{MemChunkRemote: storage.NewMemChunkRemote(), dir: t.TempDir(), hashes: make(map[string][32]byte)} - cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkCaptureInterval: 0, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }} + r := &memoryDiskRemote{dir: t.TempDir(), hashes: make(map[string][32]byte)} + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkCaptureInterval: 0} + memoryLayout(t, &cfg, r) p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) @@ -165,54 +188,34 @@ func (r *memoryDiskRemote) path(key string) string { h := sha256.Sum256([]byte(key)) return filepath.Join(r.dir, hex.EncodeToString(h[:])) } -func (r *memoryDiskRemote) Put(ctx context.Context, key string, data []byte) error { +func (r *memoryDiskRemote) Put(ctx context.Context, data []byte) (string, error) { r.firstPut.Do(func() { if r.atFirstPut != nil { r.atFirstPut() } }) if err := ctx.Err(); err != nil { - return err + return "", err } r.mu.Lock() defer r.mu.Unlock() - if _, ok := r.hashes[key]; ok { - return storage.ErrChunkKeyExists + r.next++ + id := fmt.Sprintf("needle-%d", r.next) + if err := os.WriteFile(r.path(id), data, 0600); err != nil { + return "", err } - if err := os.WriteFile(r.path(key), data, 0600); err != nil { - return err - } - r.hashes[key] = sha256.Sum256(data) - return nil + r.hashes[id] = sha256.Sum256(data) + return id, nil } func (r *memoryDiskRemote) Get(ctx context.Context, key string) ([]byte, error) { if err := ctx.Err(); err != nil { return nil, err } - return os.ReadFile(r.path(key)) -} -func (r *memoryDiskRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { - r.mu.Lock() - defer r.mu.Unlock() - return r.head, ctx.Err() -} -func (r *memoryDiskRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { - r.mu.Lock() - defer r.mu.Unlock() - if err := ctx.Err(); err != nil { - return 0, err + b, err := os.ReadFile(r.path(key)) + if os.IsNotExist(err) { + return nil, chunkstore.ErrBlobNotFound } - if expected.Gen != r.head.Gen || expected.Epoch != r.head.Epoch { - return 0, storage.ErrChunkHeadPrecondition - } - for _, ref := range next.Chunks { - if sum, ok := r.hashes[ref.Key]; !ok || sum != ref.SHA256 { - return 0, fmt.Errorf("invalid stored ref %s", ref.Key) - } - } - next.Gen = r.head.Gen + 1 - r.head = next - return next.Gen, nil + return b, err } func memoryAnonBytes() (uint64, error) { @@ -238,8 +241,8 @@ func TestWALStoreChunk_InitialWriteAnonymousMemory(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() - r := &memoryDiskRemote{MemChunkRemote: storage.NewMemChunkRemote(), dir: t.TempDir(), hashes: make(map[string][32]byte)} - cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkCaptureInterval: 0, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }} + r := &memoryDiskRemote{dir: t.TempDir(), hashes: make(map[string][32]byte)} + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkCaptureInterval: 0} if raw := os.Getenv("SWBLOCK_MEMORY_CHUNKS"); raw != "" { chunks, e := strconv.Atoi(raw) if e != nil || chunks <= 0 { @@ -252,6 +255,7 @@ func TestWALStoreChunk_InitialWriteAnonymousMemory(t *testing.T) { cfg.ChunkBlocks = uint32(cb) cfg.NumBlocks = uint32(chunks * cb) } + cat, ref := memoryLayout(t, &cfg, r) p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) @@ -412,14 +416,23 @@ func TestWALStoreChunk_InitialWriteAnonymousMemory(t *testing.T) { } t.Logf("first_cut_bytes=%d wall=%s stageRounds=%d candidates=%d", cfg.NumBlocks*4096, time.Since(cutStart), cut.Stats.StageRounds, cut.Stats.CandidateChunks) if os.Getenv("SWBLOCK_MEMORY_FULL") != "" { - head, e := r.GetHead(ctx) + head, found, e := cat.ReadHead(ctx, ref) + if e != nil || !found || head.Current == nil { + t.Fatalf("B HEAD: found=%v err=%v head=%+v", found, e, head) + } + st, e := cat.Store(ref) + if e != nil { + t.Fatal(e) + } + reader, e := layout.NewReader("/memory", ref.Dir(), st.Fetch) + if e != nil { + t.Fatal(e) + } + image, e := reader.Open(ctx, *head.Current) if e != nil { t.Fatal(e) } wantChunks := int(cfg.NumBlocks / cfg.ChunkBlocks) - if len(head.Chunks) != wantChunks { - t.Fatalf("full image references=%d, want %d", len(head.Chunks), wantChunks) - } h := sha256.New() for left := int(cfg.ChunkBlocks) * 4096; left > 0; { n := min(left, len(buf)) @@ -428,9 +441,10 @@ func TestWALStoreChunk_InitialWriteAnonymousMemory(t *testing.T) { } var want [32]byte copy(want[:], h.Sum(nil)) - for idx, ref := range head.Chunks { - if ref.SHA256 != want { - t.Fatalf("chunk %d differs from submitted bytes", idx) + for idx := 0; idx < wantChunks; idx++ { + chunk, e := image.Chunk(ctx, uint64(idx)) + if e != nil || chunk.Zero || sha256.Sum256(chunk.Data) != want { + t.Fatalf("B chunk %d differs from submitted bytes: %v", idx, e) } } } diff --git a/seaweed-block/core/frontend/durable/provider_layout.go b/seaweed-block/core/frontend/durable/provider_layout.go new file mode 100644 index 0000000000..c485d46d18 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout.go @@ -0,0 +1,169 @@ +package durable + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func initializeLayoutRoot(ws *storage.WALStore) error { + var id [16]byte + if _, err := rand.Read(id[:]); err != nil { + return err + } + return ws.SetLayoutIdentity(hex.EncodeToString(id[:]), true) +} + +// grantedLayoutLine carries the actual assignment accepted by the volume +// host. The master issues a higher epoch only after its clean proof or forced +// lease barrier; the grant is the proof, not a local clock or a HEAD read. +// layout.Start checks that a changed claim is above the HEAD it updates. +type grantedLayoutLine layout.HolderID + +func (g grantedLayoutLine) OldLeaseEnded(ctx context.Context, epoch uint64) error { + if err := ctx.Err(); err != nil { + return err + } + if g.Epoch == 0 || g.Holder == "" || g.Epoch != epoch { + return errors.New("durable: claim does not match the granted line") + } + return nil +} + +// startPath is the step a local root takes after its layout claim. +type startPath int + +const ( + startContinue startPath = iota // a non-fresh root continues from its own local data + startSeed // a fresh root seeds its frontier at HEAD's position + startAttachBase // a fresh root keeps its completed local BASE +) + +// startRoot is what the start decision reads of the local store. +type startRoot interface { + InstalledBaseLSN() (uint64, bool) + CanSeedChunkFrontier(uint64) error +} + +// canStartFrom is the one decision for the step a local root takes after its +// claim on HEAD h, with the refusal that step would give. Start asks it before +// the claim (LocalRoot.CanStartFrom) for the refusal; the attach asks it after +// the claim for the path. A completed local BASE is kept, refused only when +// HEAD is past it; another fresh root seeds at HEAD's position, refused when +// the store cannot (the seed's own precondition); a non-fresh root continues. +func canStartFrom(ws startRoot, fresh bool, h layout.Head) (startPath, error) { + if !fresh { + return startContinue, nil + } + if base, complete := ws.InstalledBaseLSN(); complete { + if h.Position > base { + return startAttachBase, errors.New("durable: completed BASE behind layout HEAD") + } + return startAttachBase, nil + } + return startSeed, ws.CanSeedChunkFrontier(h.Position) +} + +func startLayoutRoot(ctx context.Context, ws *storage.WALStore, st layout.StartStore, line layout.HolderID) (layout.Head, error) { + id, fresh, ok := ws.LayoutIdentity() + if !ok { + return layout.Head{}, errors.New("durable: legacy root has no layout identity; recreate it") + } + position, _, _ := ws.Boundaries() + h, err := layout.Start(ctx, st, grantedLayoutLine(line), line, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: uint64(ws.NumBlocks()) * uint64(ws.BlockSize()), BlockSize: uint32(ws.BlockSize()), ChunkBytes: uint64(ws.ChunkBlocks()) * uint64(ws.BlockSize())}, ClaimID: id, Fresh: fresh, Position: position, CanStartFrom: func(h layout.Head) error { _, err := canStartFrom(ws, fresh, h); return err }}) + if err != nil { + if errors.Is(err, layout.ErrNotHolder) || errors.Is(err, layout.ErrStaleEpoch) || errors.Is(err, layout.ErrPrecondition) { + // A HEAD held by another holder at our granted epoch, or any + // HEAD above it, is a final refusal. A stale local root keeps + // its own cure even when that root cannot claim this HEAD. + observed, found, readErr := st.ReadHead(ctx) + if readErr == nil && found && !errors.Is(err, layout.ErrStaleLocalRoot) && + (observed.Epoch > line.Epoch || observed.Epoch == line.Epoch && observed.Holder != line.Holder) { + err = errors.Join(err, storage.ErrChunkLayerFenced, errChunkForeignClaim) + } + } + return layout.Head{}, fmt.Errorf("durable: layout Start: %w", err) + } + return h, nil +} + +// LayoutHolder returns only the identity of the successfully attached Start. +// Pending, failed and replaced attachments provide no cleaning authority. +func (p *DurableProvider) LayoutHolder(ctx context.Context, volume string) (layout.HolderID, error) { + if err := ctx.Err(); err != nil { + return layout.HolderID{}, err + } + p.mu.Lock() + defer p.mu.Unlock() + h := p.volumes[volume] + if p.closed || h == nil || h.chunk == nil || h.layoutHolder.ClaimID == "" { + return layout.HolderID{}, ErrNotChunkVolume + } + return h.layoutHolder, nil +} + +// LayoutRemote returns the single runtime cached by a successful attachment. +// Callers must not construct another remote for the same attachment. +func (p *DurableProvider) LayoutRemote(ctx context.Context, volume string) (storage.ChunkRemote, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + p.mu.Lock() + defer p.mu.Unlock() + h := p.volumes[volume] + if p.closed || h == nil || h.chunk == nil || h.layoutHolder.ClaimID == "" || h.layoutRemote == nil { + return nil, ErrNotChunkVolume + } + return h.layoutRemote, nil +} + +type layoutBoundRemote struct { + *closeBoundRemote + keyer storage.ChunkKeyer +} + +func (r *layoutBoundRemote) ChunkKey(index uint64, sum [32]byte) string { + return r.keyer.ChunkKey(index, sum) +} + +func (r *layoutBoundRemote) Abort() { r.ChunkRemote.Abort() } + +type layoutStopRemote interface { + AbortOpenSession(context.Context) (string, error) + ReadHead(context.Context) (layout.Head, error) +} + +func settleLayoutStop(ctx context.Context, remote layoutStopRemote, me layout.HolderID) (storage.DetachSettlement, storage.ChunkCutResult, error) { + outcome, err := remote.AbortOpenSession(ctx) + if errors.Is(err, storage.ErrChunkLayerFenced) { + return storage.DetachFenced, storage.ChunkCutResult{}, nil + } + if err != nil { + return 0, storage.ChunkCutResult{}, err + } + switch outcome { + case "aborted", "idle": + return storage.DetachNotPublished, storage.ChunkCutResult{}, nil + case "detached": + h, err := remote.ReadHead(ctx) + if err != nil { + return 0, storage.ChunkCutResult{}, err + } + if h.Epoch != me.Epoch || h.Holder != me.Holder || h.ClaimID != me.ClaimID { + return storage.DetachFenced, storage.ChunkCutResult{}, nil + } + if h.State == layout.StateDetached { + return storage.DetachApplied, layoutDetachResult(h), nil + } + } + return 0, storage.ChunkCutResult{}, ErrDetachOutcomeUnknown +} + +func layoutDetachResult(h layout.Head) storage.ChunkCutResult { + return storage.ChunkCutResult{H: h.Position, Head: storage.ChunkHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.Position, State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Holder: h.Holder, Epoch: h.Epoch, Gen: h.Gen}}} +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_crash_test.go b/seaweed-block/core/frontend/durable/provider_layout_crash_test.go new file mode 100644 index 0000000000..7fe30eeb16 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_crash_test.go @@ -0,0 +1,209 @@ +package durable + +import ( + "bytes" + "context" + "errors" + "fmt" + "path/filepath" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type layoutCrashBlobs struct { + sync.Mutex + b map[string][]byte +} + +func (b *layoutCrashBlobs) Put(_ context.Context, raw []byte) (string, error) { + b.Lock() + defer b.Unlock() + id := fmt.Sprint(len(b.b) + 1) + b.b[id] = append([]byte(nil), raw...) + return id, nil +} +func (b *layoutCrashBlobs) Get(_ context.Context, id string) ([]byte, error) { + b.Lock() + defer b.Unlock() + raw, ok := b.b[id] + if !ok { + return nil, chunkstore.ErrBlobNotFound + } + return append([]byte(nil), raw...), nil +} + +type layoutCrashView struct{ epoch uint64 } + +func (v layoutCrashView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: v.epoch, EndpointVersion: 1, Healthy: true} +} + +// A fresh B root cannot legitimately contain an acknowledged guest write: +// the marker gates guest writes until Start has claimed and seeded the root. +// If a dirty root is nevertheless presented as fresh, seed's local-write +// precondition refuses it before the unclaimed HEAD can be changed. +func TestLayoutStartUnclaimedHeadRefusesFreshRootWithLocalWrites(t *testing.T) { + ctx := context.Background() + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &layoutCrashBlobs{b: map[string][]byte{}}, "/dirty-fresh") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v", ID: id} + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + st, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } + before, found, err := st.ReadHead(ctx) + if err != nil || !found || before.Epoch != 0 || before.Position != 0 { + t.Fatalf("unclaimed HEAD at zero: %+v found=%t err=%v", before, found, err) + } + ws, err := storage.CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "store"), 64, 4096, storage.WALStoreOptions{ChunkBlocks: 4}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ws.Close() }) + if _, err := ws.Write(0, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + if err := ws.SetLayoutIdentity("fresh-but-dirty", true); err != nil { + t.Fatal(err) + } + if _, err := ws.Write(1, make([]byte, 4096)); !errors.Is(err, storage.ErrLayoutFresh) { + t.Fatalf("guest write before claim: %v; want ErrLayoutFresh", err) + } + if _, err := startLayoutRoot(ctx, ws, st, layout.HolderID{Epoch: 1, Holder: "s/r"}); !errors.Is(err, layout.ErrCannotStartFrom) { + t.Fatalf("dirty fresh root: %v; want ErrCannotStartFrom", err) + } + after, found, err := st.ReadHead(ctx) + if err != nil || !found || after.Gen != before.Gen || after.Epoch != 0 || after.ClaimID != "" || after.Position != 0 { + t.Fatalf("refused Start changed HEAD: before=%+v after=%+v found=%t err=%v", before, after, found, err) + } +} + +func TestLayoutStartCrashAtEachDurableArrow(t *testing.T) { + for _, restore := range []bool{false, true} { + for _, point := range []string{"identity", "claim", "base", "fresh clear"} { + t.Run(fmt.Sprintf("restore=%v/%s", restore, point), func(t *testing.T) { + ctx := context.Background() + f := chunkstore.NewMemFiler() + cat, err := chunkstore.NewBCatalog(f, &layoutCrashBlobs{b: map[string][]byte{}}, "/crash") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v", ID: id} + if _, err = cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + makeP := func(root string, epoch uint64) (*DurableProvider, *storage.WALStore) { + t.Helper() + p, err := NewDurableProvider(ProviderConfig{Impl: ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r", ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return cat.Store(ref) }, ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + }}, layoutCrashView{epoch}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v") + if err != nil { + t.Fatal(err) + } + return p, s.(*storage.WALStore) + } + epoch := uint64(1) + want := make([]byte, 4096) + if restore { + source, ws := makeP(t.TempDir(), 1) + if _, err = source.RecoverVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + want = bytes.Repeat([]byte{'A'}, 4096) + if _, err = ws.Write(0, want); err != nil { + t.Fatal(err) + } + if _, err = ws.Sync(); err != nil { + t.Fatal(err) + } + if _, err = source.CutVolume(ctx, "v", 0); err != nil { + t.Fatal(err) + } + if err = source.Close(); err != nil { + t.Fatal(err) + } + epoch = 2 + } + root := t.TempDir() + p, ws := makeP(root, epoch) + claim, fresh, ok := ws.LayoutIdentity() + if !ok || !fresh || claim == "" { + t.Fatal("identity not durable before Start") + } + crash := errors.New("fixture: interrupted at " + point) + switch point { + case "identity": + p.cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return nil, crash } + case "claim": + p.cfg.ChunkLayoutRemoteFor = func(string, layout.HolderID) (storage.ChunkRemote, error) { return nil, crash } + case "base": + p.testBeforeChunkFreshRetire = func() error { return crash } + case "fresh clear": + p.testAfterChunkFreshRetire = func() error { return crash } + } + if _, err = p.RecoverVolume(ctx, "v"); !errors.Is(err, crash) { + t.Fatalf("interruption: %v", err) + } + if err := p.volumes["v"].backend.readyCheck(); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("interrupted Start admitted guest I/O: %v", err) + } + _, fresh, _ = ws.LayoutIdentity() + if fresh != (point != "fresh clear") { + t.Fatalf("fresh=%v at %s", fresh, point) + } + if fresh { + if _, err = ws.Write(0, want); !errors.Is(err, storage.ErrLayoutFresh) { + t.Fatalf("guest write before durable clear: %v", err) + } + } + if err = p.Close(); err != nil { + t.Fatal(err) + } + reopened, ws := makeP(root, epoch) + if got, _, _ := ws.LayoutIdentity(); got != claim { + t.Fatal("restart minted a second claim id") + } + if _, err = reopened.RecoverVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + if _, fresh, _ = ws.LayoutIdentity(); fresh { + t.Fatal("Start served before fresh clear") + } + got := make([]byte, 4096) + n, err := reopened.volumes["v"].backend.Read(ctx, 0, got) + if err != nil || n != len(got) || !bytes.Equal(got, want) { + t.Fatalf("guest base read: n=%d err=%v bytes match=%v", n, err, bytes.Equal(got, want)) + } + if n, err := reopened.volumes["v"].backend.Write(ctx, 4096, bytes.Repeat([]byte{'B'}, 4096)); err != nil || n != 4096 { + t.Fatalf("guest write after Start: n=%d err=%v", n, err) + } + if _, err = ws.Sync(); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_fixture_test.go b/seaweed-block/core/frontend/durable/provider_layout_fixture_test.go new file mode 100644 index 0000000000..f60b94eb88 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_fixture_test.go @@ -0,0 +1,106 @@ +package durable_test + +import ( + "context" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// layoutCase keeps the store and its volume identity across provider restarts. +type layoutCase struct { + cat *chunkstore.BCatalog + ref chunkstore.VolumeRef + blobs *layoutProviderBlobs +} + +func newLayoutCase(t *testing.T, blocks, chunkBlocks uint64) *layoutCase { + t.Helper() + blobs := &layoutProviderBlobs{blobs: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), blobs, "/layout-fixture") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(context.Background(), ref, layout.Geometry{SizeBytes: blocks * 4096, BlockSize: 4096, ChunkBytes: chunkBlocks * 4096}); err != nil { + t.Fatal(err) + } + return &layoutCase{cat: cat, ref: ref, blobs: blobs} +} + +func (c *layoutCase) provider(t *testing.T, root string, view *stubView, holder string, configure func(*durable.ProviderConfig)) *durable.DurableProvider { + t.Helper() + vol, err := c.cat.ReadVolume(context.Background(), c.ref) + if err != nil { + t.Fatal(err) + } + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: uint32(vol.Geometry.SizeBytes / 4096), BlockSize: 4096, ChunkBlocks: uint32(vol.Geometry.ChunkBytes / 4096), ChunkHolder: holder, + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return c.cat.Store(c.ref) }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(c.cat, c.ref, me) + }, + } + if configure != nil { + configure(&cfg) + } + p, err := durable.NewDurableProvider(cfg, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p +} + +func (c *layoutCase) head(t *testing.T) layout.Head { + t.Helper() + h, found, err := c.cat.ReadHead(context.Background(), c.ref) + if err != nil || !found { + t.Fatalf("layout HEAD: found=%v err=%v", found, err) + } + return h +} + +func (c *layoutCase) block(t *testing.T, lba uint32) []byte { + t.Helper() + h := c.head(t) + if h.Current == nil { + return make([]byte, 4096) + } + st, err := c.cat.Store(c.ref) + if err != nil { + t.Fatal(err) + } + r, err := layout.NewReader("/layout-fixture", c.ref.Dir(), st.Fetch) + if err != nil { + t.Fatal(err) + } + img, err := r.Open(context.Background(), *h.Current) + if err != nil { + t.Fatal(err) + } + chunk, err := img.Chunk(context.Background(), uint64(lba)/(hGeometryChunkBlocks(c, t))) + if err != nil { + t.Fatal(err) + } + if chunk.Zero { + return make([]byte, 4096) + } + off := int(uint64(lba)%hGeometryChunkBlocks(c, t)) * 4096 + return chunk.Data[off : off+4096] +} + +func hGeometryChunkBlocks(c *layoutCase, t *testing.T) uint64 { + t.Helper() + v, err := c.cat.ReadVolume(context.Background(), c.ref) + if err != nil { + t.Fatal(err) + } + return v.Geometry.ChunkBytes / 4096 +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_plain_replay_test.go b/seaweed-block/core/frontend/durable/provider_layout_plain_replay_test.go new file mode 100644 index 0000000000..6a300f4523 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_plain_replay_test.go @@ -0,0 +1,240 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" + "time" +) + +func TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &layoutProviderBlobs{blobs: map[string][]byte{}}, "/plain-replay") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + dir := t.TempDir() + view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})) + var proofErr error + var absent, foreign bool + var proofReads int + var onProofRead func() + open := func() (*durable.DurableProvider, *storage.WALStore) { + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: dir, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r1", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { + st, err := cat.Store(ref) + if err != nil { + return nil, err + } + return &layoutReplayFault{StartStore: st, err: &proofErr, absent: &absent, foreign: &foreign, reads: &proofReads, onRead: &onProofRead}, nil + }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + return p, s.(*storage.WALStore) + } + p, ws := open() + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if _, err := ws.Write(0, bytes.Repeat([]byte{'A'}, 4096)); err != nil { + t.Fatal(err) + } + if _, err := ws.Sync(); err != nil { + t.Fatal(err) + } + first, last, err := p.DetachVolumePlain(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if first.Head.State != storage.ChunkHeadDetached || first.H != last { + t.Fatalf("detach proof %+v last=%d", first, last) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + restarted, _ := open() + if _, err := restarted.RecoverVolume(ctx, "v1"); !errors.Is(err, layout.ErrDetached) { + t.Fatalf("same epoch restart: %v", err) + } + beforeReplayReads := proofReads + replay, again, err := restarted.DetachVolumePlain(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if replay.Head.Gen != first.Head.Gen || replay.H != first.H || again != last { + t.Fatalf("replay changed detached proof: %+v %d", replay, again) + } + if proofReads <= beforeReplayReads { + t.Fatal("replay did not read the B HEAD") + } + for _, mode := range []string{"unreadable", "absent", "foreign"} { + proofErr = nil + absent = false + foreign = false + switch mode { + case "unreadable": + proofErr = errors.New("fixture filer unavailable") + case "absent": + absent = true + case "foreign": + foreign = true + } + if _, _, err := restarted.DetachVolumePlain(ctx, "v1"); err == nil { + t.Fatalf("%s detached proof returned cached success", mode) + } + } + proofErr, absent, foreign = nil, false, false + initial := view.Projection() + onProofRead = func() { + moved := initial + moved.EndpointVersion++ + view.set(moved) + } + if _, _, err := restarted.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrChunkEpochStale) { + t.Fatalf("replay ignored authority movement during B HEAD read: %v", err) + } + onProofRead = nil + view.set(initial) + ended, end := context.WithCancel(ctx) + end() + if _, _, err := restarted.DetachVolumePlain(ended, "v1"); !errors.Is(err, context.Canceled) { + t.Fatalf("replay hid caller cancellation: %v", err) + } + if err := restarted.Close(); err != nil { + t.Fatal(err) + } + if _, _, err := restarted.DetachVolumePlain(ctx, "v1"); err == nil { + t.Fatal("closed provider replayed a seal") + } + +} + +type lostLayoutDetachAnswer struct { + *chunkstore.LayoutRemote + lose bool + lostCommitted bool +} + +func (r *lostLayoutDetachAnswer) CASHead(ctx context.Context, version storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + gen, err := r.LayoutRemote.CASHead(ctx, version, next) + if err == nil && r.lose && next.State == storage.ChunkHeadDetached { + r.lostCommitted = true + return 0, errors.New("fixture: detached commit reply lost") + } + return gen, err +} + +func (r *lostLayoutDetachAnswer) GetHead(ctx context.Context) (storage.ChunkHead, error) { + if r.lostCommitted { + return storage.ChunkHead{}, errors.New("fixture: committed HEAD readback unavailable") + } + return r.LayoutRemote.GetHead(ctx) +} + +func (r *lostLayoutDetachAnswer) AbortOpenSession(ctx context.Context) (string, error) { + if r.lose { + return "", errors.New("fixture: settlement read unavailable") + } + return r.LayoutRemote.AbortOpenSession(ctx) +} + +func TestLayoutPlainDetachLostReplyRestartReplaysProof(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + c := newLayoutCase(t, 64, 4) + root := t.TempDir() + first := c.provider(t, root, v1View(), "s/r1", func(cfg *durable.ProviderConfig) { + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + r, err := chunkstore.NewLayoutRemote(c.cat, c.ref, me) + if err != nil { + return nil, err + } + return &lostLayoutDetachAnswer{LayoutRemote: r, lose: true}, nil + } + }) + ws := openRecovered(t, first) + if _, err := ws.Write(0, bytes.Repeat([]byte{'Z'}, 4096)); err != nil { + t.Fatal(err) + } + if _, err := ws.Sync(); err != nil { + t.Fatal(err) + } + if _, _, err := first.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("committed seal with lost reply was decided without proof: %v", err) + } + sealed := c.head(t) + if sealed.State != layout.StateDetached { + t.Fatalf("lost reply did not commit: %+v", sealed) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + restarted := c.provider(t, root, v1View(), "s/r1", nil) + if _, err := restarted.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := restarted.RecoverVolume(ctx, "v1"); !errors.Is(err, layout.ErrDetached) { + t.Fatalf("same epoch served after seal: %v", err) + } + replay, last, err := restarted.DetachVolumePlain(ctx, "v1") + if err != nil || replay.Head.Gen != sealed.Gen || replay.H != sealed.Position || last != sealed.Position { + t.Fatalf("replay did not return the committed B proof: %+v last=%d err=%v", replay, last, err) + } + if got := c.head(t); got.Gen != sealed.Gen || got.State != layout.StateDetached { + t.Fatalf("replay wrote HEAD: %+v", got) + } + if !bytes.Equal(c.block(t, 0), bytes.Repeat([]byte{'Z'}, 4096)) { + t.Fatal("replay lost the acknowledged write") + } +} + +type layoutReplayFault struct { + layout.StartStore + err *error + absent, foreign *bool + reads *int + onRead *func() +} + +func (s *layoutReplayFault) ReadHead(ctx context.Context) (layout.Head, bool, error) { + *s.reads++ + if *s.onRead != nil { + (*s.onRead)() + } + if *s.err != nil { + return layout.Head{}, false, *s.err + } + if *s.absent { + return layout.Head{}, false, nil + } + h, found, err := s.StartStore.ReadHead(ctx) + if *s.foreign { + h.ClaimID = "foreign" + } + return h, found, err +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_restart_test.go b/seaweed-block/core/frontend/durable/provider_layout_restart_test.go new file mode 100644 index 0000000000..afea9eb00a --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_restart_test.go @@ -0,0 +1,171 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" + "sync" + "testing" + "time" +) + +type restartStartStore struct { + layout.StartStore + failClosure bool + closureSeen bool +} + +func (s *restartStartStore) UpdateHead(ctx context.Context, gen uint64, next layout.Head) error { + if next.Activity.Kind == layout.ActIdle && s.failClosure { + s.closureSeen = true + return errors.New("fixture: conditional Start closure failed") + } + if next.Activity.Kind == layout.ActIdle { + s.closureSeen = true + } + return s.StartStore.UpdateHead(ctx, gen, next) +} + +type heldRestartDetach struct { + layout.StartStore + held, release chan struct{} +} + +func (s *heldRestartDetach) UpdateHead(ctx context.Context, gen uint64, next layout.Head) error { + if next.State == layout.StateDetached { + close(s.held) + <-s.release + } + return s.StartStore.UpdateHead(ctx, gen, next) +} + +// This uses the real provider open/close/reopen and kernel commit paths; +// process SIGKILL/systemd qualification is a separate real-cluster gate. +func TestLayoutRestartClosesActivityBeforeGuestWrites(t *testing.T) { + for _, abortFails := range []bool{false, true} { + t.Run(map[bool]string{false: "held detach", true: "Start closure failure"}[abortFails], func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &layoutProviderBlobs{blobs: map[string][]byte{}}, "/restart") + if err != nil { + t.Fatal(err) + } + id, _ := layout.NewVolumeID() + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + g := layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096} + if _, err := cat.CreateVolume(ctx, ref, g); err != nil { + t.Fatal(err) + } + st, _ := cat.Store(ref) + dir, locks := t.TempDir(), t.TempDir() + view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})) + startStore := &restartStartStore{StartStore: st} + open := func(root string) (*durable.DurableProvider, *storage.WALStore) { + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r1", HostVolumeLock: true, VolumeLockDirTestOnly: locks, + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return startStore, nil }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + return p, s.(*storage.WALStore) + } + old, ws := open(dir) + claim, _, _ := ws.LayoutIdentity() + me := layout.HolderID{Epoch: 1, Holder: "s/r1", ClaimID: claim} + if _, err := layout.Start(ctx, st, restartLease{}, me, layout.LocalRoot{Geometry: g, ClaimID: claim, Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + if _, err := layout.RunBegin(ctx, st, me, "old-stop"); err != nil { + t.Fatal(err) + } + root, _, _ := layout.Build(nil) + rn, raw, _ := layout.NameRoot(root) + if err := layout.EnsureObject(ctx, st, rn.Path(), raw, "old-stop"); err != nil { + t.Fatal(err) + } + held := &heldRestartDetach{StartStore: st, held: make(chan struct{}), release: make(chan struct{})} + var once sync.Once + release := func() { once.Do(func() { close(held.release) }) } + defer release() + done := make(chan error, 1) + go func() { + _, err := layout.RunCommit(ctx, held, st, "v1", me, layout.CommitRequest{Session: "old-stop", State: layout.StateDetached}) + done <- err + }() + select { + case <-held.held: + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + if err := old.Close(); err != nil { + t.Fatal(err) + } // releases local store + host lock + startStore.closureSeen = false + startStore.failClosure = abortFails + p, newWS := open(dir) + _, err = p.RecoverVolume(ctx, "v1") + if !startStore.closureSeen { + t.Fatal("Start did not conditionally close the old activity") + } + if abortFails { + if err == nil { + t.Fatal("failed Start closure allowed attach") + } + if _, err := newWS.Write(0, bytes.Repeat([]byte{'B'}, 4096)); !errors.Is(err, storage.ErrLayoutFresh) { + t.Fatal("failed attach enabled writes", err) + } + release() + <-done + return + } + if err != nil { + t.Fatal(err) + } + if _, err := newWS.Write(0, bytes.Repeat([]byte{'B'}, 4096)); err != nil { + t.Fatal(err) + } + if _, err := newWS.Sync(); err != nil { + t.Fatal(err) + } + release() + if err := <-done; !errors.Is(err, layout.ErrPrecondition) { + t.Fatal("late detached commit was accepted", err) + } + h, found, err := st.ReadHead(ctx) + if err != nil || !found || h.State != layout.StateLive { + t.Fatal("HEAD did not stay live", h.State, err) + } + if _, _, err := p.DetachVolumePlain(ctx, "v1"); err != nil { + t.Fatal(err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 2})) + successor, targetWS := open(t.TempDir()) + if _, err := successor.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if got, err := targetWS.Read(0); err != nil || !bytes.Equal(got, bytes.Repeat([]byte{'B'}, 4096)) { + t.Fatal("acknowledged write lost across clean successor", err) + } + }) + } +} + +type restartLease struct{} + +func (restartLease) OldLeaseEnded(context.Context, uint64) error { return nil } diff --git a/seaweed-block/core/frontend/durable/provider_layout_same_host_clean_test.go b/seaweed-block/core/frontend/durable/provider_layout_same_host_clean_test.go new file mode 100644 index 0000000000..c6cfcc9444 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_same_host_clean_test.go @@ -0,0 +1,62 @@ +package durable_test + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// The authority's same-host clean-move test proves the detached HEAD and ACK +// admit epoch+1. This B-path test proves that the successor on that same +// host actually serves the sealed image, rather than its new empty root. +func TestLayoutSameHostCleanSuccessorReadsSealedImage(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + c := newLayoutCase(t, 64, 4) + locks := t.TempDir() + configure := func(cfg *durable.ProviderConfig) { + cfg.HostVolumeLock = true + cfg.VolumeLockDirTestOnly = locks + } + old := c.provider(t, t.TempDir(), v1View(), "node-a/r1", configure) + s := openRecovered(t, old) + want0, want3 := block(0x31), block(0x73) + writeSync(t, s, 0, 0x31) + writeSync(t, s, 3, 0x73) + sealed, _, err := old.DetachVolumePlain(ctx, "v1") + if err != nil || sealed.Head.State != storage.ChunkHeadDetached || sealed.H < 2 { + t.Fatalf("clean seal: %+v %v", sealed, err) + } + head := c.head(t) + if head.State != layout.StateDetached || head.Current == nil || head.Position != sealed.H || head.Holder != "node-a/r1" || head.Epoch != 3 { + t.Fatalf("B HEAD did not retain the sealed image: %+v", head) + } + if err := old.Close(); err != nil { + t.Fatal(err) + } + // A new root and the same holder name make this specifically a same-host + // clean successor, not an own-epoch restart reading its old local WAL. + next := c.provider(t, t.TempDir(), viewAs("r1", 4), "node-a/r1", configure) + loaded, err := next.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err := next.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("same-host clean successor did not Start from the seal: %v", err) + } + for lba, want := range map[uint32][]byte{0: want0, 3: want3} { + got, err := loaded.Read(lba) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("same-host successor LBA %d: err=%v matches sealed bytes=%t", lba, err, bytes.Equal(got, want)) + } + } + after := c.head(t) + if after.State != layout.StateLive || after.Epoch != 4 || after.Holder != "node-a/r1" || after.ClaimID == head.ClaimID || after.Position != head.Position { + t.Fatalf("same-host successor did not consume the sealed lineage: before=%+v after=%+v", head, after) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_snapshot.go b/seaweed-block/core/frontend/durable/provider_layout_snapshot.go new file mode 100644 index 0000000000..de76dc7132 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_snapshot.go @@ -0,0 +1,78 @@ +package durable + +import ( + "context" + "fmt" + "sync" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// layoutSnapshotter is the named-snapshot surface of the attached layout +// remote (chunkstore.LayoutRemote). +type layoutSnapshotter interface { + SetSnapshot(name string, meta layout.SnapshotMeta) + DropSnapshot() + TakeSnapshotErr() error + CommitPendingSnapshot(ctx context.Context) error + ReadHead(ctx context.Context) (layout.Head, error) +} + +// snapshotLocks serializes named snapshots of one volume, so one request's +// name is never committed by another's cut. +var snapshotLocks sync.Map // volume -> *sync.Mutex + +// SnapshotVolume takes a named snapshot of the volume through its attached +// layout runtime: the name and its retention facts ride on the next cut's +// commit (the engine's barrier gives the image at H); when the cut had +// nothing to publish, the current image is named by a commit of its own. +// A replay of a name already in HEAD returns the facts recorded there. A +// name or facts the kernel refuses is the typed refusal; the cut itself +// still commits unnamed. It returns HEAD with the name recorded +// (chunkstore.SnapshotInfoFromHead makes the request's answer). +func (p *DurableProvider) SnapshotVolume(ctx context.Context, volumeID, name string, meta layout.SnapshotMeta) (layout.Head, error) { + if err := layout.CheckSnapshot(name, meta); err != nil { + return layout.Head{}, err + } + r, err := p.LayoutRemote(ctx, volumeID) + if err != nil { + return layout.Head{}, err + } + sr, ok := r.(layoutSnapshotter) + if !ok { + return layout.Head{}, fmt.Errorf("durable: the remote of %s is not a layout runtime", volumeID) + } + mu, _ := snapshotLocks.LoadOrStore(volumeID, &sync.Mutex{}) + mu.(*sync.Mutex).Lock() + defer mu.(*sync.Mutex).Unlock() + + h, err := sr.ReadHead(ctx) + if err != nil { + return layout.Head{}, err + } + if _, ok := h.Snapshots[name]; ok { + return h, nil + } + sr.SetSnapshot(name, meta) + // A request that fails withdraws its name: the cut may keep its session + // for a retry, and the name must not ride onto that later image. + if _, err := p.CutVolume(ctx, volumeID, 0); err != nil { + sr.DropSnapshot() + return layout.Head{}, err + } + if err := sr.TakeSnapshotErr(); err != nil { + sr.DropSnapshot() + return layout.Head{}, err + } + if err := sr.CommitPendingSnapshot(ctx); err != nil { + sr.DropSnapshot() + return layout.Head{}, err + } + if h, err = sr.ReadHead(ctx); err != nil { + return layout.Head{}, err + } + if _, ok := h.Snapshots[name]; !ok { + return layout.Head{}, fmt.Errorf("durable: snapshot %q of %s is not in HEAD after its commit", name, volumeID) + } + return h, nil +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_snapshot_test.go b/seaweed-block/core/frontend/durable/provider_layout_snapshot_test.go new file mode 100644 index 0000000000..f5a288ea34 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_snapshot_test.go @@ -0,0 +1,196 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// SnapshotVolume through the attached layout runtime: a named snapshot of +// written data is in HEAD with its facts; a replay returns those facts; a +// snapshot of an image with nothing new to publish is still named (its own +// commit); a name the kernel refuses is the typed refusal. +func TestLayoutProviderSnapshotVolume(t *testing.T) { + ctx := context.Background() + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &layoutProviderBlobs{blobs: map[string][]byte{}}, "/layout-test") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + v := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err = cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r1", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return cat.Store(v) }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, v, me) + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ws := s.(*storage.WALStore) + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if _, err = ws.Write(0, bytes.Repeat([]byte{'A'}, 4096)); err != nil { + t.Fatal(err) + } + if _, err = ws.Sync(); err != nil { + t.Fatal(err) + } + head := func() layout.Head { + h, _, err := cat.ReadHead(ctx, v) + if err != nil { + t.Fatal(err) + } + return h + } + meta := layout.SnapshotMeta{CreatedNs: 11, Class: layout.ClassSemantic, Labels: map[string]string{"k": "v"}} + hd, err := p.SnapshotVolume(ctx, "v1", "daily", meta) + if err != nil { + t.Fatalf("snapshot: %v", err) + } + info := chunkstore.SnapshotInfoFromHead("v1", "daily", hd) + h := head() + sn, ok := h.Snapshots["daily"] + if !ok || sn.Meta.CreatedNs != 11 || sn.Meta.Labels["k"] != "v" || info.Name != "daily" || info.CreatedNs != 11 || info.CutLSN != h.Position || info.Root != sn.Root.String() { + t.Fatalf("snapshot daily: info %+v, HEAD %+v", info, sn) + } + if again, err := p.SnapshotVolume(ctx, "v1", "daily", layout.SnapshotMeta{CreatedNs: 99}); err != nil || again.Snapshots["daily"].Meta.CreatedNs != 11 { + t.Fatalf("replay: %+v %v; want the recorded facts", again, err) + } + // Nothing new written: the name still lands on the current image. + if _, err := p.SnapshotVolume(ctx, "v1", "same", layout.SnapshotMeta{CreatedNs: 12}); err != nil { + t.Fatalf("snapshot of an unchanged image: %v", err) + } + h2 := head() + if s2, ok := h2.Snapshots["same"]; !ok || s2.Root != h2.Snapshots["daily"].Root || h2.Activity.Kind != layout.ActIdle { + t.Fatalf("unchanged image snapshot: %+v", h2) + } + if _, err := p.SnapshotVolume(ctx, "v1", strings.Repeat("n", layout.MaxSnapshotNameBytes+1), layout.SnapshotMeta{}); !errors.Is(err, layout.ErrMalformed) { + t.Fatalf("too-long name: %v; want ErrMalformed", err) + } + // The cap: snapshots up to it are named; past it, the cut still commits + // (new data reaches HEAD, unnamed) and the request gets the typed error. + for i := len(head().Snapshots); i < layout.MaxSnapshots; i++ { + if _, err := p.SnapshotVolume(ctx, "v1", "s"+string(rune('a'+i)), layout.SnapshotMeta{CreatedNs: int64(20 + i)}); err != nil { + t.Fatalf("snapshot %d: %v", i+1, err) + } + } + before := head() + if _, err = ws.Write(1, bytes.Repeat([]byte{'B'}, 4096)); err != nil { + t.Fatal(err) + } + if _, err = ws.Sync(); err != nil { + t.Fatal(err) + } + if _, err := p.SnapshotVolume(ctx, "v1", "over", layout.SnapshotMeta{CreatedNs: 50}); !errors.Is(err, layout.ErrTooManySnapshots) { + t.Fatalf("snapshot past the cap: %v; want ErrTooManySnapshots", err) + } + after := head() + if _, named := after.Snapshots["over"]; named || after.Position <= before.Position || *after.Current == *before.Current { + t.Fatalf("past the cap: named %t, position %d -> %d; want the cut committed unnamed", named, before.Position, after.Position) + } + // A replay after later cuts answers with the facts recorded when the + // name was taken, not HEAD's current position or root. + again, err := p.SnapshotVolume(ctx, "v1", "daily", layout.SnapshotMeta{CreatedNs: 99}) + if err != nil { + t.Fatalf("replay after later cuts: %v", err) + } + if ri := chunkstore.SnapshotInfoFromHead("v1", "daily", again); ri.CutLSN != info.CutLSN || ri.Root != info.Root || ri.CreatedNs != 11 || ri.CutLSN == again.Position { + t.Fatalf("replay after later cuts: cut %d root %s created %d; want the recorded cut %d root %s (HEAD now at %d)", ri.CutLSN, ri.Root, ri.CreatedNs, info.CutLSN, info.Root, again.Position) + } +} + +// A snapshot request whose cut fails returns the error and withdraws its +// name: the cut keeps its session and staged uploads for its retry, and +// that later cut must not name the image the requester was told was not +// taken. +func TestLayoutProviderFailedSnapshotNamesNoLaterImage(t *testing.T) { + ctx := context.Background() + blobs := &layoutProviderBlobs{blobs: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), blobs, "/layout-test") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + v := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err = cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r1", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return cat.Store(v) }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, v, me) + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ws := s.(*storage.WALStore) + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if _, err = ws.Write(0, bytes.Repeat([]byte{'A'}, 4096)); err != nil { + t.Fatal(err) + } + if _, err = ws.Sync(); err != nil { + t.Fatal(err) + } + blobs.Lock() + blobs.fail = errors.New("blob store down") + blobs.Unlock() + shortCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + if _, err := p.SnapshotVolume(shortCtx, "v1", "weekly", layout.SnapshotMeta{CreatedNs: 7}); err == nil { + t.Fatal("a snapshot whose cut could not upload succeeded") + } + blobs.Lock() + blobs.fail = nil + blobs.Unlock() + if _, err = ws.Write(1, bytes.Repeat([]byte{'B'}, 4096)); err != nil { + t.Fatal(err) + } + if _, err = ws.Sync(); err != nil { + t.Fatal(err) + } + if _, err := p.CutVolume(ctx, "v1", 0); err != nil { + t.Fatalf("the later cut: %v", err) + } + h, _, err := cat.ReadHead(ctx, v) + if err != nil { + t.Fatal(err) + } + if _, named := h.Snapshots["weekly"]; named { + t.Fatalf("the failed request's name rode onto a later cut: %+v", h.Snapshots) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_start_class_test.go b/seaweed-block/core/frontend/durable/provider_layout_start_class_test.go new file mode 100644 index 0000000000..85f1e65a72 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_start_class_test.go @@ -0,0 +1,46 @@ +package durable + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// Start's definite refusals end this recovery; a read failure or a CAS +// precondition can be retried. Detached uses the replay-retained branch. +func TestFinalLayoutStartRefusalTable(t *testing.T) { + for _, tc := range []struct { + name string + err error + final bool + }{ + {"stale local root", layout.ErrStaleLocalRoot, true}, + {"missing local root", layout.ErrMissingLocalRoot, true}, + {"geometry", layout.ErrGeometryMismatch, true}, + {"absent HEAD", layout.ErrHeadAbsent, true}, + {"deleting", layout.ErrVolumeDeleting, true}, + {"stale epoch", layout.ErrStaleEpoch, true}, + {"another holder", layout.ErrNotHolder, true}, + {"foreign volume", layout.ErrIdentity, true}, + {"corrupt store", layout.ErrCorrupt, true}, + {"malformed store", layout.ErrMalformed, true}, + {"missing VOLUME", layout.ErrMissing, true}, + {"oversized HEAD", layout.ErrHeadTooLarge, true}, + {"legacy store", chunkstore.ErrLegacyStore, true}, + {"CAS precondition", layout.ErrPrecondition, false}, + {"busy", layout.ErrBusy, false}, + {"unanswered read", context.DeadlineExceeded, false}, + {"detached replay", layout.ErrDetached, false}, + {"other error", errors.New("network"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := finalLayoutStartRefusal(fmt.Errorf("Start: %w", tc.err)); got != tc.final { + t.Fatalf("final=%t, want %t", got, tc.final) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_stop_race_test.go b/seaweed-block/core/frontend/durable/provider_layout_stop_race_test.go new file mode 100644 index 0000000000..d3d1ec8404 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_stop_race_test.go @@ -0,0 +1,67 @@ +package durable + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" +) + +type stopRemoteProbe struct { + outcome string + err error + head layout.Head + readErr error + aborted bool +} + +func (r *stopRemoteProbe) AbortOpenSession(context.Context) (string, error) { + r.aborted = true + return r.outcome, r.err +} +func (r *stopRemoteProbe) ReadHead(context.Context) (layout.Head, error) { + if !r.aborted { + panic("read before session settlement") + } + return r.head, r.readErr +} + +// Kernel-CAS races are exercised through the real remote by +// TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit. This probe +// checks that provider settlement consumes that single decision before resume. +func TestLayoutStopAbortMustConfirmItsOutcome(t *testing.T) { + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + for _, tc := range []struct { + name, outcome string + err error + want storage.DetachSettlement + bad bool + }{ + {"aborted", "aborted", nil, storage.DetachNotPublished, false}, + {"idle", "idle", nil, storage.DetachNotPublished, false}, + {"detached", "detached", nil, storage.DetachApplied, false}, + {"fenced", "", storage.ErrChunkLayerFenced, storage.DetachFenced, false}, + {"absent", "", layout.ErrHeadAbsent, 0, true}, + {"unknown abort", "", errors.New("reply lost"), 0, true}, + {"unknown outcome", "unexpected", nil, 0, true}, + } { + t.Run(tc.name, func(t *testing.T) { + r := &stopRemoteProbe{outcome: tc.outcome, err: tc.err, head: layout.Head{Gen: 7, Epoch: 1, Holder: "s/r", ClaimID: "k", State: layout.StateDetached, Position: 11}} + got, result, err := settleLayoutStop(context.Background(), r, me) + if !r.aborted || (err != nil) != tc.bad || (!tc.bad && got != tc.want) { + t.Fatalf("got=%v err=%v aborted=%v", got, err, r.aborted) + } + if got == storage.DetachApplied && (result.H != 11 || result.Head.Gen != 7) { + t.Fatalf("detached proof: %+v", result) + } + }) + } + for _, head := range []layout.Head{{Epoch: 2, Holder: "s/r", ClaimID: "new", State: layout.StateDetached}, {Epoch: 1, Holder: "s/r", ClaimID: "k", State: layout.StateLive}} { + r := &stopRemoteProbe{outcome: "detached", head: head} + got, _, err := settleLayoutStop(context.Background(), r, me) + if err == nil && got != storage.DetachFenced { + t.Fatal("changed HEAD permitted resume", got, err) + } + } +} diff --git a/seaweed-block/core/frontend/durable/provider_layout_test.go b/seaweed-block/core/frontend/durable/provider_layout_test.go new file mode 100644 index 0000000000..13abeb7094 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_test.go @@ -0,0 +1,220 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "fmt" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type layoutProviderBlobs struct { + sync.Mutex + blobs map[string][]byte + fail error // Put fails with it while set +} + +func (b *layoutProviderBlobs) Put(_ context.Context, raw []byte) (string, error) { + b.Lock() + defer b.Unlock() + if b.fail != nil { + return "", b.fail + } + id := fmt.Sprint(len(b.blobs) + 1) + b.blobs[id] = append([]byte(nil), raw...) + return id, nil +} +func (b *layoutProviderBlobs) Get(_ context.Context, id string) ([]byte, error) { + b.Lock() + defer b.Unlock() + raw, ok := b.blobs[id] + if !ok { + return nil, chunkstore.ErrBlobNotFound + } + return append([]byte(nil), raw...), nil +} + +func TestLayoutProviderRefusesEmptyOwnEpochAndRemountedOldRoot(t *testing.T) { + ctx := context.Background() + f := chunkstore.NewMemFiler() + cat, err := chunkstore.NewBCatalog(f, &layoutProviderBlobs{blobs: map[string][]byte{}}, "/layout-test") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + v := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err = cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1})) + remoteCalls := 0 + var createdRemote storage.ChunkRemote + lostReply := false + makeProvider := func(root string) (*durable.DurableProvider, *storage.WALStore) { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r1", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { + st, err := cat.Store(v) + if err != nil { + return nil, err + } + return &layoutLostClaimReply{StartStore: st, lose: &lostReply}, nil + }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + remoteCalls++ + r, err := chunkstore.NewLayoutRemote(cat, v, me) + createdRemote = r + return r, err + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + return p, s.(*storage.WALStore) + } + oldRoot := t.TempDir() + p, ws := makeProvider(oldRoot) + claim, fresh, ok := ws.LayoutIdentity() + if !ok || !fresh || claim == "" { + t.Fatalf("identity not durable before claim: %q %v %v", claim, fresh, ok) + } + lostReply = true + if _, err = p.RecoverVolume(ctx, "v1"); err == nil { + t.Fatal("claim reply loss not observed") + } + if got, _, _ := ws.LayoutIdentity(); got != claim { + t.Fatal("claim identity changed after lost reply") + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + me, err := p.LayoutHolder(ctx, "v1") + if err != nil || me.ClaimID != claim || me.Epoch != 1 { + t.Fatalf("handover=%+v %v", me, err) + } + for i := 0; i < 2; i++ { + if got, err := p.LayoutRemote(ctx, "v1"); err != nil || got != createdRemote { + t.Fatalf("cached remote changed: %T %v", got, err) + } + } + if _, fresh, _ = ws.LayoutIdentity(); fresh { + t.Fatal("serving with a fresh descriptor") + } + if files, _ := filepath.Glob(filepath.Join(oldRoot, "*.chunkfresh")); len(files) != 0 { + t.Fatal("created a second identity marker", files) + } + if _, err = ws.Write(0, bytes.Repeat([]byte{'A'}, 4096)); err != nil { + t.Fatal(err) + } + if _, err = ws.Sync(); err != nil { + t.Fatal(err) + } + if _, err = p.CutVolume(ctx, "v1", 0); err != nil { + t.Fatal(err) + } + if err = p.Close(); err != nil { + t.Fatal(err) + } + // A newly created directory at the same grant cannot invent continuity. + empty, _ := makeProvider(t.TempDir()) + if _, err = empty.RecoverVolume(ctx, "v1"); !errors.Is(err, layout.ErrMissingLocalRoot) { + t.Fatalf("empty own epoch: %v", err) + } + if gen, ended := empty.ChunkStartupOutcome("v1"); !ended || empty.ChunkStartupCure("v1", gen) != layout.MissingLocalRootCure { + t.Fatalf("missing local root did not end with its cure: ended=%t cure=%q", ended, empty.ChunkStartupCure("v1", gen)) + } + if _, err = empty.LayoutHolder(ctx, "v1"); err == nil { + t.Fatal("failed Start exposed cleaning identity") + } + if _, err = empty.LayoutRemote(ctx, "v1"); err == nil { + t.Fatal("failed Start exposed a remote") + } + if err = empty.Close(); err != nil { + t.Fatal(err) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 2})) + successor, newWS := makeProvider(t.TempDir()) + if _, err = successor.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if got, err := newWS.Read(0); err != nil || !bytes.Equal(got, bytes.Repeat([]byte{'A'}, 4096)) { + t.Fatalf("restore lost published bytes: %v", err) + } + if _, err = newWS.Write(0, bytes.Repeat([]byte{'B'}, 4096)); err != nil { + t.Fatal(err) + } + if _, err = newWS.Sync(); err != nil { + t.Fatal(err) + } + if _, err = successor.CutVolume(ctx, "v1", 0); err != nil { + t.Fatal(err) + } + if err = successor.Close(); err != nil { + t.Fatal(err) + } + remounted, _ := makeProvider(oldRoot) + if _, err = remounted.RecoverVolume(ctx, "v1"); !errors.Is(err, layout.ErrStaleLocalRoot) || !strings.Contains(err.Error(), layout.StaleLocalRootCure) { + t.Fatalf("old directory served new lineage: %v", err) + } + gen, ended := remounted.ChunkStartupOutcome("v1") + if !ended || remounted.ChunkStartupSuperseded("v1", gen) || remounted.ChunkStartupCure("v1", gen) != layout.StaleLocalRootCure { + t.Fatalf("stale root did not end with its cure: ended=%t superseded=%t cure=%q", ended, remounted.ChunkStartupSuperseded("v1", gen), remounted.ChunkStartupCure("v1", gen)) + } + if remoteCalls != 2 { + t.Fatalf("remote constructed before Start/duplicated: %d", remoteCalls) + } + if err := remounted.Close(); err != nil { + t.Fatal(err) + } + view = newStubView(frontend.Projection{}) + deferred, _ := makeProvider(oldRoot) + if _, err := deferred.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("local recovery before authority: %v", err) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 3})) + waitFor(t, 4*time.Second, "deferred stale root to finish once", func() bool { + _, ended := deferred.ChunkStartupOutcome("v1") + return ended + }) + gen, ended = deferred.ChunkStartupOutcome("v1") + if !ended || deferred.ChunkStartupSuperseded("v1", gen) || deferred.ChunkStartupCure("v1", gen) != layout.StaleLocalRootCure { + t.Fatalf("deferred stale root did not end with its cure: ended=%t superseded=%t cure=%q", ended, deferred.ChunkStartupSuperseded("v1", gen), deferred.ChunkStartupCure("v1", gen)) + } + if err := deferred.Backend("v1").AdmitsIO(); err == nil { + t.Fatal("deferred stale root admitted guest I/O") + } +} + +type layoutLostClaimReply struct { + layout.StartStore + lose *bool +} + +func (s *layoutLostClaimReply) UpdateHead(ctx context.Context, expected uint64, next layout.Head) error { + if err := s.StartStore.UpdateHead(ctx, expected, next); err != nil { + return err + } + if *s.lose { + *s.lose = false + return errors.New("fixture: committed claim reply lost") + } + return nil +} diff --git a/seaweed-block/core/frontend/durable/provider_maintenance_test.go b/seaweed-block/core/frontend/durable/provider_maintenance_test.go index 0ad8f19d5c..1f4c1f30bf 100644 --- a/seaweed-block/core/frontend/durable/provider_maintenance_test.go +++ b/seaweed-block/core/frontend/durable/provider_maintenance_test.go @@ -9,18 +9,17 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) func TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock(t *testing.T) { entered, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) var once sync.Once finish := func() { once.Do(func() { close(release) }) } - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(ctx context.Context, vol string) error { close(entered) @@ -29,7 +28,9 @@ func TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock(t *testing.T) { <-release return ctx.Err() }, - }, v1View()) + } + testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks).Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } @@ -95,9 +96,8 @@ func TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock(t *testing.T) { func TestMaintenanceAuthorityLossCancelsHeldPass(t *testing.T) { view := v1View() entered, cancelled := make(chan struct{}), make(chan struct{}) - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(ctx context.Context, _ string) error { close(entered) @@ -105,7 +105,9 @@ func TestMaintenanceAuthorityLossCancelsHeldPass(t *testing.T) { close(cancelled) return ctx.Err() }, - }, view) + } + testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks).Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } @@ -128,9 +130,8 @@ func TestMaintenancePassHasOneDeadline(t *testing.T) { entered := make(chan error, 1) three := make(chan struct{}) var completed atomic.Int32 - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenanceTimeout: 10 * time.Millisecond, ChunkMaintenance: func(ctx context.Context, _ string) error { <-ctx.Done() @@ -143,7 +144,9 @@ func TestMaintenancePassHasOneDeadline(t *testing.T) { } return ctx.Err() }, - }, v1View()) + } + testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks).Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } @@ -180,24 +183,24 @@ func TestMaintenancePassHasOneDeadline(t *testing.T) { } } -type pendingMaintenancePut struct{ *storage.MemChunkRemote } - -func (r pendingMaintenancePut) Put(ctx context.Context, _ string, _ []byte) error { - <-ctx.Done() - return ctx.Err() -} func TestCutDeadlineIncludesUploadWithBackgroundCaller(t *testing.T) { - remote := pendingMaintenancePut{storage.NewMemChunkRemote()} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + fixture.Blobs.PutHook = func(ctx context.Context) error { <-ctx.Done(); return ctx.Err() } + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, ChunkCutTimeout: 10 * time.Millisecond, - }, v1View()) + ChunkCutTimeout: 10 * time.Millisecond, + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = p.Close() }) s := openRecovered(t, p) - claimed := freshV1Claim(t, remote.MemChunkRemote) + claimed, found, err := fixture.Catalog.ReadHead(context.Background(), fixture.Ref) + if err != nil || !found { + t.Fatalf("initial layout HEAD: found=%v err=%v", found, err) + } if _, err = s.Write(1, block(0x48)); err != nil { t.Fatal(err) } @@ -205,8 +208,10 @@ func TestCutDeadlineIncludesUploadWithBackgroundCaller(t *testing.T) { if !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("whole cut did not expire: %v", err) } - h, err := remote.GetHead(context.Background()) - if err != nil || h.Gen != claimed.Gen { + h, found, err := fixture.Catalog.ReadHead(context.Background(), fixture.Ref) + // BeginSnap may advance HEAD's generation before the upload. The + // deadline must still prevent the content and position from committing. + if err != nil || !found || h.Current != nil || h.Position != claimed.Position || len(h.Snapshots) != len(claimed.Snapshots) { t.Fatalf("expired upload published: %+v %v", h, err) } } @@ -216,9 +221,8 @@ func TestMaintenanceCoalescesWhileOnePassIsHeld(t *testing.T) { var once sync.Once finish := func() { once.Do(func() { close(release) }) } var calls atomic.Int32 - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(ctx context.Context, _ string) error { if calls.Add(1) == 1 { @@ -230,7 +234,9 @@ func TestMaintenanceCoalescesWhileOnePassIsHeld(t *testing.T) { } return ctx.Err() }, - }, v1View()) + } + testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks).Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } @@ -256,8 +262,15 @@ func TestMaintenanceCoalescesWhileOnePassIsHeld(t *testing.T) { } func TestMaintenancePeriodicNoopDoesNotChurnHead(t *testing.T) { - remote := storage.NewMemChunkRemote() - p := schedProvider(t, remote, time.Millisecond) + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkCaptureInterval: time.Millisecond} + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) s := openRecovered(t, p) lsn, err := s.Write(1, block(0x91)) if err != nil { @@ -265,13 +278,14 @@ func TestMaintenancePeriodicNoopDoesNotChurnHead(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - var first storage.ChunkHead + var first layout.Head for { - first, err = remote.GetHead(ctx) - if err != nil { - t.Fatal(err) + var found bool + first, found, err = fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found { + t.Fatalf("layout HEAD: found=%v err=%v", found, err) } - if first.RemoteLSN >= lsn { + if first.Position >= lsn { break } select { @@ -300,8 +314,8 @@ func TestMaintenancePeriodicNoopDoesNotChurnHead(t *testing.T) { case <-time.After(time.Millisecond): } } - after, err := remote.GetHead(ctx) - if err != nil || after.Gen != first.Gen { + after, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found || after.Gen != first.Gen { t.Fatalf("noop churned HEAD: before=%d after=%d err=%v", first.Gen, after.Gen, err) } } @@ -312,9 +326,8 @@ func TestMaintenanceHealthyLineageChangeCancelsHeldPass(t *testing.T) { view := v1View() entered, cancelled := make(chan struct{}), make(chan struct{}) var enterOnce, cancelOnce sync.Once - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(ctx context.Context, _ string) error { enterOnce.Do(func() { close(entered) }) @@ -322,7 +335,9 @@ func TestMaintenanceHealthyLineageChangeCancelsHeldPass(t *testing.T) { cancelOnce.Do(func() { close(cancelled) }) return ctx.Err() }, - }, view) + } + testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks).Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider_manifest_test.go b/seaweed-block/core/frontend/durable/provider_manifest_test.go deleted file mode 100644 index c68b88191d..0000000000 --- a/seaweed-block/core/frontend/durable/provider_manifest_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package durable_test - -import ( - "context" - "sync/atomic" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -type manifestAwareRemote struct { - *storage.MemChunkRemote - prepared atomic.Int32 -} - -func (r *manifestAwareRemote) PrepareManifest(ctx context.Context, base, next storage.ChunkHead, chunkBytes uint64) (storage.ChunkHead, []string, error) { - r.prepared.Add(1) - return next, nil, ctx.Err() -} -func TestWALStoreChunk_ProviderPreservesManifestCapability(t *testing.T) { - r := &manifestAwareRemote{MemChunkRemote: storage.NewMemChunkRemote()} - p := chunkProvider(t, t.TempDir(), r, v1View(), 0) - s := openRecovered(t, p) - if _, err := s.Write(0, block(0x65)); err != nil { - t.Fatal(err) - } - if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { - t.Fatal(err) - } - if r.prepared.Load() != 1 { - t.Fatalf("provider erased remote manifest capability: preparations=%d", r.prepared.Load()) - } -} diff --git a/seaweed-block/core/frontend/durable/provider_master_wait_test.go b/seaweed-block/core/frontend/durable/provider_master_wait_test.go index f2d9c6977b..87c9864bbd 100644 --- a/seaweed-block/core/frontend/durable/provider_master_wait_test.go +++ b/seaweed-block/core/frontend/durable/provider_master_wait_test.go @@ -7,8 +7,9 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) // With ChunkMasterWait set (a workspace primary), the startup authority wait @@ -26,7 +27,7 @@ func TestChunkAuthorityWaitFollowsTheMasterWait(t *testing.T) { var bound atomic.Int64 // unix ns; 0 = no bound var final atomic.Bool v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: time.Millisecond, ChunkMasterWait: func(time.Time) (time.Time, bool) { @@ -35,11 +36,14 @@ func TestChunkAuthorityWaitFollowsTheMasterWait(t *testing.T) { } return time.Time{}, final.Load() }, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { - t.Error("remote reached without authority") - return storage.NewMemChunkRemote(), nil - }, - }, v) + } + testutil.NewLayoutFixture(t, "v1", 64, 4).Configure(&cfg) + start := cfg.ChunkLayoutHeadFor + cfg.ChunkLayoutHeadFor = func(name string) (layout.StartStore, error) { + t.Error("layout reached without authority") + return start(name) + } + p, err := durable.NewDurableProvider(cfg, v) if err != nil { t.Fatal(err) } @@ -76,15 +80,16 @@ func TestChunkAuthorityWaitFollowsTheMasterWait(t *testing.T) { func TestChunkAuthorityWaitPassesItsOwnStart(t *testing.T) { v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} var starts atomic.Int64 - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkMasterWait: func(start time.Time) (time.Time, bool) { starts.Store(start.UnixNano()) return time.Time{}, false }, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, - }, v) + } + testutil.NewLayoutFixture(t, "v1", 64, 4).Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v) if err != nil { t.Fatal(err) } @@ -117,7 +122,7 @@ func TestChunkGrantedAttachThatKeepsFailingIsBounded(t *testing.T) { captureWriteLogs(t, logs) v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} var bound atomic.Int64 - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkMasterWait: func(time.Time) (time.Time, bool) { @@ -126,10 +131,10 @@ func TestChunkGrantedAttachThatKeepsFailingIsBounded(t *testing.T) { } return time.Time{}, false }, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { - return nil, errors.New("chunk store unreachable") - }, - }, v) + } + testutil.NewLayoutFixture(t, "v1", 64, 4).Configure(&cfg) + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return nil, errors.New("chunk store unreachable") } + p, err := durable.NewDurableProvider(cfg, v) if err != nil { t.Fatal(err) } @@ -156,14 +161,15 @@ func TestChunkGrantedAttachThatKeepsFailingIsBounded(t *testing.T) { func TestChunkAuthorityWaitAttachesAGrantOnTheBoundsTick(t *testing.T) { v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} var ended atomic.Bool // the master wait reports its end together with the grant - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: time.Millisecond, ChunkMasterWait: func(time.Time) (time.Time, bool) { return time.Time{}, ended.Load() }, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, - }, v) + } + testutil.NewLayoutFixture(t, "v1", 64, 4).Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider_offline_seal_test.go b/seaweed-block/core/frontend/durable/provider_offline_seal_test.go index 5f47d335ee..49e1becc27 100644 --- a/seaweed-block/core/frontend/durable/provider_offline_seal_test.go +++ b/seaweed-block/core/frontend/durable/provider_offline_seal_test.go @@ -8,6 +8,8 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -17,16 +19,8 @@ import ( func TestOfflineSealUsesCallerDeadline(t *testing.T) { for _, closed := range []bool{false, true} { t.Run(map[bool]string{false: "idle", true: "closed"}[closed], func(t *testing.T) { - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, - NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, DetachFreezeTimeout: time.Second, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = p.Close() }) + c := newLayoutCase(t, pcBlocks, pcChunkBlocks) + p := c.provider(t, t.TempDir(), v1View(), "s/r1", func(cfg *durable.ProviderConfig) { cfg.DetachFreezeTimeout = time.Second }) openRecovered(t, p) ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() @@ -64,7 +58,7 @@ func TestOfflineSealUsesCallerDeadline(t *testing.T) { if !observed { t.Error("offline seal did not drain") } - if !bytes.Equal(headBlock(t, remote, 1), block(0x61)) { + if !bytes.Equal(c.block(t, 1), block(0x61)) { t.Fatal("offline seal lost acknowledged bytes") } }) @@ -74,23 +68,42 @@ func TestOfflineSealUsesCallerDeadline(t *testing.T) { // Caller cancellation ends an offline upload; the closed backend stays closed, // and a new caller can retry the seal without losing acknowledged bytes. type cancelSealRemote struct { - *storage.MemChunkRemote - once sync.Once - cancel context.CancelFunc + storage.ChunkRemote + keyer storage.ChunkKeyer + aborter storage.ChunkRemote + once sync.Once + cancel context.CancelFunc } +func (r *cancelSealRemote) ChunkKey(idx uint64, sum [32]byte) string { + return r.keyer.ChunkKey(idx, sum) +} +func (r *cancelSealRemote) Abort() { r.aborter.Abort() } + func (r *cancelSealRemote) Put(ctx context.Context, key string, b []byte) error { r.once.Do(r.cancel) if err := ctx.Err(); err != nil { return err } - return r.MemChunkRemote.Put(ctx, key, b) + return r.ChunkRemote.Put(ctx, key, b) } func TestOfflineSealCallerCancelCanRetry(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - remote := &cancelSealRemote{MemChunkRemote: storage.NewMemChunkRemote(), cancel: cancel} - p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + c := newLayoutCase(t, pcBlocks, pcChunkBlocks) + remote := &cancelSealRemote{cancel: cancel} + p := c.provider(t, t.TempDir(), v1View(), "s/r1", func(cfg *durable.ProviderConfig) { + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + r, err := chunkstore.NewLayoutRemote(c.cat, c.ref, me) + if err != nil { + return nil, err + } + remote.ChunkRemote = r + remote.keyer = r + remote.aborter = r + return remote, nil + } + }) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") if err != nil { @@ -111,7 +124,7 @@ func TestOfflineSealCallerCancelCanRetry(t *testing.T) { retry, end := context.WithTimeout(context.Background(), time.Minute) defer end() r, _, err := p.DetachVolumePlain(retry, "v1") - if err != nil || r.Head.State != storage.ChunkHeadDetached || !bytes.Equal(headBlock(t, remote.MemChunkRemote, 1), block(0x72)) { + if err != nil || r.Head.State != storage.ChunkHeadDetached || !bytes.Equal(c.block(t, 1), block(0x72)) { t.Fatalf("offline retry failed: %+v %v", r, err) } } diff --git a/seaweed-block/core/frontend/durable/provider_plain_detach_test.go b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go index 3d7986a308..161a1ae256 100644 --- a/seaweed-block/core/frontend/durable/provider_plain_detach_test.go +++ b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go @@ -8,16 +8,28 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) +func precopyLayoutProvider(t *testing.T, c *layoutCase, view *parkView, hooks ...*detachHooks) *durable.DurableProvider { + t.Helper() + return c.provider(t, t.TempDir(), view.stubView, "s/r1", func(cfg *durable.ProviderConfig) { + cfg.ChunkDetachPrecopy = true + if len(hooks) > 0 { + cfg.OnChunkDetach = hooks[0].detach + cfg.OnChunkDetachResumed = hooks[0].resume + } + }) +} + func TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() + c := newLayoutCase(t, pcBlocks, pcChunkBlocks) hooks := &detachHooks{} - p := precopyProvider(t, remote, &parkView{stubView: v1View()}, hooks) + p := precopyLayoutProvider(t, c, &parkView{stubView: v1View()}, hooks) openRecovered(t, p) b, err := p.Open(ctx, "v1") if err != nil { @@ -62,16 +74,16 @@ func TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend(t *testing.T) { if !errors.Is(err, storage.ErrPrecopyNotConverged) || r.Precopy.Frozen { t.Fatalf("expected thawed pre-copy refusal: %+v %v", r, err) } - before, err := remote.GetHead(ctx) - if err != nil || before.State == storage.ChunkHeadDetached { - t.Fatalf("refusal detached: %+v %v", before, err) + before := c.head(t) + if before.State == layout.StateDetached { + t.Fatalf("refusal detached: %+v", before) } if _, _, err = p.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrPlainDetachBusy) { t.Fatalf("plain accepted admitted I/O: %v", err) } - after, err := remote.GetHead(ctx) - if err != nil || after.Gen != before.Gen || after.State != before.State { - t.Fatalf("busy plain mutated HEAD: before=%+v after=%+v err=%v", before, after, err) + after := c.head(t) + if after.Gen != before.Gen || after.State != before.State { + t.Fatalf("busy plain mutated HEAD: before=%+v after=%+v", before, after) } starts, resumes := hooks.calls() if len(starts) != 1 || len(resumes) != 1 { @@ -99,7 +111,7 @@ func TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend(t *testing.T) { lba uint32 value byte }{{1, 0x4a}, {2, 0x5b}} { - if !bytes.Equal(headBlock(t, remote, x.lba), block(x.value)) { + if !bytes.Equal(c.block(t, x.lba), block(x.value)) { t.Fatalf("plain lost acknowledged block %d", x.lba) } } @@ -115,8 +127,8 @@ func TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend(t *testing.T) { func TestPlainDetachSkipsPrecopyCostAdmission(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() - p := precopyProvider(t, remote, &parkView{stubView: v1View()}) + c := newLayoutCase(t, pcBlocks, pcChunkBlocks) + p := precopyLayoutProvider(t, c, &parkView{stubView: v1View()}) openRecovered(t, p) b, err := p.Open(ctx, "v1") if err != nil { @@ -126,7 +138,7 @@ func TestPlainDetachSkipsPrecopyCostAdmission(t *testing.T) { t.Fatal(err) } r, _, err := p.DetachVolumePlain(ctx, "v1") - if err != nil || r.Head.State != storage.ChunkHeadDetached || len(r.Precopy.Rounds) != 0 || !bytes.Equal(headBlock(t, remote, 1), block(0x7c)) { + if err != nil || r.Head.State != storage.ChunkHeadDetached || len(r.Precopy.Rounds) != 0 || !bytes.Equal(c.block(t, 1), block(0x7c)) { t.Fatalf("plain request used pre-copy admission or lost its point: %+v %v", r, err) } } diff --git a/seaweed-block/core/frontend/durable/provider_plain_seal_replay_test.go b/seaweed-block/core/frontend/durable/provider_plain_seal_replay_test.go deleted file mode 100644 index 6a5e50edc5..0000000000 --- a/seaweed-block/core/frontend/durable/provider_plain_seal_replay_test.go +++ /dev/null @@ -1,229 +0,0 @@ -package durable_test - -import ( - "context" - "errors" - "reflect" - "sync" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -type plainSealReplayRemote struct { - *storage.MemChunkRemote - mu sync.Mutex - loseSeal, unreadable bool - reads, cas int - corrupt func(*storage.ChunkHead) -} - -func (r *plainSealReplayRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { - r.mu.Lock() - r.reads++ - unreadable, corrupt := r.unreadable, r.corrupt - r.mu.Unlock() - if unreadable { - return storage.ChunkHead{}, errInjected - } - h, err := r.MemChunkRemote.GetHead(ctx) - if corrupt != nil { - corrupt(&h) - } - return h, err -} - -func (r *plainSealReplayRemote) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) { - r.mu.Lock() - r.cas++ - lose := r.loseSeal && h.State == storage.ChunkHeadDetached - r.mu.Unlock() - gen, err := r.MemChunkRemote.CASHead(ctx, v, h) - if err == nil && lose { - r.mu.Lock() - r.unreadable = true - r.mu.Unlock() - return 0, errInjected - } - return gen, err -} - -func TestPlainSealLostAnswerRestartReplaysFilerProof(t *testing.T) { - ctx := hangGuard(t) - r := &plainSealReplayRemote{MemChunkRemote: storage.NewMemChunkRemote()} - root := t.TempDir() - first := chunkProvider(t, root, r, v1View(), 0) - s := openRecovered(t, first) - writeSync(t, s, 1, 0x42) - r.mu.Lock() - r.loseSeal = true - r.mu.Unlock() - if _, _, err := first.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { - t.Fatal("seal did not lose its committed answer", err) - } - sealed := headHolder(t, r.MemChunkRemote) - if sealed.State != storage.ChunkHeadDetached { - t.Fatal("seal was not actually committed") - } - if err := first.Close(); err != nil { - t.Fatal(err) - } - r.mu.Lock() - r.loseSeal, r.unreadable = false, false - r.mu.Unlock() - view := v1View() - second := chunkProvider(t, root, r, view, 0) - if _, err := second.EnsureStorage("v1"); err != nil { - t.Fatal(err) - } - if _, err := second.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) { - t.Fatal("restart must keep the sealed incarnation non-serving", err) - } - // Startup reports the sealed recovery failure and remains non-serving; - // the assigned identity must still be able to answer this read-only retry. - notServing := view.Projection() - notServing.Healthy = false - view.set(notServing) - r.mu.Lock() - reads, cas := r.reads, r.cas - r.mu.Unlock() - result, last, err := second.DetachVolumePlain(ctx, "v1") - if err != nil || !reflect.DeepEqual(result.Head, sealed) || result.H != sealed.RemoteLSN || last != sealed.RemoteLSN { - t.Fatalf("re-sent seal did not return the original filer proof: result=%+v last=%d err=%v", result, last, err) - } - r.mu.Lock() - gotReads, gotCAS := r.reads, r.cas - r.mu.Unlock() - if gotReads <= reads || gotCAS != cas || !reflect.DeepEqual(headHolder(t, r.MemChunkRemote), sealed) { - t.Fatal("replay used no filer read or published a new generation") - } - for _, tc := range []struct { - name string - mutate func(*storage.ChunkHead) - }{ - {"active", func(h *storage.ChunkHead) { h.State = storage.ChunkHeadActive; h.DetachedBy = nil }}, - {"holder", func(h *storage.ChunkHead) { h.Holder = "other" }}, - {"epoch", func(h *storage.ChunkHead) { h.Epoch++ }}, - {"missing-proof", func(h *storage.ChunkHead) { h.DetachedBy = nil }}, - {"proof-generation", func(h *storage.ChunkHead) { h.DetachedBy.Gen++ }}, - {"proof-holder", func(h *storage.ChunkHead) { h.DetachedBy.Holder = "other" }}, - {"proof-epoch", func(h *storage.ChunkHead) { h.DetachedBy.Epoch++ }}, - } { - t.Run(tc.name, func(t *testing.T) { - r.mu.Lock() - r.corrupt = tc.mutate - r.mu.Unlock() - defer func() { r.mu.Lock(); r.corrupt = nil; r.mu.Unlock() }() - if _, _, err := second.DetachVolumePlain(ctx, "v1"); err == nil { - t.Fatal("invalid filer proof returned success") - } - }) - } - initial := view.Projection() - r.mu.Lock() - r.corrupt = func(*storage.ChunkHead) { moved := initial; moved.EndpointVersion++; view.set(moved) } - r.mu.Unlock() - if _, _, err := second.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrChunkEpochStale) { - t.Fatal("replay ignored authority movement during its read", err) - } - view.set(initial) - r.mu.Lock() - r.corrupt = nil - r.unreadable = true - r.mu.Unlock() - if _, _, err := second.DetachVolumePlain(ctx, "v1"); err == nil { - t.Fatal("unreadable filer returned a cached seal") - } - r.mu.Lock() - r.unreadable = false - r.mu.Unlock() - ended, cancel := context.WithCancel(ctx) - cancel() - if _, _, err := second.DetachVolumePlain(ended, "v1"); !errors.Is(err, context.Canceled) { - t.Fatal("replay hid caller cancellation", err) - } - if err := second.Close(); err != nil { - t.Fatal(err) - } - if _, _, err := second.DetachVolumePlain(ctx, "v1"); err == nil { - t.Fatal("closed provider replayed a seal") - } -} - -func TestPlainSealReplayNeverUsesProcessMemory(t *testing.T) { - ctx := hangGuard(t) - r := &plainSealReplayRemote{MemChunkRemote: storage.NewMemChunkRemote()} - p := chunkProvider(t, t.TempDir(), r, v1View(), 0) - s := openRecovered(t, p) - writeSync(t, s, 1, 0x53) - if _, _, err := p.DetachVolumePlain(ctx, "v1"); err != nil { - t.Fatal(err) - } - r.mu.Lock() - r.unreadable = true - r.mu.Unlock() - if _, _, err := p.DetachVolumePlain(ctx, "v1"); err == nil { - t.Fatal("re-sent plain seal answered from process memory despite unreadable filer") - } -} - -// INV-WS-SEAL-REPLAY-001: deferred healthy startup must not hide a filer seal. -func TestPlainSealReplayDuringDeferredAuthorityStartup(t *testing.T) { - ctx := hangGuard(t) - r := &plainSealReplayRemote{MemChunkRemote: storage.NewMemChunkRemote()} - root := t.TempDir() - first := chunkProvider(t, root, r, v1View(), 0) - s := openRecovered(t, first) - writeSync(t, s, 1, 0x64) - r.mu.Lock() - r.loseSeal = true - r.mu.Unlock() - if _, _, err := first.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { - t.Fatal("seal did not lose its committed answer", err) - } - sealed := headHolder(t, r.MemChunkRemote) - if err := first.Close(); err != nil { - t.Fatal(err) - } - r.mu.Lock() - r.loseSeal, r.unreadable = false, false - r.mu.Unlock() - view := v1View() - assigned := view.Projection() - assigned.Healthy = false - view.set(assigned) - second := chunkProvider(t, root, r, view, 0) - if _, err := second.EnsureStorage("v1"); err != nil { - t.Fatal(err) - } - if _, err := second.RecoverVolume(ctx, "v1"); err != nil { - t.Fatal(err) - } - // This is the actual awaiting/no-layer schedule, before any healthy attach. - if _, err := second.CaptureVolume(ctx, "v1"); !errors.Is(err, durable.ErrChunkAwaitingAuthority) { - t.Fatal("recovery did not enter deferred authority startup", err) - } - r.mu.Lock() - reads, cas := r.reads, r.cas - r.mu.Unlock() - result, last, err := second.DetachVolumePlain(ctx, "v1") - if err != nil || !reflect.DeepEqual(result.Head, sealed) || result.H != sealed.RemoteLSN || last != sealed.RemoteLSN { - t.Fatalf("awaiting restart did not replay exact filer proof: result=%+v last=%d err=%v", result, last, err) - } - r.mu.Lock() - gotReads, gotCAS := r.reads, r.cas - r.mu.Unlock() - if gotReads <= reads || gotCAS != cas || !reflect.DeepEqual(headHolder(t, r.MemChunkRemote), sealed) { - t.Fatal("replay skipped filer proof or changed sealed HEAD") - } - if view.Projection().Healthy { - t.Fatal("replay made the projection healthy") - } - if _, err := second.CaptureVolume(ctx, "v1"); !errors.Is(err, durable.ErrChunkAwaitingAuthority) { - t.Fatal("replay enabled unhealthy cuts", err) - } - if err := second.Close(); err != nil { - t.Fatal(err) - } -} diff --git a/seaweed-block/core/frontend/durable/provider_reopen_belt_test.go b/seaweed-block/core/frontend/durable/provider_reopen_belt_test.go index 743c9edbba..b5025e9bd4 100644 --- a/seaweed-block/core/frontend/durable/provider_reopen_belt_test.go +++ b/seaweed-block/core/frontend/durable/provider_reopen_belt_test.go @@ -2,100 +2,31 @@ package durable_test import ( "bytes" - "context" - "errors" "testing" - "github.com/seaweedfs/seaweed-block/core/frontend" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) -type reopenClaimRaceRemote struct { - storage.ChunkRemote - foreign storage.ChunkHead - reads int -} - -func (r *reopenClaimRaceRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { - h, err := r.ChunkRemote.GetHead(ctx) - if err != nil { - return h, err - } - r.reads++ - if r.reads == 1 { - // The early local-root check sees our publication. Before the claim's - // independent read, another holder publishes below the current epoch. - if _, err := r.ChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, r.foreign); err != nil { - return storage.ChunkHead{}, err - } - } - return h, nil -} - -func TestLocalReopenRejectsForeignClaimImage(t *testing.T) { - ctx := hangGuard(t) - r := storage.NewMemChunkRemote() - root := t.TempDir() - first := chunkProvider(t, root, r, viewAs("rA", 3), 0) - s := openRecovered(t, first) - writeSync(t, s, 0, 0x31) - if _, err := first.CaptureVolume(ctx, "v1"); err != nil { - t.Fatal(err) - } - writeSync(t, s, 1, 0x42) - if err := first.Close(); err != nil { - t.Fatal(err) - } - foreign := headHolder(t, r) - foreign.Epoch, foreign.Holder = 4, "rB" - race := &reopenClaimRaceRemote{ChunkRemote: r, foreign: foreign} - second := chunkProvider(t, root, race, viewAs("rA", 5), 0) - if _, err := second.EnsureStorage("v1"); err != nil { - t.Fatal(err) - } - _, err := second.RecoverVolume(ctx, "v1") - if !errors.Is(err, durable.ErrChunkStaleLocalRoot) || !errors.Is(err, storage.ErrChunkLayerFenced) { - t.Errorf("foreign claim image admitted over local WAL: %v", err) - } - if race.reads < 2 { - t.Fatal("control did not reach the independent claim observation") - } - if after := headHolder(t, r); after.Epoch != 4 || after.Holder != "rB" || after.Gen != foreign.Gen+1 { - t.Errorf("refused reopen changed the foreign HEAD: %+v", after) - } - be, err := second.Open(ctx, "v1") - if err != nil { - t.Fatal(err) - } - if _, err := be.Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) { - t.Errorf("foreign claim image exposed I/O: %v", err) - } - if got, err := second.LogicalStorage("v1").Read(1); err != nil || !bytes.Equal(got, block(0x42)) { - t.Errorf("refusal changed acknowledged local bytes: %v", err) - } -} - func TestLocalReopenClaimsBeforeServing(t *testing.T) { ctx := hangGuard(t) - r := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) root := t.TempDir() - first := chunkProvider(t, root, r, v1View(), 0) + first := layoutChunkProvider(t, root, fixture, v1View(), 0) s := openRecovered(t, first) writeSync(t, s, 0, 0x31) if _, err := first.CaptureVolume(ctx, "v1"); err != nil { t.Fatal(err) } - before := headHolder(t, r) + before := layoutHead(t, fixture) writeSync(t, s, 1, 0x42) // locally acknowledged, not yet in HEAD if err := first.Close(); err != nil { t.Fatal(err) } - second := chunkProvider(t, root, r, v1View(), 0) + second := layoutChunkProvider(t, root, fixture, v1View(), 0) s = openRecovered(t, second) - after := headHolder(t, r) - if after.Gen <= before.Gen || after.Epoch != before.Epoch || after.Holder != before.Holder || after.RemoteLSN != before.RemoteLSN { - t.Errorf("local reopen served without replacing the old CAS guard: before=%+v after=%+v", before, after) + after := layoutHead(t, fixture) + if after.Epoch != before.Epoch || after.Holder != before.Holder || after.ClaimID != before.ClaimID || after.Position != before.Position { + t.Errorf("local reopen changed the holder identity or published position: before=%+v after=%+v", before, after) } if got, err := s.Read(1); err != nil || !bytes.Equal(got, block(0x42)) { t.Fatal("claim replaced locally acknowledged bytes with HEAD", err) @@ -103,7 +34,7 @@ func TestLocalReopenClaimsBeforeServing(t *testing.T) { if _, err := second.CaptureVolume(ctx, "v1"); err != nil { t.Fatal(err) } - if !bytes.Equal(headBlock(t, r, 0), block(0x31)) || !bytes.Equal(headBlock(t, r, 1), block(0x42)) { + if !bytes.Equal(layoutHeadBlock(t, fixture, 0), block(0x31)) || !bytes.Equal(layoutHeadBlock(t, fixture, 1), block(0x42)) { t.Fatal("reopen did not publish the complete acknowledged image") } } diff --git a/seaweed-block/core/frontend/durable/provider_restore_schedule_test.go b/seaweed-block/core/frontend/durable/provider_restore_schedule_test.go index 21d2df090e..9c0c9bbb30 100644 --- a/seaweed-block/core/frontend/durable/provider_restore_schedule_test.go +++ b/seaweed-block/core/frontend/durable/provider_restore_schedule_test.go @@ -5,11 +5,11 @@ import ( "context" "crypto/sha256" "errors" - "sync" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -23,15 +23,30 @@ func awaitRestoreCondition(t *testing.T, ctx context.Context, what string, ready } } } - -func TestRestoreCheckpointBeforeAssignmentPreservesRemoteBytes(t *testing.T) { +func TestFreshStoreRefusesWriteBeforeAssignmentThenPublishesAfterClaim(t *testing.T) { ctx := hangGuard(t) - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) - p := chunkProvider(t, t.TempDir(), remote, view, 0) - s := openRecovered(t, p) - ws := s.(*storage.WALStore) + p := layoutChunkProvider(t, t.TempDir(), fixture, view, 0) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } want := block(0xD7) + if _, err := s.Write(33, want); !errors.Is(err, storage.ErrLayoutFresh) { + t.Fatalf("write before the claim: %v; want ErrLayoutFresh", err) + } + if h := layoutHead(t, fixture); h.Epoch != 0 || h.Holder != "" || h.Current != nil { + t.Fatal("unexpected claimed HEAD before assignment", h) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1})) + awaitRestoreCondition(t, ctx, "deferred attachment", func() bool { + st := p.DurableStatuses() + return len(st) == 1 && st[0].Operational && st[0].Chunk != nil && st[0].Chunk.Attached && !st[0].Chunk.Stats.Reconciling + }) lsn, err := s.Write(33, want) if err != nil { t.Fatal(err) @@ -39,87 +54,12 @@ func TestRestoreCheckpointBeforeAssignmentPreservesRemoteBytes(t *testing.T) { if _, err := s.Sync(); err != nil { t.Fatal(err) } - // FlushCount increments after checkpoint persistence AND dirty-map removal. - // The authority stays absent until that actual cycle has fully completed. - awaitRestoreCondition(t, ctx, "checkpoint before attach", func() bool { - return ws.CheckpointLSN() >= lsn && ws.FlushCount() > 0 - }) - if h, _ := remote.GetHead(ctx); h.Gen != 0 { - t.Fatal("unexpected HEAD before assignment", h) - } - view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1})) - // The local volume took writes before its first attach, so its dirty - // set is unknown and is reconciled against HEAD before cuts resume. - awaitRestoreCondition(t, ctx, "deferred attachment and reconciliation", func() bool { - st := p.DurableStatuses() - return len(st) == 1 && st[0].Operational && st[0].Chunk != nil && st[0].Chunk.Attached && !st[0].Chunk.Stats.Reconciling - }) if h, err := p.CaptureVolume(ctx, "v1"); err != nil || h != lsn { t.Fatal("cut", h, err) } - fresh := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + fresh := layoutChunkProvider(t, t.TempDir(), fixture, viewAs("rB", 4), 0) got, err := openRecovered(t, fresh).Read(33) if err != nil || !bytes.Equal(got, want) { t.Fatalf("remote restore lost checkpointed bytes: got=%x err=%v", sha256.Sum256(got), err) } } - -type publishAfterAbsentRead struct { - storage.ChunkRemote - once sync.Once - beforeReturn func() -} - -func (r *publishAfterAbsentRead) GetHead(ctx context.Context) (storage.ChunkHead, error) { - h, err := r.ChunkRemote.GetHead(ctx) - if err == nil { - r.once.Do(r.beforeReturn) - } - return h, err -} - -func TestRestoreHEADAppearsBetweenClaimAndAttach(t *testing.T) { - ctx := hangGuard(t) - remote := storage.NewMemChunkRemote() - data := bytes.Repeat([]byte{0xA7}, pcChunkBlocks*4096) - wrapped := &publishAfterAbsentRead{ChunkRemote: remote, beforeReturn: func() { - if err := remote.Put(ctx, "old-cut", data); err != nil { - t.Fatal(err) - } - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7, - Chunks: map[uint64]storage.ChunkRef{0: {Key: "old-cut", SHA256: sha256.Sum256(data)}}}); err != nil { - t.Fatal(err) - } - }} - p := chunkProvider(t, t.TempDir(), wrapped, v1View(), 0) - s, err := p.EnsureStorage("v1") - if err != nil { - t.Fatal(err) - } - _, err = p.RecoverVolume(ctx, "v1") - if err != nil { - backend, openErr := p.Open(ctx, "v1") - if openErr != nil { - t.Fatal(openErr) - } - if _, readErr := backend.Read(ctx, 0, make([]byte, 4096)); !errors.Is(readErr, frontend.ErrNotReady) { - t.Fatal("failed attach admitted I/O", readErr) - } - if _, err = p.RecoverVolume(ctx, "v1"); err != nil { - t.Fatal("retry must claim and seed", err) - } - } - h, err := remote.GetHead(ctx) - if err != nil || h.Epoch != 3 || h.Holder != "r1" { - t.Fatalf("ready without ownership: HEAD=%+v err=%v", h, err) - } - if r, _, h := s.(*storage.WALStore).Boundaries(); r != 7 || h != 7 { - t.Fatalf("ready without seed: R=%d H=%d", r, h) - } - if got, err := s.Read(0); err != nil || !bytes.Equal(got, data[:4096]) { - t.Fatal("exact lazy restore changed", err) - } - if cut, err := p.CaptureVolume(ctx, "v1"); err != nil || cut != 7 { - t.Fatal("capture after settled restore", cut, err) - } -} diff --git a/seaweed-block/core/frontend/durable/provider_seal_progress_test.go b/seaweed-block/core/frontend/durable/provider_seal_progress_test.go index f1d3c68a84..dee6577f1d 100644 --- a/seaweed-block/core/frontend/durable/provider_seal_progress_test.go +++ b/seaweed-block/core/frontend/durable/provider_seal_progress_test.go @@ -9,20 +9,37 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) type sealProgressRemote struct { - *storage.MemChunkRemote - mu sync.Mutex - expire context.CancelCauseFunc - keys []string - images map[[32]byte]int - bytes int - calls int + storage.ChunkRemote + layoutRemote *chunkstore.LayoutRemote + keyer storage.ChunkKeyer + aborter storage.ChunkRemote + mu sync.Mutex + expire context.CancelCauseFunc + keys []string + images map[[32]byte]int + bytes int + calls int } +func (r *sealProgressRemote) AbortOpenSession(ctx context.Context) (string, error) { + return r.layoutRemote.AbortOpenSession(ctx) +} +func (r *sealProgressRemote) ReadHead(ctx context.Context) (layout.Head, error) { + return r.layoutRemote.ReadHead(ctx) +} + +func (r *sealProgressRemote) ChunkKey(idx uint64, sum [32]byte) string { + return r.keyer.ChunkKey(idx, sum) +} +func (r *sealProgressRemote) Abort() { r.aborter.Abort() } + func (r *sealProgressRemote) Put(ctx context.Context, key string, b []byte) error { if err := ctx.Err(); err != nil { return err @@ -35,7 +52,7 @@ func (r *sealProgressRemote) Put(ctx context.Context, key string, b []byte) erro r.expire = nil return context.DeadlineExceeded } - if err := r.MemChunkRemote.Put(ctx, key, b); err != nil { + if err := r.ChunkRemote.Put(ctx, key, b); err != nil { return err } r.keys = append(r.keys, key) @@ -53,16 +70,19 @@ func TestPlainSealDeadlineRetryUploadsOnlyRemainingChunks(t *testing.T) { defer stop() first, expire := context.WithCancelCause(parent) defer expire(context.Canceled) - remote := &sealProgressRemote{MemChunkRemote: storage.NewMemChunkRemote(), expire: expire, images: map[[32]byte]int{}} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, - NumBlocks: chunks * pcChunkBlocks, ChunkBlocks: pcChunkBlocks, ChunkUploadConcurrency: 1, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = p.Close() }) + c := newLayoutCase(t, chunks*pcChunkBlocks, pcChunkBlocks) + remote := &sealProgressRemote{expire: expire, images: map[[32]byte]int{}} + p := c.provider(t, t.TempDir(), v1View(), "s/r1", func(cfg *durable.ProviderConfig) { + cfg.ChunkUploadConcurrency = 1 + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + r, err := chunkstore.NewLayoutRemote(c.cat, c.ref, me) + if err != nil { + return nil, err + } + remote.ChunkRemote, remote.layoutRemote, remote.keyer, remote.aborter = r, r, r, r + return remote, nil + } + }) openRecovered(t, p) b, err := p.Open(parent, "v1") if err != nil { @@ -94,21 +114,46 @@ func TestPlainSealDeadlineRetryUploadsOnlyRemainingChunks(t *testing.T) { t.Fatalf("first attempt progress: calls=%d successful=%d bytes=%d", remote.calls, len(remote.keys), remote.bytes) } firstKeys := append([]string(nil), remote.keys...) + if _, _, err := p.DetachVolumePlain(parent, "v1"); !errors.Is(err, durable.ErrDetachAborted) || !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("staged chunks from the ended session were accepted: %v", err) + } r, last, err := p.DetachVolumePlain(parent, "v1") if err != nil || r.Head.State != storage.ChunkHeadDetached || r.H != last || r.Head.RemoteLSN != last { t.Fatalf("plain seal retry failed: %+v last=%d err=%v", r, last, err) } - if len(remote.keys) != chunks || remote.bytes != chunks*chunkBytes { - t.Fatalf("plain seal retransmitted completed chunks: successful=%d bytes=%d want=%d", len(remote.keys), remote.bytes, chunks*chunkBytes) + if len(remote.keys) != 2*chunks || remote.bytes != 2*chunks*chunkBytes { + t.Fatalf("the refused cut did not restage in its new session: successful=%d bytes=%d", len(remote.keys), remote.bytes) } - for sum, n := range remote.images { - if n != 1 { - t.Errorf("reuploaded unchanged payload %x count=%d", sum, n) + if len(remote.images) != chunks { + t.Fatalf("restaged image has %d distinct payloads, want %d", len(remote.images), chunks) + } + for _, n := range remote.images { + if n != 2 { + t.Fatalf("unexpected session PUT count %d", n) } } + // The kernel requires a Put in the new session, but the content-named + // filer entry is reused by a conditional metadata update, not a blob PUT. + c.blobs.Lock() + physical := map[[32]byte]int{} + for _, raw := range c.blobs.blobs { + physical[sha256.Sum256(raw)]++ + } + c.blobs.Unlock() + for i := 0; i < chunks; i++ { + raw := make([]byte, chunkBytes) + copy(raw, block(byte(0x40+i))) + if n := physical[sha256.Sum256(raw)]; n != 1 { + t.Fatalf("physical payload upload for chunk %d occurred %d times, want one", i, n) + } + } + committed, err := remote.GetHead(parent) + if err != nil { + t.Fatal(err) + } for _, key := range firstKeys { found := false - for _, ref := range r.Head.Chunks { + for _, ref := range committed.Chunks { if ref.Key == key { found = true } @@ -122,7 +167,7 @@ func TestPlainSealDeadlineRetryUploadsOnlyRemainingChunks(t *testing.T) { if lba%pcChunkBlocks == 0 { want = block(byte(0x40 + lba/pcChunkBlocks)) } - if !bytes.Equal(headBlock(t, remote.MemChunkRemote, uint32(lba)), want) { + if !bytes.Equal(c.block(t, uint32(lba)), want) { t.Fatalf("sealed image differs at lba=%d", lba) } } diff --git a/seaweed-block/core/frontend/durable/provider_seal_replay.go b/seaweed-block/core/frontend/durable/provider_seal_replay.go index aff4df244f..a77c099412 100644 --- a/seaweed-block/core/frontend/durable/provider_seal_replay.go +++ b/seaweed-block/core/frontend/durable/provider_seal_replay.go @@ -2,7 +2,9 @@ package durable import ( "context" + "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/storage" @@ -51,12 +53,7 @@ func (p *DurableProvider) replayPlainSeal(ctx context.Context, volumeID string, } h.chunkDetach = true p.stopChunkLoop(h) - inner, err := p.cfg.ChunkRemoteFor(volumeID) - if err != nil { - return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w", ErrDetachOutcomeUnknown, err) - } - remote := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx} - head, err := storage.ReadDetachedChunkHead(ctx, remote, proj.Epoch, p.chunkHolder(proj)) + head, err := p.readLayoutSeal(ctx, volumeID, h, proj) if err != nil { return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w", ErrDetachOutcomeUnknown, err) } @@ -73,3 +70,52 @@ func (p *DurableProvider) replayPlainSeal(ctx context.Context, volumeID string, result.H, result.Head = head.RemoteLSN, head return result, head.RemoteLSN, nil } + +// readLayoutSeal reads the same layout HEAD as Start; it never constructs a +// second runtime or falls back to the removed key/intent protocol. After a +// same-epoch detached restart there is no attached runtime, so the durable +// local claim id supplies the identity checked against the record. +func (p *DurableProvider) readLayoutSeal(ctx context.Context, volumeID string, h *volHandle, proj frontend.Projection) (storage.ChunkHead, error) { + ws, ok := h.storage.(*storage.WALStore) + if !ok { + return storage.ChunkHead{}, ErrNotChunkVolume + } + claim, _, present := ws.LayoutIdentity() + if !present || claim == "" { + return storage.ChunkHead{}, errors.New("durable: detached proof requires the local layout identity") + } + ctx, cancel := context.WithCancel(ctx) + stop := context.AfterFunc(p.closeCtx, cancel) + defer func() { stop(); cancel() }() + var head layout.Head + var err error + if remote, ok := h.layoutRemote.(interface { + ReadHead(context.Context) (layout.Head, error) + }); ok { + head, err = remote.ReadHead(ctx) + } else { + var st layout.StartStore + st, err = p.cfg.ChunkLayoutHeadFor(volumeID) + if err == nil && st == nil { + err = errors.New("durable: nil layout store for detached proof") + } + if err == nil { + var found bool + head, found, err = st.ReadHead(ctx) + if err == nil && !found { + err = layout.ErrHeadAbsent + } + } + } + if err != nil { + return storage.ChunkHead{}, err + } + me := layout.HolderID{Epoch: proj.Epoch, Holder: p.chunkHolder(proj), ClaimID: claim} + if head.Epoch != me.Epoch || head.Holder != me.Holder || head.ClaimID != me.ClaimID { + return storage.ChunkHead{}, ErrChunkEpochStale + } + if !layout.DetachedBy(head, me) { + return storage.ChunkHead{}, errors.New("durable: layout HEAD is not detached") + } + return layoutDetachResult(head).Head, nil +} diff --git a/seaweed-block/core/frontend/durable/provider_seed_linux_test.go b/seaweed-block/core/frontend/durable/provider_seed_linux_test.go index 9d59f9d211..20cacbf045 100644 --- a/seaweed-block/core/frontend/durable/provider_seed_linux_test.go +++ b/seaweed-block/core/frontend/durable/provider_seed_linux_test.go @@ -4,8 +4,6 @@ package durable_test import ( "bytes" - "context" - "crypto/sha256" "errors" "os" "path/filepath" @@ -15,24 +13,11 @@ import ( "testing" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) -type seedSyncFaultRemote struct { - storage.ChunkRemote - once sync.Once - beforeSeed func() -} - -func (r *seedSyncFaultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { - head, err := r.ChunkRemote.GetHead(ctx) - if err == nil { - r.once.Do(r.beforeSeed) - } - return head, err -} - // Replace only this fixture's WAL descriptor after Recover has read it and // before the seed's real os.File.Sync. /dev/full fsync returns EINVAL. Restore // the original open-file description before retry; no production fault seam. @@ -85,80 +70,60 @@ func failSeedFD(t *testing.T, root string) func() { return restore } +// A real failed WAL fsync during a B restore must keep the guest closed. +// The store's fsync failure is sticky; reopening the same local root retries +// from the unchanged published B image. func TestRestoreFailedSeedSyncRetryCaptureAndReopen(t *testing.T) { ctx := hangGuard(t) + c, position, data := seededLayoutForSyncFault(t) root := filepath.Join(t.TempDir(), "provider") - remote := storage.NewMemChunkRemote() - data := bytes.Repeat([]byte{0xA7}, 4*4096) - if err := remote.Put(ctx, "seed", data); err != nil { - t.Fatal(err) - } - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 3, Holder: "r1", RemoteLSN: 7, - Chunks: map[uint64]storage.ChunkRef{0: {Key: "seed", SHA256: sha256.Sum256(data)}}}); err != nil { - t.Fatal(err) - } var restore func() - fault := &seedSyncFaultRemote{ChunkRemote: remote, beforeSeed: func() { restore = failSeedFD(t, root) }} - makeProvider := func(r storage.ChunkRemote) *durable.DurableProvider { - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, - NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, WALRecoveryTestDisableFlusher: true, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, v1View()) - if err != nil { - t.Fatal(err) + p := c.provider(t, root, v1View(), "r1", func(cfg *durable.ProviderConfig) { + cfg.WALRecoveryTestDisableFlusher = true + next := cfg.ChunkLayoutRemoteFor + cfg.ChunkLayoutRemoteFor = func(name string, me layout.HolderID) (storage.ChunkRemote, error) { + restore = failSeedFD(t, root) + return next(name, me) } - t.Cleanup(func() { _ = p.Close() }) - return p - } - p := makeProvider(fault) + }) s, err := p.EnsureStorage("v1") if err != nil { t.Fatal(err) } ws := s.(*storage.WALStore) - if _, err := p.RecoverVolume(ctx, "v1"); err == nil { - t.Fatal("real seed fsync failure was accepted") - } else if !errors.Is(err, syscall.EINVAL) { - t.Fatalf("expected real fsync EINVAL, got %v", err) - } else { - t.Logf("injected real WAL fsync failure: %v", err) + if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, syscall.EINVAL) { + t.Fatalf("real seed fsync should fail with EINVAL: %v", err) } if restore == nil { - t.Fatal("fault not exercised") + t.Fatal("real fsync fault not exercised") } restore() - blocked, err := p.Open(ctx, "v1") - if err != nil { - t.Fatal(err) - } - if _, err := blocked.Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) { - t.Fatalf("failed recovery exposed backend: %v", err) + if _, err := p.Backend("v1").Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("failed recovery exposed guest I/O: %v", err) } if got := ws.NextLSN(); got != 1 { - t.Errorf("failed seed published allocator watermark %d, want 1", got) + t.Fatalf("failed seed advanced allocator to %d", got) } - // The failed fsync is sticky for the open store (storage.ErrFsyncFailed, - // io_error): no same-handle retry; a reopen restores from HEAD. if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrFsyncFailed) { - t.Fatalf("same-handle retry after a failed fsync: %v; want ErrFsyncFailed", err) + t.Fatalf("same-handle retry after failed fsync: %v", err) } - if r, _, h := ws.Boundaries(); r != 0 || h != 0 { - t.Errorf("refused retry published R=%d H=%d", r, h) + if err := p.Close(); !errors.Is(err, storage.ErrFsyncFailed) { + t.Fatalf("close must report the sticky fsync failure: %v", err) } - _ = p.Close() - p1 := makeProvider(remote) + p1 := c.provider(t, root, v1View(), "r1", nil) if _, err := p1.EnsureStorage("v1"); err != nil { t.Fatal(err) } if _, err := p1.RecoverVolume(ctx, "v1"); err != nil { - t.Fatal("restore after a reopen:", err) + t.Fatal("restore after reopen:", err) } - if cut, err := p1.CaptureVolume(ctx, "v1"); err != nil || cut != 7 { - t.Errorf("cut after a reopen=%d err=%v, want 7", cut, err) + if _, err := p1.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) } if err := p1.Close(); err != nil { t.Fatal(err) } - p2 := makeProvider(remote) + p2 := c.provider(t, root, v1View(), "r1", nil) s2, err := p2.EnsureStorage("v1") if err != nil { t.Fatal(err) @@ -166,87 +131,98 @@ func TestRestoreFailedSeedSyncRetryCaptureAndReopen(t *testing.T) { if _, err := p2.RecoverVolume(ctx, "v1"); err != nil { t.Fatal(err) } - if next := s2.(*storage.WALStore).NextLSN(); next != 8 { - t.Errorf("reopen nextLSN=%d, want 8", next) - } - b, err := p2.Open(ctx, "v1") - if err != nil { - t.Fatal(err) + if next := s2.(*storage.WALStore).NextLSN(); next <= position { + t.Fatalf("reopen nextLSN=%d, published position=%d", next, position) } got := make([]byte, 4096) - if _, err := b.Read(ctx, 0, got); err != nil || !bytes.Equal(got, data[:4096]) { - t.Fatal("restored bytes changed:", err) + if _, err := p2.Backend("v1").Read(ctx, 0, got); err != nil || !bytes.Equal(got, data) { + t.Fatalf("restored bytes changed: %v", err) } - if _, err := b.Write(ctx, 4096, bytes.Repeat([]byte{0xB8}, 4096)); err != nil { + if _, err := p2.Backend("v1").Write(ctx, 4096, bytes.Repeat([]byte{0xB8}, 4096)); err != nil { t.Fatal(err) } - if err := b.Sync(ctx); err != nil { + if err := p2.Backend("v1").Sync(ctx); err != nil { t.Fatal(err) } - if cut, err := p2.CaptureVolume(ctx, "v1"); err != nil || cut != 8 { - t.Fatalf("new cut=%d err=%v, want 8", cut, err) + if cut, err := p2.CaptureVolume(ctx, "v1"); err != nil || cut <= position { + t.Fatalf("new cut=%d err=%v, prior position=%d", cut, err, position) } } -func TestRestoreFailedSeedNeverTakesOwnership(t *testing.T) { +func seededLayoutForSyncFault(t *testing.T) (*layoutCase, uint64, []byte) { + t.Helper() ctx := hangGuard(t) + c := newLayoutCase(t, 64, 4) + source := c.provider(t, t.TempDir(), viewAs("old", 1), "old", nil) + s := openRecovered(t, source) + data := bytes.Repeat([]byte{0xA7}, 4096) + if _, err := s.Write(0, data); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := source.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + position := c.head(t).Position + if position == 0 { + t.Fatal("source did not publish B image") + } + if err := source.Close(); err != nil { + t.Fatal(err) + } + return c, position, data +} + +// B may claim before local seed. A failed seed may leave that claim in HEAD, +// but it cannot change the published image or admit a guest write. +func TestRestoreFailedSeedNeverServesOrChangesImage(t *testing.T) { + ctx := hangGuard(t) + c, position, data := seededLayoutForSyncFault(t) + before := c.head(t) root := filepath.Join(t.TempDir(), "provider") - remote := storage.NewMemChunkRemote() - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7}); err != nil { - t.Fatal(err) - } - calls := 0 - watched := &takeoverOrderRemote{ChunkRemote: remote, beforeCAS: func() { calls++ }} var restore func() - fault := &seedSyncFaultRemote{ChunkRemote: watched, beforeSeed: func() { restore = failSeedFD(t, root) }} - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, WALRecoveryTestDisableFlusher: true, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return fault, nil }}, v1View()) - if err != nil { + p := c.provider(t, root, v1View(), "r1", func(cfg *durable.ProviderConfig) { + cfg.WALRecoveryTestDisableFlusher = true + next := cfg.ChunkLayoutRemoteFor + cfg.ChunkLayoutRemoteFor = func(name string, me layout.HolderID) (storage.ChunkRemote, error) { + restore = failSeedFD(t, root) + return next(name, me) + } + }) + if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } - defer p.Close() - if _, err = p.EnsureStorage("v1"); err != nil { - t.Fatal(err) - } - if _, err = p.RecoverVolume(ctx, "v1"); !errors.Is(err, syscall.EINVAL) { + if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, syscall.EINVAL) { t.Fatalf("seed sync should fail with EINVAL: %v", err) } if restore == nil { t.Fatal("real fsync fault not exercised") } restore() - h, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if calls != 0 || h.Gen != 1 || h.Epoch != 1 || h.Holder != "old" || h.RemoteLSN != 7 { - t.Fatalf("failed seed changed authority: CAS=%d HEAD=%+v; want untouched old HEAD", calls, h) + after := c.head(t) + if after.Position != position || after.Current == nil || before.Current == nil || *after.Current != *before.Current { + t.Fatalf("failed seed changed published image: before=%+v after=%+v", before, after) } if _, err := p.Backend("v1").Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) { - t.Fatal("failed seed admitted I/O", err) + t.Fatalf("failed seed admitted I/O: %v", err) } - // The failed fsync is sticky (storage.ErrFsyncFailed): the same-store - // retry refuses and still takes no ownership; a reopen takes it once. if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrFsyncFailed) { - t.Fatalf("same-store retry after a failed fsync: %v; want ErrFsyncFailed", err) + t.Fatalf("same-store retry after failed fsync: %v", err) } - if calls != 0 { - t.Fatal("a refused retry took ownership", calls) + if err := p.Close(); !errors.Is(err, storage.ErrFsyncFailed) { + t.Fatalf("close must report the sticky fsync failure: %v", err) } - _ = p.Close() - p2, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, WALRecoveryTestDisableFlusher: true, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return watched, nil }}, v1View()) - if err != nil { + again := c.provider(t, root, v1View(), "r1", nil) + if _, err := again.EnsureStorage("v1"); err != nil { t.Fatal(err) } - defer p2.Close() - if _, err = p2.EnsureStorage("v1"); err != nil { - t.Fatal(err) + if _, err := again.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal("reopen:", err) } - if _, err := p2.RecoverVolume(ctx, "v1"); err != nil { - t.Fatal("restore after a reopen", err) - } - if calls != 1 { - t.Fatal("restore after a reopen must take ownership exactly once", calls) + got := make([]byte, 4096) + if _, err := again.Backend("v1").Read(ctx, 0, got); err != nil || !bytes.Equal(got, data) { + t.Fatalf("reopen changed B image: %v", err) } } diff --git a/seaweed-block/core/frontend/durable/provider_seed_order_test.go b/seaweed-block/core/frontend/durable/provider_seed_order_test.go index 28428360e1..db545971da 100644 --- a/seaweed-block/core/frontend/durable/provider_seed_order_test.go +++ b/seaweed-block/core/frontend/durable/provider_seed_order_test.go @@ -2,81 +2,15 @@ package durable_test import ( "bytes" - "context" "errors" "fmt" - "sync/atomic" "testing" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" ) -type takeoverOrderRemote struct { - storage.ChunkRemote - beforeCAS func() -} - -func (r *takeoverOrderRemote) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) { - r.beforeCAS() - return r.ChunkRemote.CASHead(ctx, v, h) -} - -func TestRestoreSeedPrecedesTakeoverCAS(t *testing.T) { - ctx := hangGuard(t) - remote := storage.NewMemChunkRemote() - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7}); err != nil { - t.Fatal(err) - } - var p *durable.DurableProvider - var checked atomic.Bool - var calls atomic.Int32 - var nextAtCAS, durableAtCAS, headAtCAS uint64 - wrapped := &takeoverOrderRemote{ChunkRemote: remote, beforeCAS: func() { - calls.Add(1) - if !checked.Load() { - t.Error("takeover preceded VOLUME check") - } - s := p.LogicalStorage("v1") - nextAtCAS = s.NextLSN() - durableAtCAS, _, headAtCAS = s.Boundaries() - if _, err := p.Backend("v1").Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) { - t.Errorf("I/O admitted before takeover: %v", err) - } - }} - var err error - p, err = durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return wrapped, nil }, - ChunkAttachCheck: func(context.Context, string, durable.ChunkGeometry) error { checked.Store(true); return nil }, - }, v1View()) - if err != nil { - t.Fatal(err) - } - defer p.Close() - if _, err = p.EnsureStorage("v1"); err != nil { - t.Fatal(err) - } - if _, err = p.RecoverVolume(ctx, "v1"); err != nil { - t.Fatal(err) - } - if calls.Load() != 1 || nextAtCAS != 8 || durableAtCAS != 7 || headAtCAS != 7 { - t.Fatalf("takeover before durable seed: CAS calls=%d nextLSN=%d durable=%d head=%d; want 1/8/7/7", calls.Load(), nextAtCAS, durableAtCAS, headAtCAS) - } - be, err := p.Open(ctx, "v1") - if err != nil { - t.Fatal(err) - } - if _, err := be.Read(ctx, 0, make([]byte, 4096)); err != nil { - t.Fatal("ready after seed and takeover", err) - } - h, err := remote.GetHead(ctx) - if err != nil || h.Epoch != 3 || h.Holder != "r1" || h.RemoteLSN != 7 { - t.Fatal(h, err) - } - t.Logf("VOLUME check -> seed nextLSN=%d/durable=%d -> takeover -> serve", nextAtCAS, durableAtCAS) -} - // A storage restart between the successful plain seal and teardown must not // erase the proof the planned new host needs. Neither local-root nor fresh // same-assignment reopen may reactivate it or expose I/O. @@ -84,16 +18,10 @@ func TestRestoreEqualOwnerDetachedHEADStaysSealed(t *testing.T) { for _, local := range []bool{false, true} { t.Run(fmt.Sprint(local), func(t *testing.T) { ctx := hangGuard(t) - remote := storage.NewMemChunkRemote() + c := newLayoutCase(t, 64, 4) root := t.TempDir() makeProvider := func(root string, view *stubView, holder string) *durable.DurableProvider { - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: holder, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = p.Close() }) - return p + return c.provider(t, root, view, holder, nil) } source := makeProvider(root, v1View(), "node-a/r1") s := openRecovered(t, source) @@ -113,11 +41,11 @@ func TestRestoreEqualOwnerDetachedHEADStaysSealed(t *testing.T) { if _, err := restarted.EnsureStorage("v1"); err != nil { t.Fatal(err) } - if _, err := restarted.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) { + if _, err := restarted.RecoverVolume(ctx, "v1"); !errors.Is(err, layout.ErrDetached) && !errors.Is(err, layout.ErrMissingLocalRoot) { t.Errorf("sealed incarnation reopened for serving: %v", err) } - h := headHolder(t, remote) - if h.Gen != cut.Head.Gen || h.Epoch != cut.Head.Epoch || h.Holder != cut.Head.Holder || h.State != storage.ChunkHeadDetached || h.DetachedBy == nil || *h.DetachedBy != *cut.Head.DetachedBy || h.RemoteLSN != cut.H { + h := c.head(t) + if h.Gen != cut.Head.Gen || h.Epoch != cut.Head.Epoch || h.Holder != cut.Head.Holder || h.State != layout.StateDetached || h.Position != cut.H { t.Errorf("restart changed sealed proof: HEAD=%+v seal=%+v", h, cut.Head) } be, err := restarted.Open(ctx, "v1") @@ -127,7 +55,7 @@ func TestRestoreEqualOwnerDetachedHEADStaysSealed(t *testing.T) { if _, err := be.Read(ctx, 4096, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) { t.Errorf("sealed restart exposed I/O: %v", err) } - if !bytes.Equal(headBlock(t, remote, 1), want) { + if !bytes.Equal(c.block(t, 1), want) { t.Fatal("restart changed sealed bytes") } planned := makeProvider(t.TempDir(), viewAs("r2", 4), "node-b/r2") @@ -135,8 +63,8 @@ func TestRestoreEqualOwnerDetachedHEADStaysSealed(t *testing.T) { if got, err := loaded.Read(1); err != nil || !bytes.Equal(got, want) { t.Fatal("planned new holder could not load sealed image", err) } - taken := headHolder(t, remote) - if taken.State != storage.ChunkHeadActive || taken.Epoch != 4 || taken.Holder != "node-b/r2" || taken.Gen <= cut.Head.Gen || taken.RemoteLSN != cut.H { + taken := c.head(t) + if taken.State != layout.StateLive || taken.Epoch != 4 || taken.Holder != "node-b/r2" || taken.Gen <= cut.Head.Gen || taken.Position != cut.H { t.Fatalf("planned takeover did not consume preserved seal: %+v", taken) } }) diff --git a/seaweed-block/core/frontend/durable/provider_ship_rebase_order_test.go b/seaweed-block/core/frontend/durable/provider_ship_rebase_order_test.go index 0b74463ecc..94f62ca9c5 100644 --- a/seaweed-block/core/frontend/durable/provider_ship_rebase_order_test.go +++ b/seaweed-block/core/frontend/durable/provider_ship_rebase_order_test.go @@ -1,24 +1,16 @@ package durable_test -// The restored frontier seed moves the store's next LSN; the installed -// write observer's ship order must follow it inside PrepareRestore, after -// the seed and before the takeover CAS. A refused rebase fails the restore -// with HEAD still owned by its previous holder and I/O closed. - import ( + "bytes" "context" "errors" "sync" - "sync/atomic" "testing" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" ) -// countingRebaser records every ship-LSN rebase; refuseFrom > 0 refuses -// that call and every later one (1-based). type countingRebaser struct { mu sync.Mutex lsns []uint64 @@ -36,82 +28,75 @@ func (o *countingRebaser) RebaseShipLSN(lsn uint64) error { } return nil } - func (o *countingRebaser) seen() []uint64 { o.mu.Lock() defer o.mu.Unlock() return append([]uint64(nil), o.lsns...) } -// restoreWithObserver restores a fresh host from an epoch-1 HEAD at -// remote_lsn 7 with obs installed before recovery. atCAS runs right -// before the takeover CAS. Returns the recovery error. -func restoreWithObserver(t *testing.T, obs *countingRebaser, atCAS func(p *durable.DurableProvider)) (storage.ChunkRemote, *durable.DurableProvider, *atomic.Int32, error) { +// B may claim before seeding. Guest I/O remains closed until the local base +// and the observer's ship position have both settled. +func restoreWithObserver(t *testing.T, obs *countingRebaser) (*layoutCase, *durable.DurableProvider, uint64, error) { t.Helper() ctx := hangGuard(t) - remote := storage.NewMemChunkRemote() - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7}); err != nil { + c := newLayoutCase(t, 64, 4) + source := c.provider(t, t.TempDir(), viewAs("old", 1), "old", nil) + s := openRecovered(t, source) + writeSync(t, s, 0, 0x7a) + if _, err := source.CaptureVolume(ctx, "v1"); err != nil { t.Fatal(err) } - var p *durable.DurableProvider - calls := &atomic.Int32{} - wrapped := &takeoverOrderRemote{ChunkRemote: remote, beforeCAS: func() { - calls.Add(1) - atCAS(p) - }} - var err error - p, err = durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return wrapped, nil }, - ChunkAttachCheck: func(context.Context, string, durable.ChunkGeometry) error { return nil }, - }, v1View()) - if err != nil { + position := c.head(t).Position + if position == 0 { + t.Fatal("source did not publish a nonzero B position") + } + if err := source.Close(); err != nil { t.Fatal(err) } - t.Cleanup(func() { _ = p.Close() }) - if _, err = p.EnsureStorage("v1"); err != nil { + target := c.provider(t, t.TempDir(), v1View(), "r1", nil) + if _, err := target.EnsureStorage("v1"); err != nil { t.Fatal(err) } - if err := p.Backend("v1").SetWriteObserver(obs); err != nil { - t.Fatalf("observer install before recovery: %v", err) + if err := target.Backend("v1").SetWriteObserver(obs); err != nil { + t.Fatal(err) } - _, err = p.RecoverVolume(ctx, "v1") - return remote, p, calls, err + _, err := target.RecoverVolume(ctx, "v1") + return c, target, position, err } -func TestRestoreShipRebasePrecedesTakeoverCAS(t *testing.T) { +func TestRestoreShipRebasePrecedesFirstServe(t *testing.T) { obs := &countingRebaser{} - var atCAS []uint64 - var nextAtCAS uint64 - _, _, calls, err := restoreWithObserver(t, obs, func(p *durable.DurableProvider) { - atCAS = obs.seen() - nextAtCAS = p.LogicalStorage("v1").NextLSN() - }) + c, p, position, err := restoreWithObserver(t, obs) if err != nil { t.Fatal(err) } - if calls.Load() != 1 || nextAtCAS != 8 || len(atCAS) == 0 || atCAS[len(atCAS)-1] != nextAtCAS { - t.Fatalf("ship order not rebased to the seeded next LSN before the takeover CAS: CAS calls=%d nextLSN=%d rebases seen at CAS=%v; want 1, 8, last rebase 8", - calls.Load(), nextAtCAS, atCAS) + wantNext := p.LogicalStorage("v1").NextLSN() + seen := obs.seen() + if len(seen) < 2 || seen[len(seen)-1] != wantNext || wantNext <= position { + t.Fatalf("ship order not rebased before serving: rebases=%v next=%d B position=%d", seen, wantNext, position) + } + got := make([]byte, 4096) + if n, err := p.Backend("v1").Read(context.Background(), 0, got); err != nil || n != len(got) || !bytes.Equal(got, block(0x7a)) { + t.Fatalf("restored bytes before serving: n=%d err=%v", n, err) + } + if head := c.head(t); head.Position != position { + t.Fatalf("restore changed published position: %+v", head) } - t.Logf("rebases before CAS=%v (install, then post-seed); nextLSN at CAS=%d", atCAS, nextAtCAS) } -func TestRestoreRefusedShipRebaseKeepsHeadAndIOClosed(t *testing.T) { - obs := &countingRebaser{refuseFrom: 2} // install accepted, post-seed rebase refused - remote, p, calls, err := restoreWithObserver(t, obs, func(*durable.DurableProvider) {}) +func TestRestoreRefusedShipRebaseKeepsIOClosed(t *testing.T) { + obs := &countingRebaser{refuseFrom: 2} + c, p, position, err := restoreWithObserver(t, obs) if err == nil { - t.Fatal("restore succeeded although the observer refused the post-seed ship-LSN rebase") + t.Fatal("restore succeeded although observer refused post-seed rebase") } - ctx := hangGuard(t) - h, herr := remote.GetHead(ctx) - if herr != nil || calls.Load() != 0 || h.Epoch != 1 || h.Holder != "old" { - t.Fatalf("HEAD claimed despite a refused ship rebase: CAS calls=%d head=%+v err=%v; want 0 calls, epoch 1 holder old", calls.Load(), h, herr) + if head := c.head(t); head.Position != position { + t.Fatalf("refused restore changed published image: %+v", head) } - if _, rerr := p.Backend("v1").Read(ctx, 0, make([]byte, 4096)); !errors.Is(rerr, frontend.ErrNotReady) { - t.Fatalf("I/O after a refused ship rebase: %v; want ErrNotReady", rerr) + if _, rerr := p.Backend("v1").Read(context.Background(), 0, make([]byte, 4096)); !errors.Is(rerr, frontend.ErrNotReady) { + t.Fatalf("I/O after refused ship rebase: %v; want ErrNotReady", rerr) } if got := obs.seen(); len(got) != 2 { t.Fatalf("rebases=%v; want install + post-seed", got) } - t.Logf("restore refused: %v", err) } diff --git a/seaweed-block/core/frontend/durable/provider_startup.go b/seaweed-block/core/frontend/durable/provider_startup.go index 313a29e712..3f3dc6fe43 100644 --- a/seaweed-block/core/frontend/durable/provider_startup.go +++ b/seaweed-block/core/frontend/durable/provider_startup.go @@ -4,6 +4,7 @@ import ( "errors" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -43,7 +44,12 @@ func (p *DurableProvider) endChunkStartup(h *volHandle, gen uint64, cause error) h.startupEnded = gen h.startupSuperseded = errors.Is(cause, errChunkForeignClaim) h.startupCure = "" - if errors.Is(cause, ErrChunkStaleLocalRoot) { + switch { + case errors.Is(cause, layout.ErrStaleLocalRoot): + h.startupCure = layout.StaleLocalRootCure + case errors.Is(cause, layout.ErrMissingLocalRoot): + h.startupCure = layout.MissingLocalRootCure + case errors.Is(cause, ErrChunkStaleLocalRoot): h.startupCure = ChunkStaleLocalRootCure } select { diff --git a/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go b/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go index d8741bd803..fe93654ab8 100644 --- a/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go +++ b/seaweed-block/core/frontend/durable/provider_startup_outcome_test.go @@ -8,7 +8,9 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -18,14 +20,17 @@ func TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome(t *testing.T) { logs := &lockedLog{} captureWriteLogs(t, logs) v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: time.Millisecond, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { - t.Error("remote reached without authority") - return storage.NewMemChunkRemote(), nil - }, - }, v) + } + testutil.NewLayoutFixture(t, "v1", 64, 4).Configure(&cfg) + start := cfg.ChunkLayoutHeadFor + cfg.ChunkLayoutHeadFor = func(name string) (layout.StartStore, error) { + t.Error("layout reached without authority") + return start(name) + } + p, err := durable.NewDurableProvider(cfg, v) if err != nil { t.Fatal(err) } @@ -64,9 +69,9 @@ func TestChunkStartupSealedAssignmentStaysForReplay(t *testing.T) { logs := &lockedLog{} captureWriteLogs(t, logs) ctx := hangGuard(t) - remote := storage.NewMemChunkRemote() + c := newLayoutCase(t, 64, 4) root := t.TempDir() - first := chunkProvider(t, root, remote, v1View(), 0) + first := c.provider(t, root, v1View(), "s/r1", nil) openRecovered(t, first) sealed, _, err := first.DetachVolumePlain(ctx, "v1") if err != nil { @@ -81,7 +86,7 @@ func TestChunkStartupSealedAssignmentStaysForReplay(t *testing.T) { waiting.Epoch = 0 waiting.Healthy = false view.set(waiting) - second := chunkProvider(t, root, remote, view, 0) + second := c.provider(t, root, view, "s/r1", nil) if _, err := second.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -124,7 +129,7 @@ func TestChunkStartupRetainedDispositionWinsExpiredAttachContext(t *testing.T) { waiting.Healthy = false view.set(waiting) var entered atomic.Bool - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkAssignmentTimeout: 250 * time.Millisecond, ChunkAttachCheck: func(ctx context.Context, _ string, _ durable.ChunkGeometry) error { @@ -132,11 +137,14 @@ func TestChunkStartupRetainedDispositionWinsExpiredAttachContext(t *testing.T) { <-ctx.Done() return tc.err }, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { - t.Error("retained attach reached remote") - return storage.NewMemChunkRemote(), nil - }, - }, view) + } + testutil.NewLayoutFixture(t, "v1", 64, 4).Configure(&cfg) + start := cfg.ChunkLayoutHeadFor + cfg.ChunkLayoutHeadFor = func(name string) (layout.StartStore, error) { + t.Error("retained attach reached layout") + return start(name) + } + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/provider_test.go b/seaweed-block/core/frontend/durable/provider_test.go index 310c0afd1c..91c3c4afba 100644 --- a/seaweed-block/core/frontend/durable/provider_test.go +++ b/seaweed-block/core/frontend/durable/provider_test.go @@ -234,6 +234,11 @@ func TestT3b_DurableProvider_Open_SelectsImpl_Matrix(t *testing.T) { if backend.Identity().VolumeID != "v1" { t.Errorf("Identity().VolumeID=%q want v1", backend.Identity().VolumeID) } + // Close the WAL descriptor before inspecting its bytes. Windows + // denies a second read handle while the provider holds its lock. + if err := p.Close(); err != nil { + t.Fatal(err) + } // Verify on-disk magic matches selector. magic, err := readFirstMagic(filepath.Join(root, "v1.bin")) if err != nil { diff --git a/seaweed-block/core/frontend/durable/provider_zero_bootstrap_test.go b/seaweed-block/core/frontend/durable/provider_zero_bootstrap_test.go deleted file mode 100644 index 28ac62a9da..0000000000 --- a/seaweed-block/core/frontend/durable/provider_zero_bootstrap_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package durable_test - -import ( - "bytes" - "context" - "fmt" - "github.com/seaweedfs/seaweed-block/core/frontend" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" - "sync" - "testing" -) - -type bootstrapBlobs struct { - mu sync.Mutex - objects map[string][]byte -} - -func (b *bootstrapBlobs) Put(_ context.Context, data []byte) (string, error) { - b.mu.Lock() - defer b.mu.Unlock() - id := fmt.Sprintf("fid-%d", len(b.objects)+1) - b.objects[id] = bytes.Clone(data) - return id, nil -} -func (b *bootstrapBlobs) Get(_ context.Context, id string) ([]byte, error) { - b.mu.Lock() - defer b.mu.Unlock() - data, ok := b.objects[id] - if !ok { - return nil, fmt.Errorf("missing blob %s", id) - } - return bytes.Clone(data), nil -} - -func TestRestoreEnsureVolumeZeroHEADPreservesCheckpointedBootstrap(t *testing.T) { - ctx := hangGuard(t) - filer := chunkstore.NewMemFiler() - catalog, err := chunkstore.NewCatalog(filer, "/bootstrap") - if err != nil { - t.Fatal(err) - } - remote, err := chunkstore.NewChunkRemote(filer, &bootstrapBlobs{objects: map[string][]byte{}}, "/bootstrap/v1") - if err != nil { - t.Fatal(err) - } - view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) - makeProvider := func(view *stubView) *durable.DurableProvider { - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkHolder: "node-a/r1", - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - ChunkAttachCheck: func(ctx context.Context, vol string, g durable.ChunkGeometry) error { - _, err := catalog.EnsureVolume(ctx, vol, chunkstore.Geometry{NumBlocks: g.NumBlocks, BlockSize: g.BlockSize, ChunkBlocks: g.ChunkBlocks}) - return err - }, - }, view) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = p.Close() }) - return p - } - p := makeProvider(view) - s := openRecovered(t, p) - ws := s.(*storage.WALStore) - want := block(0xD7) - lsn, err := s.Write(33, want) - if err != nil { - t.Fatal(err) - } - if _, err = s.Sync(); err != nil { - t.Fatal(err) - } - awaitRestoreCondition(t, ctx, "checkpointed local bootstrap", func() bool { return ws.CheckpointLSN() >= lsn && ws.FlushCount() > 0 }) - // This production attach hook, rather than a manufactured fixture HEAD, - // creates the initial ZERO image after the write has left the dirty map. - _, err = catalog.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks}) - if err != nil { - t.Fatal(err) - } - h, err := remote.GetHead(ctx) - if err != nil || h.Gen == 0 || h.RemoteLSN != 0 || len(h.Chunks) != 0 { - t.Fatalf("initial ZERO HEAD: %+v %v", h, err) - } - view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1})) - // The bootstrap's dirty set is unknown: it is reconciled against the - // ZERO HEAD before cuts resume. - awaitRestoreCondition(t, ctx, "ZERO HEAD bootstrap attachment and reconciliation", func() bool { - st := p.DurableStatuses() - return len(st) == 1 && st[0].Operational && st[0].Chunk != nil && st[0].Chunk.Attached && !st[0].Chunk.Stats.Reconciling - }) - if got, err := p.CaptureVolume(ctx, "v1"); err != nil || got != lsn { - t.Fatalf("capture=%d want=%d err=%v", got, lsn, err) - } - fresh := makeProvider(v1View()) - got, err := openRecovered(t, fresh).Read(33) - if err != nil || !bytes.Equal(got, want) { - t.Fatalf("checkpointed local bytes lost on remote restore: exact=%v err=%v", bytes.Equal(got, want), err) - } -} diff --git a/seaweed-block/core/frontend/durable/recovery_permanent_test.go b/seaweed-block/core/frontend/durable/recovery_permanent_test.go index a45ada6517..00994bd7d8 100644 --- a/seaweed-block/core/frontend/durable/recovery_permanent_test.go +++ b/seaweed-block/core/frontend/durable/recovery_permanent_test.go @@ -9,6 +9,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -17,12 +18,13 @@ import ( // as a permanent cause. Ordinary awaiting-recovery readiness stays retryable. func TestRecoveryStoreFaultRemainsPermanentAtGuestIO(t *testing.T) { root := t.TempDir() - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, WALRecoveryTestDisableFlusher: true, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, v1View()) + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/durable/rolled_back_copy_test.go b/seaweed-block/core/frontend/durable/rolled_back_copy_test.go index a284a3045a..56fdf0fccb 100644 --- a/seaweed-block/core/frontend/durable/rolled_back_copy_test.go +++ b/seaweed-block/core/frontend/durable/rolled_back_copy_test.go @@ -7,10 +7,10 @@ import ( "io" "os" "path/filepath" - "strings" "testing" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -49,14 +49,14 @@ func copyRootFiles(t *testing.T, src, dst string) { // The durable-reopen rule: an existing root whose HEAD names this holder attaches // only if its local durable LSN reaches HEAD's remote_lsn. A rolled-back // copy of the root (a backup taken before the last cut) is refused with the -// stale-root refusal, as a no-retry (superseded) startup outcome, with the +// stale-root refusal, as a final no-retry startup outcome, with the // operator's cure; it makes no claim, never serves and is left as it was. An // exact copy of the root at HEAD, and the root's own restart, attach. func TestRolledBackCopyBelowHeadLSNIsRefused(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) root := t.TempDir() - a := chunkProvider(t, root, remote, v1View(), 0) + a := layoutChunkProvider(t, root, fixture, v1View(), 0) s := openRecovered(t, a) if _, err := s.Write(1, block(1)); err != nil { t.Fatal(err) @@ -71,7 +71,7 @@ func TestRolledBackCopyBelowHeadLSNIsRefused(t *testing.T) { backup := t.TempDir() copyRootFiles(t, root, backup) // durable LSN at the first cut - a = chunkProvider(t, root, remote, v1View(), 0) + a = layoutChunkProvider(t, root, fixture, v1View(), 0) s = openRecovered(t, a) // the root's own restart if _, err := s.Write(2, block(2)); err != nil { t.Fatal(err) @@ -82,33 +82,29 @@ func TestRolledBackCopyBelowHeadLSNIsRefused(t *testing.T) { if err := a.Close(); err != nil { t.Fatal(err) } - head, _ := remote.GetHead(ctx) + head := layoutHead(t, fixture) exact := t.TempDir() copyRootFiles(t, root, exact) // durable LSN at HEAD - puts := remote.Puts() + puts := fixture.Blobs.Puts() - observed := &casObservedRemote{ChunkRemote: remote} - b := chunkProvider(t, backup, observed, v1View(), 0) + b := layoutChunkProvider(t, backup, fixture, v1View(), 0) bs, err := b.EnsureStorage("v1") if err != nil { t.Fatal(err) } _, err = b.RecoverVolume(ctx, "v1") - if !errors.Is(err, durable.ErrChunkStaleLocalRoot) || !strings.Contains(err.Error(), "remove or quarantine the local root") { - t.Fatalf("a rolled-back copy attached under HEAD remote_lsn %d: %v; want the stale-root refusal", head.RemoteLSN, err) + if !errors.Is(err, layout.ErrStaleLocalRoot) { + t.Fatalf("a rolled-back copy attached under HEAD position %d: %v; want the stale-root refusal", head.Position, err) } gen, ended := b.ChunkStartupOutcome("v1") - if !ended || !b.ChunkStartupSuperseded("v1", gen) { - t.Fatalf("the rolled-back copy's startup: ended=%t superseded=%t, want a no-retry outcome", ended, b.ChunkStartupSuperseded("v1", gen)) + if !ended || b.ChunkStartupSuperseded("v1", gen) { + t.Errorf("the rolled-back copy's startup: ended=%t superseded=%t, want a final local-root refusal (not a foreign-holder claim)", ended, b.ChunkStartupSuperseded("v1", gen)) } - if cure := b.ChunkStartupCure("v1", gen); cure != durable.ChunkStaleLocalRootCure { - t.Fatalf("the startup end carries cure %q, want %q for the final exit line", cure, durable.ChunkStaleLocalRootCure) + if cure := b.ChunkStartupCure("v1", gen); cure != layout.StaleLocalRootCure { + t.Errorf("the startup end carries cure %q, want %q for the final exit line", cure, layout.StaleLocalRootCure) } - if after, _ := remote.GetHead(ctx); after.Gen != head.Gen || after.Epoch != head.Epoch || after.Holder != head.Holder || remote.Puts() != puts { - t.Fatalf("the refused copy claimed or wrote: HEAD gen %d -> %d, PUTs %d -> %d", head.Gen, after.Gen, puts, remote.Puts()) - } - if observed.cass != 0 { - t.Fatalf("the refused copy attempted %d HEAD CASes, want none", observed.cass) + if after := layoutHead(t, fixture); after.Gen != head.Gen || after.Epoch != head.Epoch || after.Holder != head.Holder || fixture.Blobs.Puts() != puts { + t.Fatalf("the refused copy claimed or wrote: HEAD gen %d -> %d, PUTs %d -> %d", head.Gen, after.Gen, puts, fixture.Blobs.Puts()) } if err := b.Backend("v1").AdmitsIO(); err == nil { t.Fatal("the refused copy admits I/O") @@ -129,18 +125,18 @@ func TestRolledBackCopyBelowHeadLSNIsRefused(t *testing.T) { t.Fatal(err) } - x := chunkProvider(t, exact, remote, v1View(), 0) + x := layoutChunkProvider(t, exact, fixture, v1View(), 0) if _, err := x.EnsureStorage("v1"); err != nil { t.Fatal(err) } if _, err := x.RecoverVolume(ctx, "v1"); err != nil { - t.Fatalf("an exact copy at HEAD remote_lsn %d was refused: %v", head.RemoteLSN, err) + t.Fatalf("an exact copy at HEAD position %d was refused: %v", head.Position, err) } if err := x.Close(); err != nil { t.Fatal(err) } - c := chunkProvider(t, root, remote, v1View(), 0) + c := layoutChunkProvider(t, root, fixture, v1View(), 0) if _, err := c.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -148,41 +144,4 @@ func TestRolledBackCopyBelowHeadLSNIsRefused(t *testing.T) { t.Fatalf("the root's own restart after its last cut was refused: %v", err) } - // The recheck on the exact claim image: HEAD advances at the same epoch - // and holder between the preliminary HEAD read and the claim's read - // (the original root cut again). An exact copy that passed the first - // read is then below HEAD and refused, with no CAS. - race := t.TempDir() - copyRootFiles(t, exact, race) - raced := &casObservedRemote{ChunkRemote: remote} - var advanced storage.ChunkHead - raced.onGetHead = func(n int) { - if n != 2 { - return - } - cur, err := remote.GetHead(ctx) - if err != nil { - t.Error(err) - return - } - next := cur - next.RemoteLSN = cur.RemoteLSN + 1 - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil { - t.Error(err) - } - advanced, _ = remote.GetHead(ctx) - } - y := chunkProvider(t, race, raced, v1View(), 0) - if _, err := y.EnsureStorage("v1"); err != nil { - t.Fatal(err) - } - if _, err := y.RecoverVolume(ctx, "v1"); !errors.Is(err, durable.ErrChunkStaleLocalRoot) { - t.Fatalf("HEAD advanced to remote_lsn %d (epoch %d) after the preliminary read; the claim recheck attached: %v", advanced.RemoteLSN, advanced.Epoch, err) - } - if advanced.Gen == 0 || advanced.Epoch != head.Epoch || advanced.Holder != head.Holder || raced.cass != 0 { - t.Fatalf("race control: advanced HEAD %+v (want same epoch %d, holder %q), CAS attempts %d (want 0)", advanced, head.Epoch, head.Holder, raced.cass) - } - if err := y.Close(); err != nil { - t.Fatal(err) - } } diff --git a/seaweed-block/core/frontend/durable/runtime_fence_test.go b/seaweed-block/core/frontend/durable/runtime_fence_test.go index d359d463a6..7a82386d86 100644 --- a/seaweed-block/core/frontend/durable/runtime_fence_test.go +++ b/seaweed-block/core/frontend/durable/runtime_fence_test.go @@ -6,7 +6,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) // INV-FE-PRIMARY-READY-OPERATIONAL-001 (condition A): a HEAD fence after @@ -26,8 +26,9 @@ func TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + // Move the provider's own layout HEAD, which its publications read. + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + p := layoutChunkProvider(t, t.TempDir(), fixture, v1View(), 0) s := openRecovered(t, p) if _, err := s.Write(1, block(1)); err != nil { t.Fatal(err) @@ -43,13 +44,16 @@ func TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational(t *testing.T) { t.Fatal(err) } - head, err := remote.GetHead(ctx) + store, err := fixture.Catalog.Store(fixture.Ref) if err != nil { t.Fatal(err) } + head := layoutHead(t, fixture) next := head next.Epoch, next.Holder = tc.epoch(head.Epoch), tc.holder - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next); err != nil { + next.ClaimID = "foreign-claim" + next.Gen++ + if err := store.UpdateHead(ctx, head.Gen, next); err != nil { t.Fatal(err) } if _, err := s.Write(2, block(2)); err != nil { @@ -57,6 +61,8 @@ func TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational(t *testing.T) { } if _, err := p.CaptureVolume(ctx, "v1"); err == nil { t.Fatal("a capture over another holder's HEAD succeeded") + } else { + t.Logf("foreign HEAD capture refused: %v", err) } // From the fence on, no I/O is admitted (before the watcher runs). if n, err := backend.Write(ctx, 3*4096, block(3)); err == nil || n != 0 { diff --git a/seaweed-block/core/frontend/durable/start_any_test.go b/seaweed-block/core/frontend/durable/start_any_test.go new file mode 100644 index 0000000000..87a8cc4056 --- /dev/null +++ b/seaweed-block/core/frontend/durable/start_any_test.go @@ -0,0 +1,7 @@ +package durable_test + +import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + +// anyStart is a local root that can start from any HEAD: these tests do +// not model the local store. +func anyStart(layout.Head) error { return nil } diff --git a/seaweed-block/core/frontend/durable/start_path_test.go b/seaweed-block/core/frontend/durable/start_path_test.go new file mode 100644 index 0000000000..d010d58af2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/start_path_test.go @@ -0,0 +1,68 @@ +package durable + +import ( + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// fakeRoot is a local store as the start decision reads it. +type fakeRoot struct { + base uint64 + complete bool + seedErr func(uint64) error +} + +func (r fakeRoot) InstalledBaseLSN() (uint64, bool) { return r.base, r.complete } +func (r fakeRoot) CanSeedChunkFrontier(p uint64) error { return r.seedErr(p) } + +var errNoNext = errors.New("no room for a next LSN") + +func seedsUnlessMax(p uint64) error { + if p == ^uint64(0) { + return errNoNext + } + return nil +} + +// The start decision over local-root states x HEAD positions: the path the +// root takes after its claim, and whether that path refuses (before the +// claim Start sees the same refusal). States from the code: a fresh root +// without a base seeds; with a completed base it keeps the base; with a base +// install in progress the seed refuses (the store's precondition); a +// non-fresh root continues. +func TestCanStartFrom_LocalRootStateByHeadPosition(t *testing.T) { + roots := map[string]struct { + root fakeRoot + fresh bool + }{ + "fresh, no base": {fakeRoot{seedErr: seedsUnlessMax}, true}, + "fresh, completed base at 5": {fakeRoot{base: 5, complete: true, seedErr: seedsUnlessMax}, true}, + "fresh, base in progress": {fakeRoot{seedErr: func(uint64) error { return errors.New("install in progress") }}, true}, + "fresh, local writes": {fakeRoot{seedErr: func(uint64) error { return errors.New("local writes beyond checkpoint") }}, true}, + "not fresh": {fakeRoot{seedErr: func(uint64) error { return errors.New("must not be asked") }}, false}, + } + heads := map[string]uint64{"position 0": 0, "position 3": 3, "position 9": 9, "position MaxUint64": ^uint64(0)} + // want: the path, then "ok" or "refused" + want := map[string]map[string]string{ + "fresh, no base": {"position 0": "seed ok", "position 3": "seed ok", "position 9": "seed ok", "position MaxUint64": "seed refused"}, + "fresh, completed base at 5": {"position 0": "base ok", "position 3": "base ok", "position 9": "base refused", "position MaxUint64": "base refused"}, + "fresh, base in progress": {"position 0": "seed refused", "position 3": "seed refused", "position 9": "seed refused", "position MaxUint64": "seed refused"}, + "fresh, local writes": {"position 0": "seed refused", "position 3": "seed refused", "position 9": "seed refused", "position MaxUint64": "seed refused"}, + "not fresh": {"position 0": "continue ok", "position 3": "continue ok", "position 9": "continue ok", "position MaxUint64": "continue ok"}, + } + name := map[startPath]string{startContinue: "continue", startSeed: "seed", startAttachBase: "base"} + for r, c := range roots { + for hn, pos := range heads { + path, err := canStartFrom(c.root, c.fresh, layout.Head{Position: pos}) + got := name[path] + " ok" + if err != nil { + got = name[path] + " refused" + } + if w, ok := want[r][hn]; !ok || got != w { + t.Errorf("%s on HEAD %s: %s; want %s", r, hn, got, w) + } + } + } +} diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index 7e1331c93f..e8b920121a 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -9,15 +9,15 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" - "github.com/seaweedfs/seaweed-block/core/storage" ) // External observers see the committed takeover HEAD while attachment is // held in the provider-owned worker, without a separate test goroutine. type heldTakeoverClaim struct { - storage.ChunkRemote + layout.StartStore claimed chan struct{} release chan struct{} once, releaseOnce sync.Once @@ -28,7 +28,7 @@ type heldTakeoverClaim struct { } func (r *heldTakeoverClaim) unblock() { r.releaseOnce.Do(func() { close(r.release) }) } -func (r *heldTakeoverClaim) GetHead(ctx context.Context) (storage.ChunkHead, error) { +func (r *heldTakeoverClaim) ReadHead(ctx context.Context) (layout.Head, bool, error) { // The permanent-outage case must hold outcome resolution as well as the // CAS reply: a committed CAS with readable HEAD can now settle after the // per-operation deadline. Unbounded diagnostic reads still see the root. @@ -39,17 +39,17 @@ func (r *heldTakeoverClaim) GetHead(ctx context.Context) (storage.ChunkHead, err select { case <-r.release: case <-ctx.Done(): - return storage.ChunkHead{}, ctx.Err() + return layout.Head{}, false, ctx.Err() } default: } } - return r.ChunkRemote.GetHead(ctx) + return r.StartStore.ReadHead(ctx) } -func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { - gen, err := r.ChunkRemote.CASHead(ctx, expected, next) +func (r *heldTakeoverClaim) UpdateHead(ctx context.Context, expected uint64, next layout.Head) error { + err := r.StartStore.UpdateHead(ctx, expected, next) if err != nil || next.Epoch != 4 { - return gen, err + return err } r.once.Do(func() { close(r.claimed) }) var expired <-chan time.Time @@ -57,9 +57,9 @@ func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkH select { case <-r.readRegistered: case <-r.release: - return gen, nil + return nil case <-ctx.Done(): - return gen, ctx.Err() + return ctx.Err() } timer := time.NewTimer(r.holdFor) defer timer.Stop() @@ -67,11 +67,11 @@ func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkH } select { case <-r.release: - return gen, nil + return nil case <-expired: - return gen, nil + return nil case <-ctx.Done(): - return gen, ctx.Err() + return ctx.Err() } } @@ -82,9 +82,21 @@ func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProv func pendingTakeoverReadWithRelease(t *testing.T, hold time.Duration) (*durable.DurableProvider, frontend.Backend, *nvme.IOHandler, func()) { t.Helper() - remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{}), holdFor: hold, readRegistered: make(chan struct{}), resolutionBlocked: make(chan struct{})} + fixture := seededLayoutFixture(t) + store, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + t.Fatal(err) + } + remote := &heldTakeoverClaim{StartStore: store, claimed: make(chan struct{}), release: make(chan struct{}), holdFor: hold, readRegistered: make(chan struct{}), resolutionBlocked: make(chan struct{})} view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) - p := chunkProvider(t, t.TempDir(), remote, view, 0) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks} + fixture.Configure(&cfg) + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return remote, nil } + p, err := durable.NewDurableProvider(cfg, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) // Registered after provider cleanup, so release precedes its worker join. t.Cleanup(remote.unblock) if _, err := p.EnsureStorage("v1"); err != nil { @@ -99,16 +111,11 @@ func pendingTakeoverReadWithRelease(t *testing.T, hold time.Duration) (*durable. case <-time.After(10 * time.Second): t.Fatal("takeover CAS never became visible") } - if hold == 0 { - select { - case <-remote.resolutionBlocked: - case <-time.After(30 * time.Second): - t.Fatal("permanent attach did not reach held outcome resolution") - } - } - head, err := remote.GetHead(context.Background()) - if err != nil || head.Epoch != 4 || head.Holder != "r1" { - t.Fatalf("takeover HEAD: %+v, %v", head, err) + // B Start remains inside the held UpdateHead reply. A later diagnostic + // ReadHead is optional; the committed HEAD below proves the wait is real. + head := layoutHead(t, fixture) + if head.Epoch != 4 || head.Holder != "r1" { + t.Fatalf("takeover HEAD: %+v", head) } backend, err := p.Open(context.Background(), "v1") if err != nil { diff --git a/seaweed-block/core/frontend/durable/testutil/layout_fixture.go b/seaweed-block/core/frontend/durable/testutil/layout_fixture.go new file mode 100644 index 0000000000..1ea0d62513 --- /dev/null +++ b/seaweed-block/core/frontend/durable/testutil/layout_fixture.go @@ -0,0 +1,95 @@ +// Package testutil supplies in-memory B-layout fixtures for provider tests. +package testutil + +import ( + "context" + "fmt" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type MemoryBlobs struct { + mu sync.Mutex + next uint64 + data map[string][]byte + // PutHook can hold or refuse a payload upload in a test. Set it before + // starting concurrent provider work. + PutHook func(context.Context) error + // GetHook observes or changes a fetched payload; nil uses the stored bytes. + GetHook func(context.Context, string, []byte) ([]byte, error) +} + +func (b *MemoryBlobs) Put(ctx context.Context, data []byte) (string, error) { + if b.PutHook != nil { + if err := b.PutHook(ctx); err != nil { + return "", err + } + } + b.mu.Lock() + defer b.mu.Unlock() + b.next++ + id := fmt.Sprintf("test-blob-%d", b.next) + b.data[id] = append([]byte(nil), data...) + return id, nil +} + +func (b *MemoryBlobs) Get(ctx context.Context, id string) ([]byte, error) { + b.mu.Lock() + v, ok := b.data[id] + copyV := append([]byte(nil), v...) + b.mu.Unlock() + if !ok { + return nil, chunkstore.ErrBlobNotFound + } + if b.GetHook != nil { + return b.GetHook(ctx, id, copyV) + } + return copyV, nil +} + +func (b *MemoryBlobs) Puts() uint64 { + b.mu.Lock() + defer b.mu.Unlock() + return b.next +} + +// LayoutFixture creates one B VOLUME and HEAD, retaining them across provider +// restarts. Tests can inspect Catalog and Ref instead of a legacy ChunkHead. +type LayoutFixture struct { + Catalog *chunkstore.BCatalog + Ref chunkstore.VolumeRef + Blobs *MemoryBlobs +} + +func NewLayoutFixture(t testing.TB, name string, blocks, chunkBlocks uint64) *LayoutFixture { + t.Helper() + if blocks == 0 || chunkBlocks == 0 { + t.Fatal("layout fixture requires nonzero geometry") + } + blobs := &MemoryBlobs{data: make(map[string][]byte)} + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), blobs, "/provider-test") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: name, ID: id} + if _, err := cat.CreateVolume(context.Background(), ref, layout.Geometry{SizeBytes: blocks * 4096, BlockSize: 4096, ChunkBytes: chunkBlocks * 4096}); err != nil { + t.Fatal(err) + } + return &LayoutFixture{Catalog: cat, Ref: ref, Blobs: blobs} +} + +func (f *LayoutFixture) Configure(cfg *durable.ProviderConfig) { + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return f.Catalog.Store(f.Ref) } + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(f.Catalog, f.Ref, me) + } +} diff --git a/seaweed-block/core/frontend/durable/volume_size_admission_test.go b/seaweed-block/core/frontend/durable/volume_size_admission_test.go index 5120e2951b..eea9f6e7d1 100644 --- a/seaweed-block/core/frontend/durable/volume_size_admission_test.go +++ b/seaweed-block/core/frontend/durable/volume_size_admission_test.go @@ -3,37 +3,41 @@ package durable_test import ( "context" "os" - "path/filepath" "strings" "testing" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) -func TestProviderCreateCapacityPrecedesFreshMarker(t *testing.T) { +func TestProviderCreateCapacityPrecedesLayoutAccess(t *testing.T) { root := t.TempDir() id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: ^uint32(0), BlockSize: 8192, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }}, newStubView(healthyProj(id))) + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: ^uint32(0), BlockSize: 8192, + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { + t.Fatal("capacity check must precede layout access") + return nil, nil + }, + ChunkLayoutRemoteFor: func(string, layout.HolderID) (storage.ChunkRemote, error) { + t.Fatal("capacity check must precede layout access") + return nil, nil + }, + }, newStubView(healthyProj(id))) if err != nil { t.Fatal(err) } t.Cleanup(func() { p.Close() }) - // A blocked marker path prevents a giant allocation even without admission. - parent := filepath.Join(root, "v1.bin.chunkfresh") - if err := os.Mkdir(parent, 0700); err != nil { - t.Fatal(err) - } _, err = p.Open(context.Background(), "v1") if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { - t.Fatalf("want capacity before marker, got %v", err) + t.Fatalf("want capacity before layout access, got %v", err) } entries, err := os.ReadDir(root) if err != nil { t.Fatal(err) } - if len(entries) != 1 || entries[0].Name() != "v1.bin.chunkfresh" { + if len(entries) != 0 { t.Fatalf("refused create wrote files: %v", entries) } } diff --git a/seaweed-block/core/frontend/ublk/target_latency_perf_test.go b/seaweed-block/core/frontend/ublk/target_latency_perf_test.go index 5389ef869c..30685204a7 100644 --- a/seaweed-block/core/frontend/ublk/target_latency_perf_test.go +++ b/seaweed-block/core/frontend/ublk/target_latency_perf_test.go @@ -11,7 +11,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) func TestTargetDurabilityLatencyPerf(t *testing.T) { @@ -23,8 +23,7 @@ func TestTargetDurabilityLatencyPerf(t *testing.T) { cfg := durable.ProviderConfig{Impl: kind, StorageRoot: t.TempDir(), NumBlocks: 256, BlockSize: 4096} if kind == durable.ImplWALStoreChunk { cfg.ChunkBlocks = 16 - remote := storage.NewMemChunkRemote() - cfg.ChunkRemoteFor = func(string) (storage.ChunkRemote, error) { return remote, nil } + testutil.NewLayoutFixture(t, "v1", 256, 16).Configure(&cfg) } p, err := durable.NewDurableProvider(cfg, targetPerfView{}) if err != nil { diff --git a/seaweed-block/core/host/master/auth_red_test.go b/seaweed-block/core/host/master/auth_red_test.go index beb74b033c..e11945a7b3 100644 --- a/seaweed-block/core/host/master/auth_red_test.go +++ b/seaweed-block/core/host/master/auth_red_test.go @@ -50,7 +50,7 @@ func startAuthMaster(t *testing.T) authMaster { } authn := auth.NewAuthenticator(table, nil) authn.SetAudit(auth.NewAuditLog(io.Discard, nil)) // strict calls need an audit log - h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{Gen: 2, Epoch: 1, Holder: "node-a/r1"}, nil }, diff --git a/seaweed-block/core/host/master/authz.go b/seaweed-block/core/host/master/authz.go index 6531bf2144..99ca4b9eec 100644 --- a/seaweed-block/core/host/master/authz.go +++ b/seaweed-block/core/host/master/authz.go @@ -16,6 +16,10 @@ import ( // move's admin check is MoveWorkspace's (auth.RequireRole). A method missing // here is refused (TestMasterAuthorizationTableCoversEveryMethod). var masterRules = map[string]auth.Rule{ + control.LifecycleService_GetVolume_FullMethodName: {Min: auth.RoleViewer}, + control.LifecycleService_ReserveVolumeDeletion_FullMethodName: {Min: auth.RoleAdmin, Strict: true}, + control.LifecycleService_CheckVolumeNoLiveLease_FullMethodName: {Min: auth.RoleViewer}, + control.ObservationService_ReportHeartbeat_FullMethodName: {Node: true}, control.ObservationService_ReportClusterEvent_FullMethodName: {Min: auth.RoleOperator}, diff --git a/seaweed-block/core/host/master/authz_test.go b/seaweed-block/core/host/master/authz_test.go index dc0dbeb9aa..31939c8312 100644 --- a/seaweed-block/core/host/master/authz_test.go +++ b/seaweed-block/core/host/master/authz_test.go @@ -40,10 +40,10 @@ func TestMasterAuthorizationTableCoversEveryMethod(t *testing.T) { if len(missing) > 0 || len(stale) > 0 { t.Fatalf("authorization table out of date: methods without a rule %v; rules without a method %v", missing, stale) } - // 26: SubscribeProbeRounds and AnswerProbe (the promotion probe round) - // are node-only, each for the caller's own server id. - if len(registered) != 26 { - t.Fatalf("%d registered methods; the table was written for 26: review the new ones", len(registered)) + // SubscribeProbeRounds and AnswerProbe (the promotion probe round) are + // node-only, each for the caller's own server id. + if len(registered) != 29 { + t.Fatalf("%d registered methods; the table was written for 29: review the new ones", len(registered)) } } @@ -77,7 +77,7 @@ func TestMasterOperatorMethodsAreStrict(t *testing.T) { t.Errorf("%s is named in notStrict but is not a non-strict operator method: drop the entry", m) } } - if strict != 10 { - t.Errorf("%d strict methods; the phase 0 set is 10 (update this count with the change that adds one)", strict) + if strict != 11 { + t.Errorf("%d strict methods; the phase 0 set is 11 (update this count with the change that adds one)", strict) } } diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 3bafaeac3a..59c5a0754f 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -29,6 +29,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/auth" "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/host/bootstrap" "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" @@ -83,6 +84,14 @@ type Config struct { WorkspaceMaxClockSkew time.Duration WorkspaceRPC bool WorkspaceHeadReader func(context.Context, string) (authority.WorkspaceHead, error) + // LayoutCreateVolume writes VOLUME then the unclaimed HEAD using the + // immutable identity and geometry in the persisted lifecycle record. + LayoutCreateVolume func(context.Context, lifecycle.VolumeSpec) error + // Restore creation reads the source VOLUME's immutable geometry before + // persisting the target, then replays CreateTarget using that record. + LayoutReadVolume func(context.Context, lifecycle.VolumeSpec) (layout.Volume, error) + LayoutReadHead func(context.Context, lifecycle.VolumeSpec) (layout.Head, error) + LayoutCreateTarget func(context.Context, lifecycle.VolumeSpec, lifecycle.VolumeSpec, string) error // FrontendPublicationRuntimeHTTP enables the frontend publication runtime // HTTP surface. It is disabled by default and only confirms a post-failback @@ -301,6 +310,15 @@ func New(cfg Config) (*Host, error) { h.ln = ln h.lifecycle = lifecycleStores if h.lifecycle != nil { + // Rebuild permanent grant exclusions before any request, publisher + // loop or lifecycle reconciliation can create positive validity. + for _, volume := range h.lifecycle.Deletions.CommittedVolumes() { + if err := h.Publisher().ReserveWorkspaceDeletion(context.Background(), volume, nil); err != nil { + _ = ln.Close() + _ = boot.Close() + return nil, fmt.Errorf("master.New: deletion reservation recovery: %w", err) + } + } if err := h.reconcileWorkspaceBindings(); err != nil { _ = ln.Close() _ = boot.Close() diff --git a/seaweed-block/core/host/master/journal_isolation.go b/seaweed-block/core/host/master/journal_isolation.go index 2bfbdc4c8f..fe6996584e 100644 --- a/seaweed-block/core/host/master/journal_isolation.go +++ b/seaweed-block/core/host/master/journal_isolation.go @@ -129,10 +129,10 @@ func (h *Host) colocatedTargetRefused(server string) bool { // volume), and no new placement chooses a co-located node. func (h *Host) reconcilePlacements(stores *LifecycleStores, nodes []lifecycle.NodeRegistration) []lifecycle.ReconcileResult { if !h.cfg.StrictJournalIsolation { - return lifecycle.ReconcilePlacement(stores.liveVolumes(), nodes, stores.Placements) + return lifecycle.ReconcilePlacement(h.readyVolumeRecords(stores.liveVolumes()), nodes, stores.Placements) } var out []lifecycle.ReconcileResult - for _, v := range stores.liveVolumes() { + for _, v := range h.readyVolumeRecords(stores.liveVolumes()) { placed := map[string]bool{} if p, ok := stores.Placements.GetPlacement(v.Spec.VolumeID); ok { for _, slot := range p.Slots { diff --git a/seaweed-block/core/host/master/journal_isolation_test.go b/seaweed-block/core/host/master/journal_isolation_test.go index a73e291f25..91b11462f0 100644 --- a/seaweed-block/core/host/master/journal_isolation_test.go +++ b/seaweed-block/core/host/master/journal_isolation_test.go @@ -46,7 +46,7 @@ func newIsolationRig(t *testing.T, strict bool, authorityDir, lifecycleDir strin func startIsolationRig(t *testing.T, strict bool, authorityDir, lifecycleDir string, self *storeident.Identity) *isolationRig { t.Helper() logs := &syncBuffer{} - m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authorityDir, LifecycleStoreDir: lifecycleDir, WorkspaceRPC: true, + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authorityDir, LifecycleStoreDir: lifecycleDir, WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, StrictJournalIsolation: strict, Logger: log.New(logs, "", 0), WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil diff --git a/seaweed-block/core/host/master/launcher_plan.go b/seaweed-block/core/host/master/launcher_plan.go index 901fe070b5..21105b451f 100644 --- a/seaweed-block/core/host/master/launcher_plan.go +++ b/seaweed-block/core/host/master/launcher_plan.go @@ -27,7 +27,7 @@ func (h *Host) RunLifecycleWorkloadPlanTick(cfg lifecycle.WorkloadPlanConfig) (L if stores == nil { return LifecycleWorkloadPlanTickResult{}, nil } - volumes := stores.Volumes.ListVolumes() + volumes := h.readyVolumeRecords(stores.Volumes.ListVolumes()) volumeByID := make(map[string]lifecycle.VolumeRecord, len(volumes)) for _, volume := range volumes { volumeByID[volume.Spec.VolumeID] = volume diff --git a/seaweed-block/core/host/master/layout_ready.go b/seaweed-block/core/host/master/layout_ready.go new file mode 100644 index 0000000000..2f4428c65e --- /dev/null +++ b/seaweed-block/core/host/master/layout_ready.go @@ -0,0 +1,37 @@ +package master + +import "github.com/seaweedfs/seaweed-block/core/lifecycle" + +// layoutStoreReady is a placement hint, not Start's safety check. Production +// layout masters install LayoutCreateVolume; older non-layout deployments do +// not use the filer-ready bit. +func (h *Host) layoutStoreReady(volume string) bool { + if !h.cfg.WorkspaceRPC && h.cfg.LayoutCreateVolume == nil { + return true + } + if h.lifecycle == nil || h.lifecycle.Volumes == nil { + return false + } + r, ok := h.lifecycle.Volumes.GetVolumeSnapshot(volume) + return ok && r.StoreReady +} + +func (h *Host) readyVolumeRecords(all []lifecycle.VolumeRecord) []lifecycle.VolumeRecord { + ready := make([]lifecycle.VolumeRecord, 0, len(all)) + for _, r := range all { + if h.layoutStoreReady(r.Spec.VolumeID) { + ready = append(ready, r) + } + } + return ready +} + +func (h *Host) readyPlacements(all []lifecycle.PlacementIntent) []lifecycle.PlacementIntent { + ready := make([]lifecycle.PlacementIntent, 0, len(all)) + for _, p := range all { + if h.layoutStoreReady(p.VolumeID) { + ready = append(ready, p) + } + } + return ready +} diff --git a/seaweed-block/core/host/master/layout_ready_guard_test.go b/seaweed-block/core/host/master/layout_ready_guard_test.go new file mode 100644 index 0000000000..b51b21a444 --- /dev/null +++ b/seaweed-block/core/host/master/layout_ready_guard_test.go @@ -0,0 +1,110 @@ +package master + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "reflect" + "strings" + "testing" +) + +// These are the record-to-placement and assignment decisions in this package. +// Reconcile and workload planning filter records; the product loop filters +// placements before both direct asks and RF3 promotion; workspaceVolume is the +// common RPC admission gate for binding, move, and publication. A new decision +// site must be listed here with a not-ready behavioral probe before it ships. +func TestLayoutStoreReadyDecisionSites(t *testing.T) { + want := map[string]int{ + "journal_isolation.go reconcilePlacements ReconcilePlacement": 2, + "journal_isolation.go reconcilePlacements readyVolumeRecords": 2, + "launcher_plan.go RunLifecycleWorkloadPlanTick PlanBlockVolumeWorkloads": 1, + "launcher_plan.go RunLifecycleWorkloadPlanTick readyVolumeRecords": 1, + "layout_ready.go readyPlacements layoutStoreReady": 1, + "layout_ready.go readyVolumeRecords layoutStoreReady": 1, + "lifecycle_snapshot.go verifyPlacements readyPlacements": 1, + "product_loop.go RunLifecycleProductTick SubmitAssignmentAsk": 2, + "product_loop.go RunLifecycleProductTick readyPlacements": 2, + "product_loop.go submitPlacementSnapshots readyPlacements": 1, + "workspace_binding.go PlaceWorkspace workspaceVolume": 1, + "workspace_binding.go RegisterWorkspaceBinding workspaceVolume": 1, + "workspace_binding.go admitWorkspacePublication layoutStoreReady": 1, + "workspace_service.go AckWorkspaceRevoked workspaceVolume": 1, + "workspace_service.go MoveWorkspace MoveWorkspace": 1, + "workspace_service.go MoveWorkspace workspaceVolume": 2, + "workspace_service.go PreviewWorkspaceMove workspaceVolume": 1, + "workspace_service.go QueryWorkspace workspaceVolume": 1, + "workspace_service.go QueryWorkspaceLostRange workspaceVolume": 1, + "workspace_service.go RevokeWorkspace workspaceVolume": 1, + "workspace_service.go workspaceVolume layoutStoreReady": 1, + "workspace_service.go workspaceVolumeForRenewal layoutStoreReady": 1, + } + got := map[string]int{} + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + for _, path := range files { + if strings.HasSuffix(path, "_test.go") { + continue + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + sites, err := layoutReadyDecisionSites(path, raw) + if err != nil { + t.Fatal(err) + } + for site, count := range sites { + got[site] += count + } + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("placement or assignment site changed; enumerate its ready guard and behavioral probe: got=%v want=%v", got, want) + } +} + +func layoutReadyDecisionSites(path string, raw []byte) (map[string]int, error) { + f, err := parser.ParseFile(token.NewFileSet(), path, raw, 0) + if err != nil { + return nil, err + } + methods := map[string]bool{ + "ReconcilePlacement": true, "PlanBlockVolumeWorkloads": true, + "SubmitAssignmentAsk": true, "MoveWorkspace": true, + "readyVolumeRecords": true, "readyPlacements": true, + "workspaceVolume": true, "layoutStoreReady": true, + } + out := map[string]int{} + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(node ast.Node) bool { + call, ok := node.(*ast.CallExpr) + if !ok { + return true + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if ok && methods[sel.Sel.Name] { + out[path+" "+fn.Name.Name+" "+sel.Sel.Name]++ + } + return true + }) + } + return out, nil +} + +func TestLayoutReadyEnumerationSeesANewAssignmentSite(t *testing.T) { + got, err := layoutReadyDecisionSites("new.go", []byte(`package master; func bypass(){ controller.SubmitAssignmentAsk(ask) }`)) + if err != nil { + t.Fatal(err) + } + if got["new.go bypass SubmitAssignmentAsk"] != 1 { + t.Fatal("new assignment site escaped enumeration", got) + } +} diff --git a/seaweed-block/core/host/master/layout_ready_test.go b/seaweed-block/core/host/master/layout_ready_test.go new file mode 100644 index 0000000000..f7280f309c --- /dev/null +++ b/seaweed-block/core/host/master/layout_ready_test.go @@ -0,0 +1,59 @@ +package master + +import ( + "context" + "testing" + + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestLayoutStoreNotReadyCannotBePlacedOrMoved(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + h.cfg.LayoutCreateVolume = func(context.Context, lifecycle.VolumeSpec) error { return nil } + h.cfg.WorkspaceRPC = true + stores := h.Lifecycle() + rec, err := stores.Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}) + if err != nil { + t.Fatal(err) + } + if _, err := stores.Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "10.0.0.2:9201", CtrlAddr: "10.0.0.2:9101", Pools: []lifecycle.StoragePool{{PoolID: "default", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096}}}); err != nil { + t.Fatal(err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + if _, ok := stores.Placements.GetPlacement("v"); ok { + t.Fatal("record without VOLUME and HEAD was placed") + } + // A persisted intent can predate a failed filer create (or survive a + // restart). Neither workload planning nor the product assignment loop + // may treat that intent as authority while store_ready is false. + if results := lifecycle.ReconcilePlacement([]lifecycle.VolumeRecord{rec}, stores.Nodes.ListNodes(), stores.Placements); len(results) != 1 || !results[0].Applied { + t.Fatalf("fixture placement: %+v", results) + } + plans, err := h.RunLifecycleWorkloadPlanTick(lifecycle.WorkloadPlanConfig{}) + if err != nil || plans.PlannedVolumes != 0 { + t.Fatalf("unready workload plans=%+v err=%v", plans, err) + } + tick, err := h.RunLifecycleProductTick() + if err != nil || tick.PublishedAsks != 0 || tick.PromotionProbes != 0 { + t.Fatalf("unready assignment/promotion tick=%+v err=%v", tick, err) + } + if err := newServices(h).workspaceVolume("v"); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("move admission before store ready: %v", err) + } + resp, err := newServices(h).CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}) + if err != nil || !resp.GetStoreReady() || resp.GetLayoutId() != rec.Spec.LayoutID { + t.Fatalf("healing create: response=%+v err=%v", resp, err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + if _, ok := stores.Placements.GetPlacement("v"); !ok { + t.Fatal("ready record was not placed") + } +} diff --git a/seaweed-block/core/host/master/lifecycle_service_test.go b/seaweed-block/core/host/master/lifecycle_service_test.go index 8861a983d5..ee87b37c06 100644 --- a/seaweed-block/core/host/master/lifecycle_service_test.go +++ b/seaweed-block/core/host/master/lifecycle_service_test.go @@ -2,15 +2,141 @@ package master import ( "context" + "errors" "reflect" "testing" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) +func TestRestoreCreateVolumePersistsRequestBeforeTargetAndHealsRetry(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + svc := newServices(h) + h.cfg.LayoutCreateVolume = func(context.Context, lifecycle.VolumeSpec) error { return nil } + if _, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "source", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + g := layout.Geometry{SizeBytes: 1 << 20, BlockSize: 4096, ChunkBytes: 4 << 20} + h.cfg.LayoutReadVolume = func(_ context.Context, source lifecycle.VolumeSpec) (layout.Volume, error) { + id, err := layout.ParseVolumeID(source.LayoutID) + return layout.Volume{ID: id, Name: source.VolumeID, Geometry: g, Format: layout.VolumeFormat}, err + } + h.cfg.LayoutReadHead = func(_ context.Context, source lifecycle.VolumeSpec) (layout.Head, error) { + id, _ := layout.ParseVolumeID(source.LayoutID) + return layout.Head{VolumeID: id, State: layout.StateLive, Snapshots: map[string]layout.Snapshot{"daily": {}}}, nil + } + var targetID string + var calls int + h.cfg.LayoutCreateTarget = func(_ context.Context, source, target lifecycle.VolumeSpec, snapshot string) error { + calls++ + rec, ok := h.Lifecycle().Volumes.GetVolume(target.VolumeID) + if !ok || rec.StoreReady || rec.Spec != target || snapshot != "daily" || source.VolumeID != "source" { + t.Fatalf("target called before durable request: %+v, source=%+v snapshot=%s", rec, source, snapshot) + } + if target.SourceLayoutID != source.LayoutID { + t.Fatalf("target did not bind source layout id: %+v source=%+v", target, source) + } + if targetID == "" { + targetID = target.LayoutID + } + if target.LayoutID != targetID || target.SizeBytes != g.SizeBytes || target.BlockSize != g.BlockSize || target.ChunkBytes != g.ChunkBytes { + t.Fatalf("target replay changed id or source geometry: %+v", target) + } + if calls == 1 { + return errors.New("interrupted after AddDependent") + } + return nil + } + req := &control.CreateVolumeRequest{VolumeId: "target", SourceVolume: "source", SourceSnapshot: "daily", CreateRequestId: "restore-1"} + if _, err := svc.CreateVolume(context.Background(), req); status.Code(err) != codes.Unavailable { + t.Fatalf("interrupted restore: %v; want retryable unavailable", err) + } + if rec, _ := h.Lifecycle().Volumes.GetVolume("target"); rec.StoreReady { + t.Fatal("interrupted restore became placeable") + } + resp, err := svc.CreateVolume(context.Background(), req) + if err != nil || !resp.GetStoreReady() || resp.GetLayoutId() != targetID || calls != 2 { + t.Fatalf("replay: %+v %v, calls=%d", resp, err, calls) + } + req.SourceSnapshot = "weekly" + if _, err := svc.CreateVolume(context.Background(), req); status.Code(err) != codes.AlreadyExists { + t.Fatalf("rebound request: %v; want conflict", err) + } + wrong := &control.CreateVolumeRequest{VolumeId: "wrong", SourceVolume: "source", SourceSnapshot: "missing", CreateRequestId: "restore-wrong"} + if _, err := svc.CreateVolume(context.Background(), wrong); status.Code(err) != codes.NotFound { + t.Fatalf("missing snapshot: %v; want not found", err) + } + if _, ok := h.Lifecycle().Volumes.GetVolume("wrong"); ok { + t.Fatal("missing snapshot created a target record") + } + h.cfg.LayoutReadHead = func(_ context.Context, source lifecycle.VolumeSpec) (layout.Head, error) { + id, _ := layout.ParseVolumeID(source.LayoutID) + return layout.Head{VolumeID: id, State: layout.StateDeleting, Snapshots: map[string]layout.Snapshot{"daily": {}}}, nil + } + deleting := &control.CreateVolumeRequest{VolumeId: "from-deleting", SourceVolume: "source", SourceSnapshot: "daily", CreateRequestId: "restore-deleting"} + if _, err := svc.CreateVolume(context.Background(), deleting); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("deleting source: %v; want refusal", err) + } + if _, ok := h.Lifecycle().Volumes.GetVolume("from-deleting"); ok { + t.Fatal("deleting source created a target record") + } + unsafe := &control.CreateVolumeRequest{VolumeId: "net-target", SourceVolume: "source", SourceSnapshot: "daily", CreateRequestId: "restore-net", ReplicationFactor: 2} + if _, err := svc.CreateVolume(context.Background(), unsafe); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("RF2 restore: %v; want refusal", err) + } + if _, ok := h.Lifecycle().Volumes.GetVolume("net-target"); ok { + t.Fatal("RF2 restore created a target record") + } + if _, err := svc.CreateVolume(context.Background(), &control.CreateVolumeRequest{VolumeId: "net-source", SizeBytes: 1 << 20, ReplicationFactor: 2}); err != nil { + t.Fatal(err) + } + unsafe = &control.CreateVolumeRequest{VolumeId: "from-net", SourceVolume: "net-source", SourceSnapshot: "daily", CreateRequestId: "restore-from-net"} + if _, err := svc.CreateVolume(context.Background(), unsafe); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("RF2 source restore: %v; want refusal", err) + } + if _, ok := h.Lifecycle().Volumes.GetVolume("from-net"); ok { + t.Fatal("RF2 source restore created a target record") + } +} + +func TestCreateVolumeRetriesFilerCreateBeforeStoreReady(t *testing.T) { + h := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, h) + failure := errors.New("filer unavailable") + var calls []lifecycle.VolumeSpec + h.cfg.LayoutCreateVolume = func(_ context.Context, spec lifecycle.VolumeSpec) error { + calls = append(calls, spec) + if len(calls) == 1 { + return failure + } + return nil + } + svc := newServices(h) + req := &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1} + if _, err := svc.CreateVolume(context.Background(), req); status.Code(err) != codes.Unavailable { + t.Fatalf("first create=%v, want retryable unavailable", err) + } + partial, ok := h.Lifecycle().Volumes.GetVolume("v") + if !ok || partial.StoreReady { + t.Fatalf("partial create advertised readiness: %+v", partial) + } + resp, err := svc.CreateVolume(context.Background(), req) + if err != nil || !resp.GetStoreReady() { + t.Fatalf("replay did not heal: response=%+v err=%v", resp, err) + } + if len(calls) != 2 || calls[0] != calls[1] || calls[0].LayoutID != partial.Spec.LayoutID { + t.Fatalf("replay changed persisted identity: calls=%+v partial=%+v", calls, partial) + } + if _, err := svc.CreateVolume(context.Background(), req); err != nil || len(calls) != 2 { + t.Fatalf("ready replay must not create an absent HEAD after service: calls=%d err=%v", len(calls), err) + } +} + func TestG15c_LifecycleService_CreateVolumePersistsDesiredIntent(t *testing.T) { h := newTestMaster(t, t.TempDir()) defer closeTestMaster(t, h) @@ -33,6 +159,12 @@ func TestG15c_LifecycleService_CreateVolumePersistsDesiredIntent(t *testing.T) { if resp.GetVolumeId() != "pvc-a" || resp.GetSizeBytes() != 1<<30 || resp.GetReplicationFactor() != 2 { t.Fatalf("response=%+v", resp) } + if resp.GetBlockSize() != 4096 || resp.GetChunkBytes() != 4<<20 { + t.Fatalf("response geometry=%+v", resp) + } + if resp.GetStoreReady() { + t.Fatal("record without filer creation advertised store readiness") + } if resp.GetPvcName() != "demo-pvc" || resp.GetPvcNamespace() != "demo-ns" || resp.GetPvcUid() != "uid-123" || resp.GetPvName() != "pvc-a" { t.Fatalf("kubernetes metadata response=%+v", resp) } @@ -49,6 +181,12 @@ func TestG15c_LifecycleService_CreateVolumePersistsDesiredIntent(t *testing.T) { if rec.Spec.VolumeID != "pvc-a" || rec.Spec.SizeBytes != 1<<30 || rec.Spec.ReplicationFactor != 2 { t.Fatalf("record=%+v", rec) } + if rec.Spec.BlockSize != 4096 || rec.Spec.ChunkBytes != 4<<20 { + t.Fatalf("record geometry=%+v", rec.Spec) + } + if resp.GetLayoutId() == "" || resp.GetLayoutId() != rec.Spec.LayoutID { + t.Fatal("create response does not carry the durable layout identity") + } if rec.Spec.Protocol != "nvme" { t.Fatalf("record protocol=%q want nvme", rec.Spec.Protocol) } diff --git a/seaweed-block/core/host/master/lifecycle_snapshot.go b/seaweed-block/core/host/master/lifecycle_snapshot.go index 96dd7ea02c..d2f09f2767 100644 --- a/seaweed-block/core/host/master/lifecycle_snapshot.go +++ b/seaweed-block/core/host/master/lifecycle_snapshot.go @@ -34,6 +34,7 @@ func (h *Host) LifecycleSnapshot() (LifecycleSnapshot, bool) { } func (h *Host) verifyPlacements(placements []lifecycle.PlacementIntent, nodes []lifecycle.NodeRegistration) []lifecycle.VerifiedPlacement { + placements = h.readyPlacements(placements) verified := make([]lifecycle.VerifiedPlacement, 0, len(placements)) var obsStore *authority.ObservationStore if h.obs != nil { diff --git a/seaweed-block/core/host/master/lifecycle_test.go b/seaweed-block/core/host/master/lifecycle_test.go index 61bfa48d24..8abdff4fcb 100644 --- a/seaweed-block/core/host/master/lifecycle_test.go +++ b/seaweed-block/core/host/master/lifecycle_test.go @@ -13,6 +13,18 @@ import ( "github.com/seaweedfs/seaweed-block/core/lifecycle" ) +// testLayoutCreateVolume stands in for the filer's two exclusive creates in +// authority tests; the product path uses BCatalog.CreateVolume instead. +func testLayoutCreateVolume(context.Context, lifecycle.VolumeSpec) error { return nil } + +func testCreateReadyVolume(store *lifecycle.FileStore, spec lifecycle.VolumeSpec) (lifecycle.VolumeRecord, error) { + rec, err := store.CreateVolume(spec) + if err != nil { + return rec, err + } + return store.MarkStoreReady(rec.Spec.VolumeID, rec.Spec.LayoutID) +} + func TestMasterLifecycleStore_OptionalNilByDefault(t *testing.T) { h := newTestMaster(t, "") defer closeTestMaster(t, h) diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index 27608411ec..09a1d0d906 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -97,7 +97,7 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) { // New placements never choose a co-located node under strict journal // isolation; existing placements still verify against every node. reconciled := h.reconcilePlacements(stores, nodes) - placements := stores.Placements.ListPlacements() + placements := h.readyPlacements(stores.Placements.ListPlacements()) verified := h.verifyPlacements(placements, nodes) result := LifecycleProductTickResult{ ReconciledVolumes: len(reconciled), @@ -113,7 +113,7 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) { } // A remote probe may have overlapped a placement/move/delete. Never use // its captured intent after that local intent has changed. - if !reflect.DeepEqual(placements, stores.Placements.ListPlacements()) { + if !reflect.DeepEqual(placements, h.readyPlacements(stores.Placements.ListPlacements())) { return result, nil } verified = h.verifyPlacements(placements, stores.Nodes.ListNodes()) @@ -170,6 +170,7 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) { } func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent) (bool, int, int, []authority.AssignmentAsk, error) { + placements = h.readyPlacements(placements) captured := placements if h.obs == nil || h.ctrl == nil { diff --git a/seaweed-block/core/host/master/server_host_identity_test.go b/seaweed-block/core/host/master/server_host_identity_test.go index ddd79a481e..5480afa917 100644 --- a/seaweed-block/core/host/master/server_host_identity_test.go +++ b/seaweed-block/core/host/master/server_host_identity_test.go @@ -27,7 +27,7 @@ import ( // holder; the old host, still reporting the replica id with a newer observation, wins none of them. func TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot(t *testing.T) { heads := map[string]authority.WorkspaceHead{"a2": {Gen: 9, Epoch: 1, Holder: "node-b/r1", RemoteLSN: 42, Detached: true}} - m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceHeadReader: func(_ context.Context, v string) (authority.WorkspaceHead, error) { return heads[v], nil }}) if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index cc65942a56..2f33c299af 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -11,6 +11,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/auth" "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/lifecycle" "github.com/seaweedfs/seaweed-block/core/ops" control "github.com/seaweedfs/seaweed-block/core/rpc/control" @@ -69,17 +70,132 @@ func (s *services) CreateVolume(ctx context.Context, req *control.CreateVolumeRe if stores.Deletions.Reserved(spec.VolumeID) { return nil, status.Errorf(codes.FailedPrecondition, "create volume: %s is being deleted or was deleted; its id is never reused", spec.VolumeID) } + // A retry may carry a different restore tuple. The target's durable + // binding decides that conflict before looking up the caller's new source + // snapshot, which might itself be absent. + if existing, ok := stores.Volumes.GetVolume(spec.VolumeID); ok && + (existing.Spec.SourceVolume != spec.SourceVolume || existing.Spec.SourceSnapshot != spec.SourceSnapshot || existing.Spec.CreateRequestID != spec.CreateRequestID) { + return nil, status.Errorf(codes.AlreadyExists, "create volume: %s is bound to another restore request", spec.VolumeID) + } + if spec.SourceVolume != "" || spec.SourceSnapshot != "" || spec.CreateRequestID != "" { + if spec.SourceVolume == "" || spec.SourceSnapshot == "" || spec.CreateRequestID == "" || spec.SourceVolume == spec.VolumeID { + return nil, status.Error(codes.InvalidArgument, "restore needs a distinct source volume, snapshot and request id") + } + source, ok := stores.Volumes.GetVolume(spec.SourceVolume) + if !ok || !source.StoreReady { + return nil, status.Errorf(codes.FailedPrecondition, "restore source %q is not store-ready", spec.SourceVolume) + } + if source.Spec.ReplicationFactor != 1 || spec.ReplicationFactor > 1 { + return nil, status.Error(codes.FailedPrecondition, "restore of an RF>1 volume is not supported") + } + if s.host.cfg.LayoutReadVolume == nil || s.host.cfg.LayoutReadHead == nil || s.host.cfg.LayoutCreateTarget == nil { + return nil, status.Error(codes.FailedPrecondition, "master has no restore store") + } + v, err := s.host.cfg.LayoutReadVolume(ctx, source.Spec) + if err != nil { + return nil, status.Errorf(codes.Unavailable, "read restore source VOLUME: %v", err) + } + id, err := layout.ParseVolumeID(source.Spec.LayoutID) + if err != nil || v.ID != id || v.Name != source.Spec.VolumeID || v.CheckIdentity() != nil || v.Geometry.Check() != nil { + return nil, status.Error(codes.FailedPrecondition, "restore source VOLUME identity or geometry is invalid") + } + head, err := s.host.cfg.LayoutReadHead(ctx, source.Spec) + if err != nil { + if errors.Is(err, layout.ErrHeadAbsent) || errors.Is(err, layout.ErrVolumeDeleting) { + return nil, status.Errorf(codes.FailedPrecondition, "restore source HEAD is unavailable: %v", err) + } + return nil, status.Errorf(codes.Unavailable, "read restore source HEAD: %v", err) + } + if head.VolumeID != id || head.State != layout.StateLive && head.State != layout.StateDetached { + return nil, status.Error(codes.FailedPrecondition, "restore source HEAD is absent, foreign or not live/detached") + } + if _, ok := head.Snapshots[spec.SourceSnapshot]; !ok { + return nil, status.Errorf(codes.NotFound, "restore source snapshot %q is absent", spec.SourceSnapshot) + } + spec.SourceLayoutID = source.Spec.LayoutID + if (spec.SizeBytes != 0 && spec.SizeBytes != v.Geometry.SizeBytes) || (spec.BlockSize != 0 && spec.BlockSize != v.Geometry.BlockSize) || (spec.ChunkBytes != 0 && spec.ChunkBytes != v.Geometry.ChunkBytes) { + return nil, status.Error(codes.InvalidArgument, "restore target geometry must match source VOLUME") + } + spec.SizeBytes, spec.BlockSize, spec.ChunkBytes = v.Geometry.SizeBytes, v.Geometry.BlockSize, v.Geometry.ChunkBytes + if spec.ReplicationFactor == 0 { + spec.ReplicationFactor = source.Spec.ReplicationFactor + } + if spec.Protocol == "" { + spec.Protocol = source.Spec.Protocol + } + if spec.FrontendTransport == "" { + spec.FrontendTransport = source.Spec.FrontendTransport + } + } if createVolumeHook != nil { createVolumeHook(spec.VolumeID) } s.host.log.Printf("blockmaster: CreateVolume volume=%q protocol=%q replication_factor=%d pvc=%q namespace=%q", spec.VolumeID, spec.Protocol, spec.ReplicationFactor, spec.PVCName, spec.PVCNamespace) - rec, err := stores.Volumes.CreateVolume(spec) + rec, err := s.host.createLifecycleVolume(ctx, spec) if err != nil { + if errors.Is(err, layout.ErrNoSnapshot) { + return nil, status.Errorf(codes.NotFound, "restore snapshot: %v", err) + } + if errors.Is(err, layout.ErrForeignSource) || errors.Is(err, layout.ErrVolumeDeleting) || errors.Is(err, layout.ErrExists) { + return nil, status.Errorf(codes.FailedPrecondition, "restore target: %v", err) + } + if errors.Is(err, errLayoutStoreNotReady) { + return nil, status.Errorf(codes.Unavailable, "create volume: created, store not ready; retry: %v", err) + } return nil, lifecycleError("create volume", err) } + return lifecycleVolumeResponse(rec) +} + +var errLayoutStoreNotReady = errors.New("layout store not ready") + +// createLifecycleVolume is called under workspaceMu. A failed filer create +// leaves the durable record not-ready; replay uses its same identity and +// completes VOLUME/HEAD before publishing the one-way placement hint. +func (h *Host) createLifecycleVolume(ctx context.Context, spec lifecycle.VolumeSpec) (lifecycle.VolumeRecord, error) { + rec, err := h.lifecycle.Volumes.CreateVolume(spec) + if err != nil { + return lifecycle.VolumeRecord{}, err + } + if h.cfg.LayoutCreateVolume == nil && rec.Spec.SourceVolume == "" { + if h.cfg.WorkspaceRPC { + return lifecycle.VolumeRecord{}, fmt.Errorf("%w: master has no filer writer", errLayoutStoreNotReady) + } + return rec, nil + } + if rec.StoreReady { + // A missing HEAD after the volume was made ready is damage, not a + // half-finished create. Start checks the filer and refuses it; a + // CreateVolume replay must never seed an empty HEAD over its lineage. + return rec, nil + } + var createErr error + if rec.Spec.SourceVolume != "" { + source, ok := h.lifecycle.Volumes.GetVolume(rec.Spec.SourceVolume) + if !ok || source.Spec.LayoutID != rec.Spec.SourceLayoutID || h.cfg.LayoutCreateTarget == nil { + return lifecycle.VolumeRecord{}, fmt.Errorf("%w: restore source or target creator is unavailable", errLayoutStoreNotReady) + } + createErr = h.cfg.LayoutCreateTarget(ctx, source.Spec, rec.Spec, rec.Spec.SourceSnapshot) + } else { + createErr = h.cfg.LayoutCreateVolume(ctx, rec.Spec) + } + if createErr != nil { + return lifecycle.VolumeRecord{}, fmt.Errorf("%w: %w", errLayoutStoreNotReady, createErr) + } + return h.lifecycle.Volumes.MarkStoreReady(rec.Spec.VolumeID, rec.Spec.LayoutID) +} + +func lifecycleVolumeResponse(rec lifecycle.VolumeRecord) (*control.CreateVolumeResponse, error) { + if rec.Spec.LayoutID == "" { + return nil, status.Error(codes.FailedPrecondition, "volume has no layout identity; recreate the legacy volume") + } return &control.CreateVolumeResponse{ VolumeId: rec.Spec.VolumeID, + LayoutId: rec.Spec.LayoutID, SizeBytes: rec.Spec.SizeBytes, + BlockSize: rec.Spec.BlockSize, + ChunkBytes: rec.Spec.ChunkBytes, + StoreReady: rec.StoreReady, ReplicationFactor: int32(rec.Spec.ReplicationFactor), Protocol: rec.Spec.Protocol, FrontendTransport: rec.Spec.FrontendTransport, @@ -90,6 +206,26 @@ func (s *services) CreateVolume(ctx context.Context, req *control.CreateVolumeRe }, nil } +// GetVolume resolves a name using durable lifecycle intent only. It never +// creates a record or infers an identity from the filer or an assignment. +func (s *services) GetVolume(ctx context.Context, req *control.GetLifecycleVolumeRequest) (*control.CreateVolumeResponse, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + if req.GetVolumeId() == "" { + return nil, status.Error(codes.InvalidArgument, "volume_id is required") + } + stores := s.host.Lifecycle() + if stores == nil { + return nil, status.Error(codes.FailedPrecondition, "lifecycle store is not configured") + } + rec, ok := stores.Volumes.GetVolume(req.GetVolumeId()) + if !ok { + return nil, status.Error(codes.NotFound, "volume not found") + } + return lifecycleVolumeResponse(rec) +} + func (s *services) DeleteVolume(ctx context.Context, req *control.DeleteVolumeRequest) (*control.DeleteVolumeResponse, error) { s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() @@ -206,7 +342,7 @@ func (h *Host) ImportLifecycleVolume(spec lifecycle.VolumeSpec) (imported bool, if stores.Deletions.Reserved(spec.VolumeID) { return false, nil } - if _, err := stores.Volumes.CreateVolume(spec); err != nil { + if _, err := h.createLifecycleVolume(context.Background(), spec); err != nil { return false, err } return true, nil @@ -349,6 +485,8 @@ func lifecycleSpecFromWire(req *control.CreateVolumeRequest) lifecycle.VolumeSpe return lifecycle.VolumeSpec{ VolumeID: req.GetVolumeId(), SizeBytes: req.GetSizeBytes(), + BlockSize: req.GetBlockSize(), + ChunkBytes: req.GetChunkBytes(), ReplicationFactor: int(req.GetReplicationFactor()), Protocol: req.GetProtocol(), FrontendTransport: req.GetFrontendTransport(), @@ -356,6 +494,9 @@ func lifecycleSpecFromWire(req *control.CreateVolumeRequest) lifecycle.VolumeSpe PVCNamespace: req.GetPvcNamespace(), PVCUID: req.GetPvcUid(), PVName: req.GetPvName(), + SourceVolume: req.GetSourceVolume(), + SourceSnapshot: req.GetSourceSnapshot(), + CreateRequestID: req.GetCreateRequestId(), } } @@ -477,7 +618,9 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co lastEpoch uint64 lastEV uint64 sentAny bool - lastInfo adapter.AssignmentInfo + // current rebuilds the fact of the last line sent (no local copy of + // the assignment: only the publisher mints one). + current func() *control.AssignmentFact ) // A change of the volume's store record re-sends the current fact: its // descriptors carry the recorded stores (the same generation; the @@ -492,8 +635,8 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co return nil case <-storesChanged: storesChanged = s.host.attest.watch(req.VolumeId) - if sentAny { - if err := stream.Send(s.assignmentFact(lastInfo)); err != nil { + if current != nil { + if err := stream.Send(current()); err != nil { return err } } @@ -530,7 +673,7 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co lastEpoch = info.Epoch lastEV = info.EndpointVersion - lastInfo = info + current = func() *control.AssignmentFact { return s.assignmentFact(info) } sentAny = true fact := s.assignmentFact(info) if err := stream.Send(fact); err != nil { diff --git a/seaweed-block/core/host/master/volume_delete_authority.go b/seaweed-block/core/host/master/volume_delete_authority.go new file mode 100644 index 0000000000..6c8240f13b --- /dev/null +++ b/seaweed-block/core/host/master/volume_delete_authority.go @@ -0,0 +1,75 @@ +package master + +import ( + "context" + "errors" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// VolumeDeleteAuthority binds the layout delete's two authority operations +// to its lifecycle volume and existing deletion token. +func (h *Host) VolumeDeleteAuthority(volume, token string) *volumeDeleteAuthority { + return &volumeDeleteAuthority{host: h, volume: volume, token: token} +} + +type volumeDeleteAuthority struct { + host *Host + volume, token string +} + +func (a *volumeDeleteAuthority) Reserve(ctx context.Context) error { + h := a.host + h.workspaceMu.Lock() + defer h.workspaceMu.Unlock() + if h.lifecycle == nil { + return errors.New("workspace delete: lifecycle store unavailable") + } + return h.Publisher().ReserveWorkspaceDeletion(ctx, a.volume, func() error { + if _, err := h.lifecycle.Deletions.Admit(a.volume, a.token); err != nil { + return err + } + _, err := h.lifecycle.Deletions.Commit(a.volume, a.token) + return err + }) +} + +func (a *volumeDeleteAuthority) NoLiveLease(ctx context.Context) error { + if a.host.lifecycle == nil || !a.host.lifecycle.Deletions.CommittedSnapshot(a.volume) { + return errors.New("workspace delete: committed reservation required") + } + return a.host.Publisher().NoLiveWorkspaceLease(ctx, a.volume) +} + +// ReserveVolumeDeletion exposes the same committed reservation used by startup +// and every positive lease writer. It does not reuse abortable admission. +func (s *services) ReserveVolumeDeletion(ctx context.Context, req *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) { + if req.GetVolumeId() == "" || req.GetToken() == "" { + return nil, status.Error(codes.InvalidArgument, "volume_id and token are required") + } + if err := s.host.VolumeDeleteAuthority(req.GetVolumeId(), req.GetToken()).Reserve(ctx); err != nil { + if errors.Is(err, authority.ErrWorkspaceDeleteRefused) { + return nil, status.Errorf(codes.FailedPrecondition, "reserve volume deletion: %v", err) + } + return nil, status.Errorf(codes.Unavailable, "reserve volume deletion: %v", err) + } + _, known := s.host.lifecycle.Volumes.GetVolume(req.GetVolumeId()) + return &control.MarkVolumeDeletingResponse{Known: known, State: lifecycle.ReservationCommitted}, nil +} + +// CheckVolumeNoLiveLease reads the master's authoritative barrier at the +// delete's CAS boundary, including granted-but-unclaimed lines. +func (s *services) CheckVolumeNoLiveLease(ctx context.Context, req *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) { + if req.GetVolumeId() == "" || req.GetToken() == "" { + return nil, status.Error(codes.InvalidArgument, "volume_id and token are required") + } + if err := s.host.VolumeDeleteAuthority(req.GetVolumeId(), req.GetToken()).NoLiveLease(ctx); err != nil { + return nil, workspaceError(err) + } + _, known := s.host.lifecycle.Volumes.GetVolume(req.GetVolumeId()) + return &control.MarkVolumeDeletingResponse{Known: known, State: lifecycle.ReservationCommitted}, nil +} diff --git a/seaweed-block/core/host/master/volume_delete_authority_test.go b/seaweed-block/core/host/master/volume_delete_authority_test.go new file mode 100644 index 0000000000..1e6c55cfb3 --- /dev/null +++ b/seaweed-block/core/host/master/volume_delete_authority_test.go @@ -0,0 +1,141 @@ +package master + +import ( + "context" + "errors" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestVolumeDeleteAuthorityReservationSurvivesRestart(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + authDir, lifecycleDir := filepath.Join(root, "authority"), filepath.Join(root, "lifecycle") + h, client, stop := hostOn(t, authDir, lifecycleDir) + if _, err := client.CreateVolume(ctx, createReq("v")); err != nil { + stop() + t.Fatal(err) + } + a := h.VolumeDeleteAuthority("v", "delete-v") + if err := a.NoLiveLease(ctx); err == nil { + stop() + t.Fatal("unreserved proof succeeded") + } + if _, err := client.ReserveVolumeDeletion(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "delete-v"}); err != nil { + stop() + t.Fatal(err) + } + if _, err := client.ReserveVolumeDeletion(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "delete-v"}); err != nil { + stop() + t.Fatal("replay", err) + } + if _, err := h.lifecycle.Deletions.Abort("v", "delete-v"); !errors.Is(err, lifecycle.ErrReservationCommitted) { + stop() + t.Fatalf("abort reopened reservation: %v", err) + } + if _, err := client.CheckVolumeNoLiveLease(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "delete-v"}); err != nil { + stop() + t.Fatal(err) + } + if _, err := client.AbortVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "delete-v"}); status.Code(err) != codes.FailedPrecondition { + stop() + t.Fatalf("RPC abort reopened committed reservation: %v", err) + } + stop() + _, lc, closeLoaded := hostOn(t, authDir, lifecycleDir) + defer closeLoaded() + if _, err := lc.CheckVolumeNoLiveLease(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "delete-v"}); err != nil { + t.Fatal("reloaded exclusion missing", err) + } + if _, err := lc.CreateVolume(ctx, createReq("v")); err == nil { + t.Fatal("recreated a reserved volume") + } +} + +// The two RPCs the volume delete calls are the in-master authority: the +// check refuses before the reservation, the reservation commits (a replay +// is fine, it is never given back), the check then passes. +func TestVolumeDeleteAuthorityRPCs(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + _, client, stop := hostOn(t, filepath.Join(root, "authority"), filepath.Join(root, "lifecycle")) + defer stop() + if _, err := client.CreateVolume(ctx, createReq("v")); err != nil { + t.Fatal(err) + } + req := &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "delete-v"} + if _, err := client.CheckVolumeNoLiveLease(ctx, req); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("check before the reservation: %v; want FailedPrecondition", err) + } + for i := 0; i < 2; i++ { + if _, err := client.ReserveVolumeDeletion(ctx, req); err != nil { + t.Fatalf("reserve #%d: %v", i+1, err) + } + } + if _, err := client.AbortVolumeDeleting(ctx, req); err == nil { + t.Fatal("a committed reservation was given back") + } + if _, err := client.CheckVolumeNoLiveLease(ctx, req); err != nil { + t.Fatalf("check after the reservation: %v", err) + } + if _, err := client.ReserveVolumeDeletion(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v"}); status.Code(err) != codes.InvalidArgument { + t.Fatalf("reserve without a token: %v", err) + } + for _, tc := range []struct { + volume string + known bool + }{{"v", true}, {"unknown", false}} { + q := &control.MarkVolumeDeletingRequest{VolumeId: tc.volume, Token: "delete-v"} + reserved, err := client.ReserveVolumeDeletion(ctx, q) + if err != nil || reserved.GetKnown() != tc.known { + t.Fatalf("reserve known(%s): %+v %v", tc.volume, reserved, err) + } + checked, err := client.CheckVolumeNoLiveLease(ctx, q) + if err != nil || checked.GetKnown() != tc.known { + t.Fatalf("check known(%s): %+v %v", tc.volume, checked, err) + } + } +} + +// A failed reservation is never evidence that a durable write did not happen. +// These handler calls avoid a transport's own cancellation masking its status. +func TestVolumeDeleteAuthorityRPCFailureIsUnknown(t *testing.T) { + svc := &services{host: &Host{}} + canceled, cancel := context.WithCancel(context.Background()) + cancel() + expired, stop := context.WithDeadline(context.Background(), time.Unix(0, 0)) + defer stop() + req := &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "delete-v"} + for _, ctx := range []context.Context{context.Background(), canceled, expired} { + if _, err := svc.ReserveVolumeDeletion(ctx, req); status.Code(err) != codes.Unavailable { + t.Fatalf("reservation failure: %v; want unknown/Unavailable", err) + } + } + if _, err := svc.CheckVolumeNoLiveLease(context.Background(), &control.MarkVolumeDeletingRequest{VolumeId: "v"}); status.Code(err) != codes.InvalidArgument { + t.Fatalf("lease proof without token: %v", err) + } +} + +func TestReserveVolumeDeletionLiveLeaseIsDefiniteAndKeepsRenewing(t *testing.T) { + h, conn, ctx := reviewBindingHost(t) + reviewLegacyBind(t, h, conn, ctx, "live-delete") + if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1); err != nil { + t.Fatal(err) + } + lc := control.NewLifecycleServiceClient(conn) + if _, err := lc.ReserveVolumeDeletion(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "live-delete", Token: "typo"}); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("live reservation status: %v; want definite FailedPrecondition", err) + } + if h.lifecycle.Deletions.Reserved("live-delete") { + t.Fatal("refusal persisted a reservation") + } + if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1); err != nil { + t.Fatalf("refused delete interrupted renewal: %v", err) + } +} diff --git a/seaweed-block/core/host/master/volume_identity_test.go b/seaweed-block/core/host/master/volume_identity_test.go new file mode 100644 index 0000000000..50202c12fa --- /dev/null +++ b/seaweed-block/core/host/master/volume_identity_test.go @@ -0,0 +1,73 @@ +package master + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type identityRPC struct{ svc *services } + +func (c identityRPC) GetVolume(ctx context.Context, q *control.GetLifecycleVolumeRequest, _ ...grpc.CallOption) (*control.CreateVolumeResponse, error) { + return c.svc.GetVolume(ctx, q) +} + +func TestGetLifecycleVolumeResolvesOnlyTheDurableIdentity(t *testing.T) { + dir := t.TempDir() + const id = "1234567890abcdef1234567890abcdef" + for _, name := range []string{"v", "legacy"} { + spec := lifecycle.VolumeSpec{VolumeID: name, SizeBytes: 1 << 20, ReplicationFactor: 1} + if name == "v" { + spec.LayoutID = id + } + raw, _ := json.Marshal(lifecycle.VolumeRecord{Spec: spec}) + if err := os.WriteFile(filepath.Join(dir, name+".json"), raw, 0600); err != nil { + t.Fatal(err) + } + } + store, err := lifecycle.OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + svc := newServices(&Host{lifecycle: &LifecycleStores{Volumes: store}}) + resolved, err := lifecycleclient.ResolveVolume(context.Background(), identityRPC{svc}, "v") + if err != nil || resolved.String() != id { + t.Fatalf("resolve: %v %s", err, resolved) + } + if _, err := lifecycleclient.ResolveVolume(context.Background(), identityRPC{svc}, "legacy"); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("legacy identity was invented: %v", err) + } + if _, err := lifecycleclient.ResolveVolume(context.Background(), identityRPC{svc}, "missing"); status.Code(err) != codes.NotFound { + t.Fatalf("missing volume: %v", err) + } + if len(store.ListVolumes()) != 2 { + t.Fatal("lookup mutated lifecycle intent") + } + ref, err := svc.host.WorkspaceLayoutVolume(context.Background(), "v") + if err != nil || ref.Name != "v" || ref.ID.String() != id { + t.Fatalf("HEAD identity resolver: %+v %v", ref, err) + } + for _, name := range []string{"legacy", "missing"} { + if _, err := svc.host.WorkspaceLayoutVolume(context.Background(), name); err == nil { + t.Fatalf("HEAD identity invented for %s", name) + } + } + var unready *Host + if _, err := unready.WorkspaceLayoutVolume(context.Background(), "v"); err == nil { + t.Fatal("resolver accepted before Host construction") + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := svc.host.WorkspaceLayoutVolume(ctx, "v"); err != context.Canceled { + t.Fatalf("cancelled lookup: %v", err) + } +} diff --git a/seaweed-block/core/host/master/workspace_ack_stop_identity_test.go b/seaweed-block/core/host/master/workspace_ack_stop_identity_test.go new file mode 100644 index 0000000000..e2cb12bf2d --- /dev/null +++ b/seaweed-block/core/host/master/workspace_ack_stop_identity_test.go @@ -0,0 +1,55 @@ +package master + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/authority" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +func TestWorkspaceAckRecordsTheAuthoritativeStopIdentity(t *testing.T) { + head := authority.WorkspaceHead{Gen: 99, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true} + var readErr error + h, conn, ctx := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) { return head, readErr }, nil) + reviewLegacyBind(t, h, conn, ctx, "v") + ws := control.NewWorkspaceServiceClient(conn) + id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "v", ReplicaId: "r1", Epoch: 1} + if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil { + t.Fatal(err) + } + if _, err := ws.RevokeWorkspace(ctx, id); err != nil { + t.Fatal(err) + } + good := head + for _, tc := range []struct { + name string + mutate func() + }{ + {"unreadable", func() { readErr = errors.New("filer unavailable") }}, + {"live", func() { head.Detached = false }}, + {"other epoch", func() { head.Epoch++ }}, + {"other holder", func() { head.Holder = "node-b/r1" }}, + {"deleting", func() { head.Deleting = true }}, + } { + t.Run(tc.name, func(t *testing.T) { + head, readErr = good, nil + tc.mutate() + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 7}); err == nil { + t.Fatal("unproven stopped image accepted") + } + if h.Publisher().WorkspaceState("v").Ack != nil { + t.Fatal("refusal persisted an ACK") + } + }) + } + head, readErr = good, nil + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 7}); err != nil { + t.Fatal("metadata generation changed before ACK", err) + } + ack := h.Publisher().WorkspaceState("v").Ack + if ack == nil || ack.Epoch != 1 || ack.Holder != good.Holder || ack.RemoteLSN != 42 || ack.HeadGen != 7 { + t.Fatalf("wrong persisted stop identity/readout: %+v", ack) + } +} diff --git a/seaweed-block/core/host/master/workspace_binding.go b/seaweed-block/core/host/master/workspace_binding.go index f1360f1f0a..b7910f91b5 100644 --- a/seaweed-block/core/host/master/workspace_binding.go +++ b/seaweed-block/core/host/master/workspace_binding.go @@ -132,7 +132,9 @@ func (h *Host) reconcileWorkspaceBindings() error { continue } for _, m := range state.Moves { - if m.Issued { + // A move must not retire its own target reservation. A same-host + // successor reuses it; a later ACK still retires that epoch below. + if m.Issued && m.OldHost != m.NewHost { if err := h.lifecycle.WorkspaceBindings.Retire(volume, m.OldHost, m.OldEpoch); err != nil { return err } @@ -216,6 +218,9 @@ func (h *Host) admitWorkspacePublication(ask authority.AssignmentAsk, publish fu if _, alive := h.lifecycle.Volumes.GetVolume(ask.VolumeID); !alive { return fmt.Errorf("workspace publication: no lifecycle VolumeRecord for %s; register it (CreateVolume) before publishing", ask.VolumeID) } + if !h.layoutStoreReady(ask.VolumeID) { + return fmt.Errorf("workspace publication: volume %s created, store not ready; retry CreateVolume", ask.VolumeID) + } bindings, bound, err := h.lifecycle.WorkspaceBindings.Get(ask.VolumeID) if err != nil { return err diff --git a/seaweed-block/core/host/master/workspace_binding_review_test.go b/seaweed-block/core/host/master/workspace_binding_review_test.go index 269caba18a..1bcb1e5c53 100644 --- a/seaweed-block/core/host/master/workspace_binding_review_test.go +++ b/seaweed-block/core/host/master/workspace_binding_review_test.go @@ -29,7 +29,7 @@ func reviewBindingHostWithReader(t *testing.T, reader func(context.Context, stri func reviewBindingHostBeforeStart(t *testing.T, reader func(context.Context, string) (authority.WorkspaceHead, error), before func(*Host)) (*Host, *grpc.ClientConn, context.Context) { t.Helper() - h, e := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) + h, e := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceHeadReader: reader}) if e != nil { t.Fatal(e) } @@ -245,6 +245,9 @@ func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) { t.Run(mode, func(t *testing.T) { arrived, release := make(chan struct{}), make(chan struct{}) h, c, ctx := reviewBindingHostWithReader(t, func(ctx context.Context, vol string) (authority.WorkspaceHead, error) { + if vol == "ack" { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", Detached: true}, nil + } close(arrived) select { case <-release: @@ -302,7 +305,7 @@ func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) { return e }) } else { - if _, e := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-rf3", SizeBytes: 1 << 20, ReplicationFactor: 3}); e != nil { + if _, e := testCreateReadyVolume(h.Lifecycle().Volumes, lifecycle.VolumeSpec{VolumeID: "vol-rf3", SizeBytes: 1 << 20, ReplicationFactor: 3}); e != nil { t.Fatal(e) } seedRF3Placement(t, h) diff --git a/seaweed-block/core/host/master/workspace_binding_test.go b/seaweed-block/core/host/master/workspace_binding_test.go index 0b6eeef493..8b67709c13 100644 --- a/seaweed-block/core/host/master/workspace_binding_test.go +++ b/seaweed-block/core/host/master/workspace_binding_test.go @@ -15,7 +15,7 @@ import ( ) func TestWorkspaceBindingPlacesRF1OnChosenNode(t *testing.T) { - h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) if err != nil { t.Fatal(err) } @@ -73,7 +73,7 @@ func TestWorkspaceBindingsForcedRetiresOnlyAfterIssue(t *testing.T) { } func workspaceBindingsMove(t *testing.T, forced bool) { - cfg := Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + cfg := Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil }} h, err := New(cfg) @@ -218,7 +218,7 @@ func workspaceBindingsMove(t *testing.T, forced bool) { } func TestWorkspaceBindingsRejectCollisionsAndLiveChangesAndDeleteCleans(t *testing.T) { - h, e := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + h, e := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) if e != nil { t.Fatal(e) } diff --git a/seaweed-block/core/host/master/workspace_exited_holder_test.go b/seaweed-block/core/host/master/workspace_exited_holder_test.go index 3a1df34d97..3ee7bc03c8 100644 --- a/seaweed-block/core/host/master/workspace_exited_holder_test.go +++ b/seaweed-block/core/host/master/workspace_exited_holder_test.go @@ -9,7 +9,9 @@ import ( "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/storage" @@ -29,16 +31,19 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) { // this budget; the rest must cover the work after it under load and -race. ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second) defer cancel() - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "vol-a", 64, 4) reader := func(ctx context.Context, _ string) (authority.WorkspaceHead, error) { - h, err := remote.GetHead(ctx) + h, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) if err != nil { return authority.WorkspaceHead{}, err } - return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached}, nil + if !found { + return authority.WorkspaceHead{}, layout.ErrHeadAbsent + } + return layoutWorkspaceHead(h), nil } const skew = 100 * time.Millisecond - m, err := New(Config{WorkspaceMaxClockSkew: skew, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) + m, err := New(Config{WorkspaceMaxClockSkew: skew, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceHeadReader: reader}) if err != nil { t.Fatal(err) } @@ -85,11 +90,12 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) { open := func(host string, line authority.AuthorityBasis) (*durable.DurableProvider, frontend.Backend) { t.Helper() - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, - ChunkHolder: host + "/" + line.ReplicaID, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, restoreProjection{frontend.Projection{VolumeID: "vol-a", ReplicaID: line.ReplicaID, Epoch: line.Epoch, EndpointVersion: line.EndpointVersion, Healthy: true}}) + ChunkHolder: host + "/" + line.ReplicaID, + } + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, restoreProjection{frontend.Projection{VolumeID: "vol-a", ReplicaID: line.ReplicaID, Epoch: line.Epoch, EndpointVersion: line.EndpointVersion, Healthy: true}}) if err != nil { t.Fatal(err) } @@ -123,9 +129,9 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) { if err := oldProvider.Close(); err != nil { t.Fatal(err) } - head, err := remote.GetHead(ctx) - if err != nil || head.RemoteLSN != cut || head.State == storage.ChunkHeadDetached { - t.Fatalf("HEAD after the holder exited: %+v %v", head, err) + head, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found || head.Position != cut || head.State == layout.StateDetached { + t.Fatalf("HEAD after the holder exited: %+v found=%v err=%v", head, found, err) } // The exited holder's live authority blocks the delete and a clean move. @@ -169,9 +175,9 @@ func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) { // The new host claims HEAD, serves the last cut and continues past it. newProvider, newBackend := open("node-b", newLine) - claimed, err := remote.GetHead(ctx) - if err != nil || claimed.Epoch != newLine.Epoch || claimed.Holder != "node-b/r1" || claimed.RemoteLSN != cut || claimed.State == storage.ChunkHeadDetached { - t.Fatalf("HEAD after the new host's recovery: %+v %v", claimed, err) + claimed, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found || claimed.Epoch != newLine.Epoch || claimed.Holder != "node-b/r1" || claimed.Position != cut || claimed.State == layout.StateDetached { + t.Fatalf("HEAD after the new host's recovery: %+v found=%v err=%v", claimed, found, err) } got := make([]byte, len(want)) if n, err := newBackend.Read(ctx, 8*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) { diff --git a/seaweed-block/core/host/master/workspace_head.go b/seaweed-block/core/host/master/workspace_head.go deleted file mode 100644 index 72f8771ccf..0000000000 --- a/seaweed-block/core/host/master/workspace_head.go +++ /dev/null @@ -1,111 +0,0 @@ -package master - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - "time" - - "github.com/seaweedfs/seaweed-block/core/authority" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" -) - -// headFilerMtimeNS is the HEAD entry's mtime from the filer's Last-Modified -// header of the same response as the content (1 s resolution), or 0 -// (unknown) when the header is absent, unparseable or not after the epoch. -func headFilerMtimeNS(h http.Header) int64 { - v := h.Get("Last-Modified") - if v == "" { - return 0 - } - t, err := http.ParseTime(v) - if err != nil || t.UnixNano() <= 0 { - return 0 - } - return t.UnixNano() -} - -// NewWorkspaceHEADReader reads inline HEAD content from the configured filer -// HTTP directory. It never follows redirects or accepts operator-supplied HEAD -// evidence. W2's detached state is part of the committed HEAD document. The -// HEAD's filer mtime comes from the same response (headFilerMtimeNS). -func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authority.WorkspaceHead, error), error) { - u, err := url.Parse(base) - if err != nil || u == nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" { - return nil, fmt.Errorf("workspace HEAD base must be an absolute HTTP directory URL") - } - client := &http.Client{Timeout: 5 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} - return func(ctx context.Context, volume string) (authority.WorkspaceHead, error) { - if volume == "" || volume == "." || volume == ".." || strings.ContainsAny(volume, "/\\\x00") { - return authority.WorkspaceHead{}, fmt.Errorf("invalid volume path") - } - endpoint := strings.TrimRight(base, "/") + "/" + url.PathEscape(volume) + "/HEAD" - req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) - if err != nil { - return authority.WorkspaceHead{}, err - } - res, err := client.Do(req) - if err != nil { - return authority.WorkspaceHead{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return authority.WorkspaceHead{}, fmt.Errorf("HEAD read HTTP %d", res.StatusCode) - } - raw, err := io.ReadAll(io.LimitReader(res.Body, (16<<20)+1)) - if err != nil { - return authority.WorkspaceHead{}, err - } - if len(raw) > 16<<20 { - return authority.WorkspaceHead{}, fmt.Errorf("HEAD too large") - } - var doc struct { - Gen uint64 `json:"gen"` - Epoch uint64 `json:"epoch"` - Holder string `json:"holder"` - RemoteLSN uint64 `json:"remote_lsn"` - State string `json:"state"` - DetachedBy *struct { - Holder string `json:"holder"` - Epoch uint64 `json:"epoch"` - Gen uint64 `json:"gen"` - } `json:"detachedBy"` - LegacyDetached json.RawMessage `json:"detached"` - } - if err := json.Unmarshal(raw, &doc); err != nil { - return authority.WorkspaceHead{}, err - } - if _, err := chunkstore.DecodeHeadDocument("workspace/"+volume, raw); err != nil { - return authority.WorkspaceHead{}, err - } - // DecodeHeadDocument above owns the supported-format checks. - // The initial HEAD of a volume no holder ever claimed: epoch 0, no - // holder, active. It names no identity, so callers that need one get - // an error as before; the delete reads it as "never started". - // A HEAD the delete has marked (deleting, purging, deleted): no claim - // can move it again; the delete's re-run reads it as past the fence. - if doc.Gen > 0 && doc.LegacyDetached == nil && (doc.State == "deleting" || doc.State == "purging" || doc.State == "deleted") { - return authority.WorkspaceHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, Deleting: true, FilerMtimeNS: headFilerMtimeNS(res.Header)}, authority.ErrWorkspaceHeadDeleting - } - if doc.Gen > 0 && doc.Epoch == 0 && doc.Holder == "" && doc.LegacyDetached == nil && doc.DetachedBy == nil && (doc.State == "" || doc.State == "active") { - return authority.WorkspaceHead{Gen: doc.Gen, FilerMtimeNS: headFilerMtimeNS(res.Header)}, authority.ErrWorkspaceHeadUnclaimed - } - if doc.Gen == 0 || doc.Epoch == 0 || doc.Holder == "" || doc.LegacyDetached != nil || (doc.State != "" && doc.State != "active" && doc.State != "detached") { - return authority.WorkspaceHead{}, fmt.Errorf("invalid HEAD identity/state") - } - // Missing state is the legacy active representation. Only a final-cut - // CAS whose proof names the installed identity can authorize CLEAN. - if doc.State == "detached" { - if doc.DetachedBy == nil || doc.DetachedBy.Holder != doc.Holder || doc.DetachedBy.Epoch != doc.Epoch || doc.DetachedBy.Gen != doc.Gen { - return authority.WorkspaceHead{}, fmt.Errorf("invalid HEAD detachedBy proof") - } - } else if doc.DetachedBy != nil { - return authority.WorkspaceHead{}, fmt.Errorf("active HEAD retains detachedBy proof") - } - return authority.WorkspaceHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN, Detached: doc.State == "detached", FilerMtimeNS: headFilerMtimeNS(res.Header)}, nil - }, nil -} diff --git a/seaweed-block/core/host/master/workspace_head_format3_test.go b/seaweed-block/core/host/master/workspace_head_format3_test.go deleted file mode 100644 index 7a07fbf073..0000000000 --- a/seaweed-block/core/host/master/workspace_head_format3_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package master - -import ( - "context" - "crypto/sha256" - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -type workspaceManifestBlobs struct{ chunkstore.Blobs } - -func (workspaceManifestBlobs) Put(context.Context, []byte) (string, error) { - return "1,0000000100000001", nil -} - -// Exercise the F4 writer and HTTP reader together, not a hand-written schema. -func TestWorkspaceHEADReadsProductionFormat3Detach(t *testing.T) { - ctx := context.Background() - filer := chunkstore.NewMemFiler() - remote, err := chunkstore.NewChunkRemote(filer, workspaceManifestBlobs{}, "/vol-a") - if err != nil { - t.Fatal(err) - } - head := storage.ChunkHead{Epoch: 3, Holder: "node-a/r1", RemoteLSN: 42, - State: storage.ChunkHeadDetached, - DetachedBy: &storage.ChunkDetachedBy{Holder: "node-a/r1", Epoch: 3, Gen: 1}, - Chunks: map[uint64]storage.ChunkRef{0: {Key: "data-1", SHA256: sha256.Sum256([]byte("cut-image")), Encoding: "full", BirthLSN: 42}}} - head, _, err = remote.PrepareManifest(ctx, storage.ChunkHead{}, head, 4096) - if err != nil { - t.Fatal(err) - } - if _, err = remote.CASHead(ctx, storage.ChunkHeadVersion{}, head); err != nil { - t.Fatal(err) - } - stored, err := filer.LookupEntry(ctx, "/vol-a", "HEAD") - if err != nil { - t.Fatal(err) - } - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write(stored.Content) - })) - defer s.Close() - read, err := NewWorkspaceHEADReader(s.URL) - if err != nil { - t.Fatal(err) - } - got, err := read(ctx, "vol-a") - if err != nil || !got.Detached || got.Gen != 1 || got.Epoch != 3 || got.Holder != "node-a/r1" || got.RemoteLSN != 42 { - t.Fatalf("production detached HEAD not usable as move evidence: %+v, %v; body=%s", got, err, stored.Content) - } -} - -func TestWorkspaceHEADFormat3DetachedProof(t *testing.T) { - for _, tc := range []struct { - name, state string - format, levels int - valid, detached bool - }{ - {"detached", `,"state":"detached","detachedBy":{"holder":"node-a/r1","epoch":3,"gen":9}`, 3, 1, true, true}, - {"active", `,"state":"active"`, 3, 1, true, false}, - {"missing-proof", `,"state":"detached"`, 3, 1, false, false}, - {"wrong-proof", `,"state":"detached","detachedBy":{"holder":"node-b/r1","epoch":3,"gen":9}`, 3, 1, false, false}, - {"stale-active-proof", `,"state":"active","detachedBy":{"holder":"node-a/r1","epoch":3,"gen":9}`, 3, 1, false, false}, - {"unknown-format", `,"state":"active"`, 4, 1, false, false}, - {"unknown-levels", `,"state":"active"`, 3, 2, false, false}, - } { - t.Run(tc.name, func(t *testing.T) { - // A data-bearing F4 root: the control-plane reader validates the - // root and detach proof without fetching immutable segment payloads. - body := fmt.Sprintf(`{"format":%d,"levels":%d,"gen":9,"epoch":3,"holder":"node-a/r1","remote_lsn":42,"chunk_bytes":4096,"chunk_count":1,"segments":{"0":{"key":"segment-1","sha256":[],"owner":"vol-a","count":1,"seg_format":2,"max_birth_lsn":42}}%s}`, tc.format, tc.levels, tc.state) - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/vol-a/HEAD" { - t.Errorf("unexpected path %s", r.URL.Path) - http.NotFound(w, r) - return - } - _, _ = w.Write([]byte(body)) - })) - defer s.Close() - read, err := NewWorkspaceHEADReader(s.URL) - if err != nil { - t.Fatal(err) - } - h, err := read(context.Background(), "vol-a") - if (err == nil) != tc.valid { - t.Fatalf("valid=%v, HEAD=%+v, error=%v", tc.valid, h, err) - } - if err == nil && (h.Gen != 9 || h.Epoch != 3 || h.Holder != "node-a/r1" || h.RemoteLSN != 42 || h.Detached != tc.detached) { - t.Fatalf("incorrect HEAD evidence: %+v", h) - } - }) - } -} diff --git a/seaweed-block/core/host/master/workspace_head_test.go b/seaweed-block/core/host/master/workspace_head_test.go deleted file mode 100644 index 0e250e1644..0000000000 --- a/seaweed-block/core/host/master/workspace_head_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package master - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "testing" - - "github.com/seaweedfs/seaweed-block/core/authority" -) - -// These are decoder controls, not the W2 Detach/filer integration proof. -func TestWorkspaceHEADCanonicalState(t *testing.T) { - for _, tc := range []struct { - name, suffix string - valid, detached bool - }{ - {"legacy-active", ``, true, false}, - {"active", `,"state":"active"`, true, false}, - {"detached", `,"state":"detached","detachedBy":{"holder":"old","epoch":3,"gen":9}`, true, true}, - {"obsolete-attached", `,"state":"attached"`, false, false}, - {"missing-proof", `,"state":"detached"`, false, false}, - {"wrong-holder", `,"state":"detached","detachedBy":{"holder":"other","epoch":3,"gen":9}`, false, false}, - {"wrong-epoch", `,"state":"detached","detachedBy":{"holder":"old","epoch":2,"gen":9}`, false, false}, - {"wrong-gen", `,"state":"detached","detachedBy":{"holder":"old","epoch":3,"gen":8}`, false, false}, - {"active-stale-proof", `,"state":"active","detachedBy":{"holder":"old","epoch":3,"gen":9}`, false, false}, - {"legacy-boolean", `,"detached":true`, false, false}, - } { - t.Run(tc.name, func(t *testing.T) { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write([]byte(`{"format":1,"gen":9,"epoch":3,"holder":"old","remote_lsn":42` + tc.suffix + `}`)) - })) - defer s.Close() - read, err := NewWorkspaceHEADReader(s.URL) - if err != nil { - t.Fatal(err) - } - h, err := read(context.Background(), "v") - if (err == nil) != tc.valid { - t.Fatalf("valid=%v, HEAD=%+v, error=%v", tc.valid, h, err) - } - if err == nil && h.Detached != tc.detached { - t.Fatalf("detached=%v, HEAD=%+v", tc.detached, h) - } - }) - } -} - -// The initial HEAD of a volume no holder ever claimed (epoch 0, no holder, -// active) reads as ErrWorkspaceHeadUnclaimed with its generation and epoch 0: -// still an error to every caller that needs an identity, and the delete's -// evidence of "never started". A claimed or detached HEAD is unchanged, and -// an epoch-0 HEAD with a holder or a detach proof stays invalid. -func TestWorkspaceHEADUnclaimed(t *testing.T) { - for _, tc := range []struct { - name, doc string - unclaimed bool - }{ - {"initial", `{"format":1,"gen":1,"epoch":0,"holder":"","remote_lsn":0}`, true}, - {"initial active", `{"format":1,"gen":1,"epoch":0,"holder":"","remote_lsn":0,"state":"active"}`, true}, - {"epoch 0 with a holder", `{"format":1,"gen":1,"epoch":0,"holder":"x/r1","remote_lsn":0}`, false}, - {"epoch 0 detached", `{"format":1,"gen":1,"epoch":0,"holder":"","remote_lsn":0,"state":"detached","detachedBy":{"holder":"","epoch":0,"gen":1}}`, false}, - } { - t.Run(tc.name, func(t *testing.T) { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(tc.doc)) })) - defer s.Close() - read, err := NewWorkspaceHEADReader(s.URL) - if err != nil { - t.Fatal(err) - } - h, err := read(context.Background(), "v") - if got := errors.Is(err, authority.ErrWorkspaceHeadUnclaimed); got != tc.unclaimed { - t.Fatalf("unclaimed=%v (err %v); want %v", got, err, tc.unclaimed) - } - if tc.unclaimed && (h.Gen != 1 || h.Epoch != 0) { - t.Fatalf("unclaimed HEAD %+v; want its generation and epoch 0", h) - } - if !tc.unclaimed && err == nil { - t.Fatalf("HEAD %+v accepted; want an error", h) - } - }) - } -} - -// A HEAD the delete has marked (deleting, purging, deleted) reads as -// ErrWorkspaceHeadDeleting with Deleting set: the delete's re-run sees it as -// past the fence; every other caller still gets an error. -func TestWorkspaceHEADDeleting(t *testing.T) { - for _, state := range []string{"deleting", "purging", "deleted"} { - t.Run(state, func(t *testing.T) { - doc := `{"format":1,"gen":5,"epoch":0,"holder":"","remote_lsn":0,"state":"` + state + `"}` - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(doc)) })) - defer s.Close() - read, err := NewWorkspaceHEADReader(s.URL) - if err != nil { - t.Fatal(err) - } - h, err := read(context.Background(), "v") - if !errors.Is(err, authority.ErrWorkspaceHeadDeleting) || !h.Deleting || h.Gen != 5 { - t.Fatalf("HEAD %s: %+v, %v; want ErrWorkspaceHeadDeleting with Deleting and its generation", state, h, err) - } - }) - } -} diff --git a/seaweed-block/core/host/master/workspace_layout_head.go b/seaweed-block/core/host/master/workspace_layout_head.go new file mode 100644 index 0000000000..3e6e8df66a --- /dev/null +++ b/seaweed-block/core/host/master/workspace_layout_head.go @@ -0,0 +1,125 @@ +package master + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// NewLayoutWorkspaceHEADReader resolves the master's immutable identity before +// reading one ordinary filer metadata response. Content, generation and mtime +// come from that same entry; no legacy path or body decoder is a fallback. +func NewLayoutWorkspaceHEADReader(base string, resolve func(context.Context, string) (chunkstore.VolumeRef, error)) (func(context.Context, string) (authority.WorkspaceHead, error), error) { + u, err := url.Parse(base) + if err != nil || u == nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || resolve == nil { + return nil, fmt.Errorf("workspace HEAD needs an absolute HTTP directory and master volume resolver") + } + client := &http.Client{Timeout: 5 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + return func(ctx context.Context, name string) (authority.WorkspaceHead, error) { + if err := ctx.Err(); err != nil { + return authority.WorkspaceHead{}, err + } + v, err := resolve(ctx, name) + if err != nil { + return authority.WorkspaceHead{}, err + } + if v.Name != name { + return authority.WorkspaceHead{}, layout.ErrIdentity + } + if err := (layout.Volume{ID: v.ID, Name: v.Name, Format: layout.VolumeFormat}).CheckIdentity(); err != nil { + return authority.WorkspaceHead{}, err + } + endpoint := *u + endpoint.Path = strings.TrimRight(u.Path, "/") + "/" + v.Dir() + "/HEAD" + endpoint.RawPath = "" + endpoint.RawQuery = "metadata=true" + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil) + if err != nil { + return authority.WorkspaceHead{}, err + } + res, err := client.Do(req) + if err != nil { + return authority.WorkspaceHead{}, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return authority.WorkspaceHead{}, fmt.Errorf("HEAD metadata read HTTP %d", res.StatusCode) + } + // HEAD is at most 64 KiB inline; allow its base64 envelope and ordinary + // filer attributes without accepting an unbounded metadata response. + const limit = 4 * layout.MaxHeadBytes + raw, err := io.ReadAll(io.LimitReader(res.Body, limit+1)) + if err != nil { + return authority.WorkspaceHead{}, err + } + if len(raw) > limit { + return authority.WorkspaceHead{}, fmt.Errorf("HEAD metadata too large") + } + var entry struct { + FullPath string + Content []byte + Extended map[string][]byte + Mtime time.Time + Mode uint32 + Chunks []*filerpb.FileChunk + } + if err := json.Unmarshal(raw, &entry); err != nil { + return authority.WorkspaceHead{}, err + } + if entry.FullPath != endpoint.Path { + return authority.WorkspaceHead{}, fmt.Errorf("HEAD metadata path mismatch") + } + h, err := chunkstore.DecodeLayoutHeadEntry(&filerpb.Entry{Name: "HEAD", IsDirectory: entry.Mode&uint32(os.ModeDir) != 0, Content: entry.Content, Extended: entry.Extended, Chunks: entry.Chunks}, v.ID) + if err != nil { + return authority.WorkspaceHead{}, err + } + mtime := int64(0) + if ns := entry.Mtime.UnixNano(); ns > 0 && time.Unix(0, ns).Equal(entry.Mtime) { + mtime = ns + } + proof := authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.Position, Detached: h.State == layout.StateDetached, FilerMtimeNS: mtime} + if h.State == layout.StateDeleting || h.State == layout.StateDeleted { + proof.Deleting = true + return proof, authority.ErrWorkspaceHeadDeleting + } + if h.Epoch == 0 { + return proof, authority.ErrWorkspaceHeadUnclaimed + } + return proof, nil + }, nil +} + +// WorkspaceLayoutVolume reads only published lifecycle intent. A missing +// identity cannot be inferred from a filer directory or a public HEAD. +func (h *Host) WorkspaceLayoutVolume(ctx context.Context, name string) (chunkstore.VolumeRef, error) { + if err := ctx.Err(); err != nil { + return chunkstore.VolumeRef{}, err + } + if h == nil || h.lifecycle == nil || h.lifecycle.Volumes == nil { + return chunkstore.VolumeRef{}, fmt.Errorf("workspace lifecycle intent is not ready") + } + rec, ok := h.lifecycle.Volumes.GetVolumeSnapshot(name) + if !ok { + return chunkstore.VolumeRef{}, fmt.Errorf("workspace volume %q is not registered", name) + } + id, err := layout.ParseVolumeID(rec.Spec.LayoutID) + if err != nil { + return chunkstore.VolumeRef{}, fmt.Errorf("workspace volume %q has no valid layout identity; recreate the legacy volume: %w", name, err) + } + v := chunkstore.VolumeRef{Name: rec.Spec.VolumeID, ID: id} + if v.Name != name { + return chunkstore.VolumeRef{}, layout.ErrIdentity + } + return v, nil +} diff --git a/seaweed-block/core/host/master/workspace_layout_head_test.go b/seaweed-block/core/host/master/workspace_layout_head_test.go new file mode 100644 index 0000000000..f32c00b5fe --- /dev/null +++ b/seaweed-block/core/host/master/workspace_layout_head_test.go @@ -0,0 +1,205 @@ +package master + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +type workspaceHeadBlobs struct{} + +func (workspaceHeadBlobs) Put(context.Context, []byte) (string, error) { + return "", errors.New("HEAD reader must not upload") +} +func (workspaceHeadBlobs) Get(context.Context, string) ([]byte, error) { + return nil, errors.New("HEAD reader must not hydrate") +} + +func TestWorkspaceLayoutHEADUsesTheMasterIdentity(t *testing.T) { + ctx := context.Background() + id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff") + v := chunkstore.VolumeRef{Name: "v", ID: id} + f := chunkstore.NewMemFiler() + s, err := chunkstore.NewLayoutStore(f, workspaceHeadBlobs{}, "/chunks/"+v.Dir(), id) + if err != nil { + t.Fatal(err) + } + rn := layout.RootName{Hash: layout.Sum([]byte("committed root"))} + h := layout.Head{VolumeID: id, Epoch: 3, Holder: "node/r", ClaimID: "claim", Activity: layout.Activity{Kind: layout.ActIdle}, Current: &rn, Position: 42, State: layout.StateDetached} + if err := s.CreateHead(ctx, layout.Unclaimed(id, nil)); err != nil { + t.Fatal(err) + } + if err := s.UpdateHead(ctx, 1, h); err != nil { + t.Fatal(err) + } + e, err := f.LookupEntry(ctx, "/chunks/"+v.Dir(), "HEAD") + if err != nil { + t.Fatal(err) + } + mtime := time.Unix(100, 0).UTC() + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.Header().Set("Last-Modified", time.Unix(200, 0).UTC().Format(http.TimeFormat)) + if r.URL.Path != "/chunks/"+v.Dir()+"/HEAD" || r.URL.RawQuery != "metadata=true" { + t.Errorf("unbound HEAD path: %s", r.URL) + } + _ = json.NewEncoder(w).Encode(struct { + FullPath string + Content []byte + Extended map[string][]byte + Mtime time.Time + Chunks []*filerpb.FileChunk + }{r.URL.Path, e.Content, e.Extended, mtime, nil}) + })) + defer server.Close() + read, err := NewLayoutWorkspaceHEADReader(server.URL+"/chunks", func(_ context.Context, name string) (chunkstore.VolumeRef, error) { + if name != "v" { + return chunkstore.VolumeRef{}, errors.New("not registered") + } + return v, nil + }) + if err != nil { + t.Fatal(err) + } + got, err := read(ctx, "v") + if err != nil || !got.Detached || got.Gen != 2 || got.Epoch != 3 || got.Holder != "node/r" || got.RemoteLSN != 42 || got.FilerMtimeNS != mtime.UnixNano() { + t.Fatalf("proof: %+v %v", got, err) + } + if _, err := read(ctx, "other"); err == nil || calls.Load() != 1 { + t.Fatalf("resolver failure contacted filer: %d %v", calls.Load(), err) + } + if _, err := NewLayoutWorkspaceHEADReader(server.URL, nil); err == nil { + t.Fatal("nil identity resolver accepted") + } +} + +func TestWorkspaceLayoutHEADRefusalsAndStates(t *testing.T) { + id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff") + v := chunkstore.VolumeRef{Name: "v", ID: id} + rn := layout.RootName{Hash: layout.Sum([]byte("root"))} + base := layout.Head{VolumeID: id, Epoch: 3, Holder: "node/r", ClaimID: "claim", Activity: layout.Activity{Kind: layout.ActIdle}, Current: &rn, Position: 42, State: layout.StateDetached} + type response struct { + FullPath string + Content []byte + Extended map[string][]byte + Mtime time.Time + Mode uint32 + Chunks []*filerpb.FileChunk + } + for _, tc := range []struct { + name string + state string + alter func(*response) + status int + raw string + valid bool + sentinel error + }{ + {name: "detached", valid: true}, + {name: "live", state: "live", valid: true}, + {name: "unknown mtime", valid: true, alter: func(e *response) { e.Mtime = time.Date(9999, 1, 1, 0, 0, 0, 0, time.UTC) }}, + {name: "unclaimed", state: "unclaimed", sentinel: authority.ErrWorkspaceHeadUnclaimed}, + {name: "deleted", state: layout.StateDeleted, sentinel: authority.ErrWorkspaceHeadDeleting}, + {name: "missing generation", alter: func(e *response) { delete(e.Extended, "swb.layout.gen") }}, + {name: "zero generation", alter: func(e *response) { e.Extended["swb.layout.gen"] = []byte("0") }}, + {name: "noncanonical generation", alter: func(e *response) { e.Extended["swb.layout.gen"] = []byte("09") }}, + {name: "wrong volume attribute", alter: func(e *response) { e.Extended["swb.layout.volume"] = []byte("ffffffffffffffffffffffffffffffff") }}, + {name: "wrong body volume", alter: func(e *response) { + e.Content = bytes.ReplaceAll(e.Content, []byte(id.String()), []byte("ffffffffffffffffffffffffffffffff")) + }}, + {name: "missing kind", alter: func(e *response) { delete(e.Extended, "swb.layout.kind") }}, + {name: "missing claim", alter: func(e *response) { e.Content = bytes.ReplaceAll(e.Content, []byte(`,"claim_id":"claim"`), nil) }}, + {name: "detached activity", alter: func(e *response) { + e.Content = bytes.ReplaceAll(e.Content, []byte(`"kind":"idle"`), []byte(`"kind":"snap","session":"s"`)) + }}, + {name: "chunked HEAD", alter: func(e *response) { e.Chunks = []*filerpb.FileChunk{{FileId: "x"}} }}, + {name: "directory HEAD", alter: func(e *response) { e.Mode = 1 << 31 }}, + {name: "wrong path", alter: func(e *response) { e.FullPath = "/chunks/other/HEAD" }}, + {name: "legacy content", alter: func(e *response) { + e.Content = []byte(`{"format":1,"gen":9,"epoch":3,"holder":"node/r","remote_lsn":42}`) + }}, + {name: "oversized inline HEAD", alter: func(e *response) { e.Content = bytes.Repeat([]byte("x"), layout.MaxHeadBytes+1) }, sentinel: layout.ErrHeadTooLarge}, + {name: "not found", status: http.StatusNotFound}, + {name: "unavailable", status: http.StatusServiceUnavailable}, + {name: "malformed envelope", raw: "not JSON"}, + {name: "oversized envelope", raw: string(bytes.Repeat([]byte("x"), 4*layout.MaxHeadBytes+1))}, + } { + t.Run(tc.name, func(t *testing.T) { + h := base + switch tc.state { + case "live": + h.State = layout.StateLive + case "unclaimed": + h = layout.Unclaimed(id, nil) + case layout.StateDeleted: + h = layout.Unclaimed(id, nil) + h.State = layout.StateDeleted + } + raw, err := h.Encode() + if err != nil { + t.Fatal(err) + } + e := response{FullPath: "/chunks/" + v.Dir() + "/HEAD", Content: raw, Extended: map[string][]byte{"swb.layout.gen": []byte("9"), "swb.layout.kind": []byte("head"), "swb.layout.volume": []byte(id.String())}} + if tc.alter != nil { + tc.alter(&e) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if tc.status != 0 { + w.WriteHeader(tc.status) + return + } + if tc.raw != "" { + _, _ = w.Write([]byte(tc.raw)) + return + } + _ = json.NewEncoder(w).Encode(e) + })) + defer server.Close() + read, err := NewLayoutWorkspaceHEADReader(server.URL+"/chunks", func(context.Context, string) (chunkstore.VolumeRef, error) { return v, nil }) + if err != nil { + t.Fatal(err) + } + got, err := read(context.Background(), "v") + if tc.valid { + if err != nil || got.Gen != 9 || got.Detached != (tc.state != "live") || got.FilerMtimeNS != 0 { + t.Fatalf("valid proof: %+v %v", got, err) + } + } else if tc.sentinel != nil { + if !errors.Is(err, tc.sentinel) { + t.Fatalf("sentinel: %+v %v", got, err) + } + } else if err == nil { + t.Fatalf("invalid proof accepted: %+v", got) + } + }) + } +} + +func TestWorkspaceLayoutHEADNeverFollowsRedirects(t *testing.T) { + var followed atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { followed.Add(1) })) + defer target.Close() + source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, target.URL, http.StatusFound) })) + defer source.Close() + read, err := NewLayoutWorkspaceHEADReader(source.URL, func(context.Context, string) (chunkstore.VolumeRef, error) { + return chunkstore.VolumeRef{Name: "v", ID: layout.VolumeID{1}}, nil + }) + if err != nil { + t.Fatal(err) + } + if _, err := read(context.Background(), "v"); err == nil || followed.Load() != 0 { + t.Fatalf("redirect followed: %d %v", followed.Load(), err) + } +} diff --git a/seaweed-block/core/host/master/workspace_lost_range_readout_test.go b/seaweed-block/core/host/master/workspace_lost_range_readout_test.go index 07c288e846..f57fc066f1 100644 --- a/seaweed-block/core/host/master/workspace_lost_range_readout_test.go +++ b/seaweed-block/core/host/master/workspace_lost_range_readout_test.go @@ -4,8 +4,6 @@ import ( "context" "io/fs" "log" - "net/http" - "net/http/httptest" "os" "path/filepath" "strings" @@ -115,7 +113,7 @@ func TestWorkspaceForcedMoveLostRangeOverRPC(t *testing.T) { logs := &syncBuffer{} headTime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) authDir := t.TempDir() - cfg := Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + cfg := Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, Logger: log.New(logs, "", 0), WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, FilerMtimeNS: headTime.UnixNano()}, nil @@ -220,36 +218,3 @@ func TestWorkspaceForcedMoveLostRangeOverRPC(t *testing.T) { t.Fatalf("lost range query with a damaged record: %v; want DataLoss", err) } } - -// The HEAD reader takes the HEAD entry's mtime from the filer's -// Last-Modified header of the same response; without a usable header the -// time is unknown (0), never invented. -func TestWorkspaceHEADReadsFilerMtime(t *testing.T) { - mtime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) - for _, tc := range []struct { - name, header string - want int64 - }{ - {"last-modified", mtime.Format(http.TimeFormat), mtime.UnixNano()}, - {"absent", "", 0}, - {"unparseable", "yesterday", 0}, - } { - t.Run(tc.name, func(t *testing.T) { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - if tc.header != "" { - w.Header().Set("Last-Modified", tc.header) - } - _, _ = w.Write([]byte(`{"format":1,"gen":9,"epoch":3,"holder":"old","remote_lsn":42}`)) - })) - defer s.Close() - read, err := NewWorkspaceHEADReader(s.URL) - if err != nil { - t.Fatal(err) - } - h, err := read(context.Background(), "v") - if err != nil || h.FilerMtimeNS != tc.want || h.Gen != 9 || h.RemoteLSN != 42 { - t.Fatalf("HEAD %+v %v; want filer mtime %d", h, err, tc.want) - } - }) - } -} diff --git a/seaweed-block/core/host/master/workspace_move_integration_test.go b/seaweed-block/core/host/master/workspace_move_integration_test.go deleted file mode 100644 index 5e0aab1895..0000000000 --- a/seaweed-block/core/host/master/workspace_move_integration_test.go +++ /dev/null @@ -1,325 +0,0 @@ -//go:build chunkstore_integration - -package master - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "sync/atomic" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/host/volume" - "github.com/seaweedfs/seaweed-block/core/lifecycle" - control "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/storage" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" -) - -type workspaceTakeoverWitness struct { - storage.ChunkRemote - reads, calls atomic.Uint64 - checked, committed atomic.Bool -} - -func (r *workspaceTakeoverWitness) GetHead(ctx context.Context) (storage.ChunkHead, error) { - r.reads.Add(1) - return r.ChunkRemote.GetHead(ctx) -} -func (r *workspaceTakeoverWitness) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) { - r.calls.Add(1) - gen, err := r.ChunkRemote.CASHead(ctx, v, h) - if err == nil && r.checked.Load() && h.State == "active" && h.DetachedBy == nil { - r.committed.Store(true) - } - return gen, err -} - -func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) { - c := startWorkspaceWeed(t) - for _, kind := range []string{"clean", "forced"} { - t.Run(kind, func(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) - defer cancel() - base := "/swblock/workspace-" + kind - swfs := c.client(t, base+"/vol-a") - cat, err := chunkstore.NewCatalog(swfs, base) - if err != nil { - t.Fatal(err) - } - reader, err := NewWorkspaceHEADReader("http://" + c.filerHTTP + base) - if err != nil { - t.Fatal(err) - } - h, err := New(Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceHeadReader: reader}) - if err != nil { - t.Fatal(err) - } - h.Start() - defer closeTestMaster(t, h) - if _, err = h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 64 * 4096, ReplicationFactor: 1}); err != nil { - t.Fatal(err) - } - if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101"}); err != nil { - t.Fatal(err) - } - if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: "127.0.0.1:9202", CtrlAddr: "127.0.0.1:9102"}); err != nil { - t.Fatal(err) - } - seedVerifiedExistingReplicaPlacement(t, h) - if _, err = h.RunLifecycleProductTick(); err != nil { - t.Fatal(err) - } - line := waitAuthorityLine(t, h.Publisher(), "vol-a") - conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - t.Fatal(err) - } - defer conn.Close() - client := control.NewWorkspaceServiceClient(conn) - id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch} - _, err = client.RenewWorkspaceLease(ctx, id) - if err != nil { - t.Fatal(err) - } - remote, err := chunkstore.NewSWFSChunkRemote(swfs, base+"/vol-a") - if err != nil { - t.Fatal(err) - } - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, - ChunkHolder: "node-a/" + line.ReplicaID, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - ChunkAttachCheck: func(ctx context.Context, v string, g durable.ChunkGeometry) error { - _, err := cat.EnsureVolume(ctx, v, chunkstore.Geometry{NumBlocks: g.NumBlocks, BlockSize: g.BlockSize, ChunkBlocks: g.ChunkBlocks}) - return err - }, - }, workspaceRPCView{frontend.Projection{VolumeID: "vol-a", ReplicaID: line.ReplicaID, Epoch: line.Epoch, EndpointVersion: line.EndpointVersion, Healthy: true}}) - if err != nil { - t.Fatal(err) - } - defer p.Close() - if _, err = p.EnsureStorage("vol-a"); err != nil { - t.Fatal(err) - } - if _, err = p.RecoverVolume(ctx, "vol-a"); err != nil { - t.Fatal(err) - } - backend, err := p.Open(ctx, "vol-a") - if err != nil { - t.Fatal(err) - } - want := bytes.Repeat([]byte{0xD7}, 4096) - // A nontrivial source frontier makes a reset-to-local-LSN regression visible. - for i := 0; i < 8; i++ { - if n, err := backend.Write(ctx, 9*4096, want); err != nil || n != len(want) { - t.Fatal(n, err) - } - } - if err = backend.Sync(ctx); err != nil { - t.Fatal(err) - } - if _, err = p.CaptureVolume(ctx, "vol-a"); err != nil { - t.Fatal(err) - } - q := &control.WorkspaceMove{RequestId: kind + "-actual", VolumeId: "vol-a", ExpectedReplicaId: line.ReplicaID, ExpectedEpoch: line.Epoch, TargetReplicaId: line.ReplicaID, TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:9201", TargetCtrlAddr: "127.0.0.1:9101", Kind: kind, Force: kind == "forced"} - if _, err = client.MoveWorkspace(ctx, q); err == nil { - t.Fatal("move accepted before detach/ACK or lease expiry") - } - var detached volume.ChunkDetachResponse - if kind == "clean" { - if _, err = client.RevokeWorkspace(ctx, id); err != nil { - t.Fatal(err) - } - // Real W2 adapter -> provider StopIO/drain -> final-cut serializer -> filer CAS. - detached, err = volume.NewChunkControl(p, cat).Detach(ctx, "vol-a") - if err != nil { - t.Fatal(err) - } - stored, err := swfs.LookupEntry(ctx, base+"/vol-a", "HEAD") - if err != nil { - t.Fatal(err) - } - t.Logf("producer HEAD persisted by filer: %s", stored.Content) - var root struct { - Format int `json:"format"` - Segments map[string]json.RawMessage `json:"segments"` - } - if err = json.Unmarshal(stored.Content, &root); err != nil || root.Format != 3 || len(root.Segments) == 0 { - t.Fatalf("CLEAN move must exercise upgraded segmented root: %s %v", stored.Content, err) - } - - if _, err = backend.Write(ctx, 0, want); err == nil { - t.Fatal("W2 detach left frontend writable") - } - if _, err = p.CaptureVolume(ctx, "vol-a"); err == nil { - t.Fatal("W2 detach left cuts running") - } - observed, err := reader(ctx, "vol-a") - if err != nil || !observed.Detached || observed.Gen != detached.HeadGen { - t.Fatalf("production HEAD -> HTTP reader: %+v %v", observed, err) - } - if _, err = client.MoveWorkspace(ctx, q); err == nil { - t.Fatal("detached production HEAD accepted without ACK") - } - if _, err = client.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: detached.HeadGen}); err != nil { - t.Fatal(err) - } - } else { - // The master owns the full horizon/deadline/skew barrier. Wait - // for its affirmative preview, not a locally copied expiry formula. - ticker := time.NewTicker(100 * time.Millisecond) - defer ticker.Stop() - for { - preview, err := client.PreviewWorkspaceMove(ctx, q) - if err != nil { - t.Fatal(err) - } - if preview.Admitted { - break - } - select { - case <-ticker.C: - case <-ctx.Done(): - t.Fatalf("forced preview never admitted: %v (last reason %q)", ctx.Err(), preview.Reason) - } - } - q.Force = false - if _, err = client.MoveWorkspace(ctx, q); err == nil { - t.Fatal("forced move accepted without explicit force") - } - q.Force = true - } - before, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - grant, err := client.MoveWorkspace(ctx, q) - if err != nil { - t.Fatal(err) - } - if !grant.Issued || grant.NewEpoch <= line.Epoch || grant.HeadGen != before.Gen || grant.RemoteLsn != before.RemoteLSN || grant.OldHost != "node-a" || grant.NewHost != "node-b" { - t.Fatal("grant not bound to production HEAD", grant, before) - } - status, err := client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-a"}) - if err != nil || len(status.Moves) != 1 || !status.Moves[0].Issued { - t.Fatal(status, err) - } - if kind == "clean" && (status.RevocationAck != nil || detached.HeadGen != grant.HeadGen) { - t.Fatal("grant did not consume matching ACK", status) - } - after, err := remote.GetHead(ctx) - if err != nil || after.Gen != before.Gen || after.Epoch != before.Epoch { - t.Fatal("grant itself must not claim remote fencing", after, err) - } - if _, err = client.RenewWorkspaceLease(ctx, id); err == nil { - t.Fatal("old authority renewed") - } - // Resume on an actually empty provider. No manual HEAD takeover here. - newView := workspaceRPCView{frontend.Projection{VolumeID: "vol-a", ReplicaID: grant.NewReplicaId, Epoch: grant.NewEpoch, EndpointVersion: 1, Healthy: true}} - makeTarget := func(deny bool) (*durable.DurableProvider, *workspaceTakeoverWitness) { - t.Helper() - w := &workspaceTakeoverWitness{ChunkRemote: remote} - target, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, - ChunkHolder: "node-b/" + grant.NewReplicaId, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return w, nil }, - ChunkAttachCheck: func(ctx context.Context, v string, g durable.ChunkGeometry) error { - blocks := g.NumBlocks - if deny { - blocks++ - } - _, err := cat.EnsureVolume(ctx, v, chunkstore.Geometry{NumBlocks: blocks, BlockSize: g.BlockSize, ChunkBlocks: g.ChunkBlocks}) - if err == nil { - w.checked.Store(true) - } - return err - }}, newView) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = target.Close() }) - if _, err := target.EnsureStorage("vol-a"); err != nil { - t.Fatal(err) - } - return target, w - } - denied, deniedWitness := makeTarget(true) - if _, err := denied.RecoverVolume(ctx, "vol-a"); chunkstore.CodeOf(err) != chunkstore.CodeGeometryMismatch { - t.Fatal("geometry refusal", err) - } - if deniedWitness.reads.Load() != 0 || deniedWitness.calls.Load() != 0 { - t.Fatal("VOLUME refusal came after HEAD read/CAS") - } - target, witness := makeTarget(false) - if _, err := target.RecoverVolume(ctx, "vol-a"); err != nil { - t.Fatal("h2 recovery", err) - } - beforeIO, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if !witness.committed.Load() || beforeIO.Epoch != grant.NewEpoch || beforeIO.Holder != grant.NewHost+"/"+grant.NewReplicaId || beforeIO.State != "active" || beforeIO.DetachedBy != nil { - t.Errorf("h2 ready before active takeover: HEAD=%+v committed=%v", beforeIO, witness.committed.Load()) - } - if beforeIO.RemoteLSN != before.RemoteLSN { - t.Errorf("frontier changed before first I/O: %d -> %d", before.RemoteLSN, beforeIO.RemoteLSN) - } - newBackend, err := target.Open(ctx, "vol-a") - if err != nil { - t.Fatal(err) - } - got := make([]byte, len(want)) - if n, err := newBackend.Read(ctx, 9*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) { - t.Fatal("h2 first exact I/O", n, err) - } - if n, err := newBackend.Write(ctx, 0, bytes.Repeat([]byte{0x88}, 4096)); err != nil || n != 4096 { - t.Fatal(n, err) - } - if err := newBackend.Sync(ctx); err != nil { - t.Fatal(err) - } - cut, err := target.CaptureVolume(ctx, "vol-a") - if err != nil { - t.Fatal("h2 cut", err) - } - if cut <= before.RemoteLSN { - t.Errorf("h2 remote_lsn regressed or reused source frontier: %d -> %d", before.RemoteLSN, cut) - } - t.Logf("h2 first-I/O witness: gen=%d epoch=%d holder=%s state=%s LSN=%d; next cut=%d", beforeIO.Gen, beforeIO.Epoch, beforeIO.Holder, beforeIO.State, beforeIO.RemoteLSN, cut) - if _, err = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: before.Gen, Epoch: before.Epoch}, before); !errors.Is(err, storage.ErrChunkHeadPrecondition) { - t.Fatal("old HEAD CAS not fenced after takeover", err) - } - if _, err := p.CaptureVolume(ctx, "vol-a"); err == nil { - t.Error("old host cut after h2 takeover") - } - if _, err := backend.Read(ctx, 0, make([]byte, 4096)); err == nil { - t.Error("old host served after observing h2 takeover") - } - now, err := reader(ctx, "vol-a") - if err != nil || now.Detached || now.Epoch != grant.NewEpoch { - t.Fatal("takeover failed to clear canonical proof", now, err) - } - // Bytes written by the real provider survive both metadata transitions. - entry, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - ref, ok := entry.Chunks[1] - if !ok { - t.Fatal("published data chunk missing") - } - data, err := remote.Get(ctx, ref.Key) - if err != nil || len(data) < 8192 || !bytes.Equal(data[4096:8192], want) { - t.Fatal("data changed across move", err) - } - if !t.Failed() { - t.Logf("%s production chain PASS: HEAD gen=%d LSN=%d -> grant epoch=%d -> takeover epoch=%d", kind, grant.HeadGen, grant.RemoteLsn, grant.NewEpoch, now.Epoch) - } - }) - } -} diff --git a/seaweed-block/core/host/master/workspace_move_refusal_test.go b/seaweed-block/core/host/master/workspace_move_refusal_test.go index 3bcf314468..bc4b728a6d 100644 --- a/seaweed-block/core/host/master/workspace_move_refusal_test.go +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -42,7 +42,7 @@ func (s *syncBuffer) String() string { // on that node). func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { logs := &syncBuffer{} - m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, Logger: log.New(logs, "", 0), WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil @@ -153,7 +153,7 @@ func (b *blockingWriter) Write(p []byte) (int, error) { // writer is blocked, another workspace RPC still gets the lock. func TestWorkspaceMoveRefusalLogsOutsideTheWorkspaceLock(t *testing.T) { w := &blockingWriter{marker: "MoveWorkspace refused", entered: make(chan struct{}), release: make(chan struct{})} - m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, Logger: log.New(w, "", 0), + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, Logger: log.New(w, "", 0), WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/host/master/workspace_move_slot_test.go b/seaweed-block/core/host/master/workspace_move_slot_test.go index 6362bd1c8e..44ffa896d6 100644 --- a/seaweed-block/core/host/master/workspace_move_slot_test.go +++ b/seaweed-block/core/host/master/workspace_move_slot_test.go @@ -23,7 +23,7 @@ import ( // check. The grant routes a2 to the slot-1 endpoints it asked for. func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) { heads := map[string]authority.WorkspaceHead{"a2": {Gen: 9, Epoch: 1, Holder: "node-b/r1", RemoteLSN: 42, Detached: true}} - m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceHeadReader: func(_ context.Context, v string) (authority.WorkspaceHead, error) { return heads[v], nil }}) if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/host/master/workspace_paused_grantee_test.go b/seaweed-block/core/host/master/workspace_paused_grantee_test.go index 6a89dc26b9..f80f0b36bc 100644 --- a/seaweed-block/core/host/master/workspace_paused_grantee_test.go +++ b/seaweed-block/core/host/master/workspace_paused_grantee_test.go @@ -10,6 +10,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/host/volume" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/storage" @@ -86,22 +87,23 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) { } oldBarrier := time.Unix(0, p.WorkspaceState("v").Lease.ExpiresAtNS) - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v", 64, 4) readHead := func() authority.WorkspaceHead { t.Helper() - h, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) + h, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found { + t.Fatalf("layout HEAD: found=%v err=%v", found, err) } - return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached} + return layoutWorkspaceHead(h) } open := func(holder string, view frontend.ProjectionView) *durable.DurableProvider { t.Helper() - prov, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: holder, ChunkAssignmentTimeout: 2 * time.Second, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, view) + } + fixture.Configure(&cfg) + prov, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } @@ -140,7 +142,7 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) { if err != nil || detached.Head.State != storage.ChunkHeadDetached { t.Fatalf("detach: %+v %v", detached.Head, err) } - if err := p.AckWorkspaceRevocation(ctx, "v", authority.WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: detached.Head.Gen}); err != nil { + if err := p.AckWorkspaceRevocation(ctx, "v", authority.WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: detached.Head.Gen, Holder: detached.Head.Holder}, authority.WorkspaceHead{Detached: true, Epoch: 1, Holder: detached.Head.Holder, RemoteLSN: detached.H}); err != nil { t.Fatal(err) } // The lease reply's validity is measured on the real clock: keep the @@ -202,11 +204,11 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) { // projection records the HEAD current at that instant. Close then // settles the deferred attempts, so none can land afterwards. witness := &attachWitness{base: guard, head: func() authority.WorkspaceHead { - h, err := remote.GetHead(context.Background()) // also read off the test goroutine: no t.Fatal - if err != nil { + h, found, err := fixture.Catalog.ReadHead(context.Background(), fixture.Ref) // also read off the test goroutine: no t.Fatal + if err != nil || !found { return authority.WorkspaceHead{} } - return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached} + return layoutWorkspaceHead(h) }} granteeProv := open("new-node/r", witness) refusedAt, refusals := witness.first() diff --git a/seaweed-block/core/host/master/workspace_protocol.md b/seaweed-block/core/host/master/workspace_protocol.md index 095312612c..69ef315fef 100644 --- a/seaweed-block/core/host/master/workspace_protocol.md +++ b/seaweed-block/core/host/master/workspace_protocol.md @@ -70,14 +70,14 @@ refresh cannot bypass an enrolled workspace's move path. ## Move admission and persistence -Clean: the configured filer HEAD reader must observe `state: "detached"` and -`detachedBy: {holder, epoch, gen}` matching the installed HEAD's holder, epoch and -generation. W2 writes both in the same final-cut CAS. State is exactly `active` -or `detached`; missing state means active for older HEADs. No boolean `detached` -is accepted. A new holder's takeover CAS sets active and clears detachedBy; the -move journal retains history. The master's stored revocation ACK must name that -exact HEAD generation. Revocation stops extending the lease. `AckWorkspaceRevoked` -is a trusted host protocol fact, not a request to close another host remotely. +Clean: the configured filer HEAD reader must observe B's detached state. +After the holder drains, `AckWorkspaceRevoked` reads that HEAD, checks its epoch +and holder against the authenticated caller, and persists its published position +in the ACK. Move admission matches that detached epoch, holder and position. +Snapshot deletion and restore dependencies may change generation without +changing the stopped image; generation is diagnostic readout only. A higher +epoch claim ends the stable detached predicate. Revocation stops extending the +lease. The ACK is a trusted host drain fact, not a request to close another host. Forced: the request must explicitly say `kind: "forced", force: true`; the master's lease must have expired. The journal records the observed HEAD gen and diff --git a/seaweed-block/core/host/master/workspace_restore_test.go b/seaweed-block/core/host/master/workspace_restore_test.go index 27359cf045..09cacad702 100644 --- a/seaweed-block/core/host/master/workspace_restore_test.go +++ b/seaweed-block/core/host/master/workspace_restore_test.go @@ -9,7 +9,10 @@ import ( "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -17,14 +20,18 @@ type restoreProjection struct{ projection frontend.Projection } func (v restoreProjection) Projection() frontend.Projection { return v.projection } +func layoutWorkspaceHead(h layout.Head) authority.WorkspaceHead { + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.Position, Detached: h.State == layout.StateDetached} +} + type restoreRemote struct { - storage.ChunkRemote - gets atomic.Uint64 + *chunkstore.LayoutRemote + gets *atomic.Uint64 } func (r *restoreRemote) Get(ctx context.Context, key string) ([]byte, error) { r.gets.Add(1) - return r.ChunkRemote.Get(ctx, key) + return r.LayoutRemote.Get(ctx, key) } // This CPU component loop uses a real master authority runtime, two real @@ -43,16 +50,33 @@ func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { t.Fatal(err) } oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a") - remote := &restoreRemote{ChunkRemote: storage.NewMemChunkRemote()} + fixture := testutil.NewLayoutFixture(t, "vol-a", 64, 4) + var gets atomic.Uint64 + readHead := func() layout.Head { + t.Helper() + h, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found { + t.Fatalf("layout HEAD: found=%v err=%v", found, err) + } + return h + } open := func(line authority.AuthorityBasis) (*durable.DurableProvider, frontend.Backend) { t.Helper() view := restoreProjection{frontend.Projection{VolumeID: "vol-a", ReplicaID: line.ReplicaID, Epoch: line.Epoch, EndpointVersion: line.EndpointVersion, Healthy: true}} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, view) + } + fixture.Configure(&cfg) + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(fixture.Catalog, fixture.Ref, me) + if err != nil { + return nil, err + } + return &restoreRemote{LayoutRemote: inner, gets: &gets}, nil + } + p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) } @@ -83,9 +107,9 @@ func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { if err != nil { t.Fatal(err) } - headBefore, err := remote.GetHead(ctx) - if err != nil || headBefore.RemoteLSN != cut || len(headBefore.Chunks) != 2 { - t.Fatalf("initial HEAD=%+v err=%v", headBefore, err) + headBefore := readHead() + if headBefore.Position != cut || headBefore.Current == nil { + t.Fatalf("initial HEAD=%+v", headBefore) } // The authority runtime, not either provider, allocates the next epoch. @@ -105,18 +129,15 @@ func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { if !ok || newLine.ReplicaID != "r1" || newLine.Epoch <= oldLine.Epoch { t.Fatalf("master did not move authority: %+v", newLine) } - gets := remote.gets.Load() + beforeGets := gets.Load() freshProvider, freshBackend := open(newLine) // unrelated empty local directory - if remote.gets.Load() != gets { + if gets.Load() != beforeGets { t.Error("restore eagerly fetched chunk bodies before any read") } - claimed, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if claimed.Epoch != newLine.Epoch || claimed.Holder != newLine.ReplicaID || claimed.RemoteLSN != cut { + claimed := readHead() + if claimed.Epoch != newLine.Epoch || claimed.Holder != newLine.ReplicaID || claimed.Position != cut { t.Errorf("restore served before HEAD takeover: HEAD epoch=%d holder=%q cut=%d; want master epoch=%d holder=%q cut=%d", - claimed.Epoch, claimed.Holder, claimed.RemoteLSN, newLine.Epoch, newLine.ReplicaID, cut) + claimed.Epoch, claimed.Holder, claimed.Position, newLine.Epoch, newLine.ReplicaID, cut) } for offset, data := range want { got := make([]byte, len(data)) @@ -124,7 +145,7 @@ func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { t.Fatalf("fresh exact read offset=%d n=%d err=%v", offset, n, err) } } - if remote.gets.Load() <= gets { + if gets.Load() <= beforeGets { t.Error("fresh reads did not lazily fetch HEAD chunks") } // With assignment delivery held, the stale host can still have local dirt. @@ -143,10 +164,7 @@ func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { if err := oldBackend.Sync(ctx); err == nil { t.Error("old host kept acknowledging Sync after its refused cut") } - afterStale, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } + afterStale := readHead() if !reflect.DeepEqual(afterStale, claimed) { t.Errorf("stale host changed claimed HEAD: %+v", afterStale) } @@ -165,15 +183,9 @@ func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { if newCut <= cut { t.Errorf("restored WAL did not advance beyond HEAD: old=%d new=%d", cut, newCut) } - newHead, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - final, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if final.Epoch != newLine.Epoch || final.Holder != newLine.ReplicaID || final.RemoteLSN != newCut || final.Gen != newHead.Gen || !reflect.DeepEqual(final.Chunks, newHead.Chunks) { + newHead := readHead() + final := readHead() + if final.Epoch != newLine.Epoch || final.Holder != newLine.ReplicaID || final.Position != newCut || final.Gen != newHead.Gen || !reflect.DeepEqual(final.Current, newHead.Current) { t.Errorf("old host changed restored HEAD: %+v", final) } for offset, data := range want { diff --git a/seaweed-block/core/host/master/workspace_same_host_forced_test.go b/seaweed-block/core/host/master/workspace_same_host_forced_test.go new file mode 100644 index 0000000000..0acd0db260 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_same_host_forced_test.go @@ -0,0 +1,175 @@ +package master + +import ( + "context" + "errors" + "os" + "os/exec" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/protobuf/proto" +) + +type sameHostRecoveryView struct{ epoch uint64 } + +func (v sameHostRecoveryView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v", ReplicaID: "r1", Epoch: v.epoch, Healthy: true} +} + +// The child is a separate successor process with a different data directory. +// Its admission must still use the host-wide lock, not the root's WAL lock. +func TestWorkspaceSameHostSuccessorLockProbe(t *testing.T) { + locks := os.Getenv("SWBLOCK_SAMEHOST_LOCK_PROBE") + if locks == "" { + return + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), NumBlocks: 16, BlockSize: 4096, + HostVolumeLock: true, VolumeLockDirTestOnly: locks, + }, sameHostRecoveryView{2}) + if err != nil { + t.Fatal(err) + } + defer p.Close() + _, err = p.EnsureStorage("v") + if os.Getenv("SWBLOCK_SAMEHOST_EXPECT_LOCKED") == "yes" { + if !errors.Is(err, storage.ErrWALStoreLocked) { + t.Fatalf("live predecessor did not exclude the successor: %v", err) + } + } else if err != nil { + t.Fatal("successor still excluded after predecessor close", err) + } +} + +func TestWorkspaceRPCSameHostForcedRecoveryRecordsLoss(t *testing.T) { + var nowNS atomic.Int64 + nowNS.Store(time.Now().UnixNano()) + var observed atomic.Pointer[authority.WorkspaceHead] + observed.Store(&authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42}) + h, conn, ctx := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) { + return *observed.Load(), nil + }, func(h *Host) { + authority.WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })(h.Publisher()) + }) + reviewCreate(t, conn, ctx, "v") + ws := control.NewWorkspaceServiceClient(conn) + b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + reviewHeartbeat(t, conn, ctx, "v", "node-a", b.DataAddr, b.CtrlAddr) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, h.Publisher(), "v") + if _, err := ws.RenewWorkspaceLease(ctx, leaseHolderIdentity(t, line.Epoch, "node-a")); err != nil { + t.Fatal(err) + } + guard, err := volume.NewWorkspaceLeaseGuard(sameHostRecoveryView{line.Epoch}, ws, + leaseHolderIdentity(t, line.Epoch, "node-a"), + func(context.Context) (uint64, error) { return 9, nil }, + func() time.Time { return time.Unix(0, nowNS.Load()) }) + if err != nil { + t.Fatal(err) + } + if err := guard.Refresh(ctx); err != nil { + t.Fatal(err) + } + locks := t.TempDir() + old, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), NumBlocks: 16, BlockSize: 4096, + HostVolumeLock: true, VolumeLockDirTestOnly: locks, + }, guard) + if err != nil { + t.Fatal(err) + } + defer old.Close() + if _, err := old.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + if _, err := old.RecoverVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + backend, err := old.Open(ctx, "v") + if err != nil { + t.Fatal(err) + } + if n, err := backend.Write(ctx, 0, make([]byte, 4096)); err != nil || n != 4096 { + t.Fatalf("predecessor never served under its granted lease: %d %v", n, err) + } + q := &control.WorkspaceMove{RequestId: "same-host-recovery", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1", TargetServerId: "node-a", TargetDataAddr: b.DataAddr, TargetCtrlAddr: b.CtrlAddr, Kind: "forced", Force: true} + if _, err := ws.MoveWorkspace(ctx, q); err == nil { + t.Fatal("same-host recovery bypassed a live lease") + } + nowNS.Add(int64(24 * time.Hour)) + if preview, err := ws.PreviewWorkspaceMove(ctx, q); err != nil || !preview.Admitted { + t.Fatalf("same-host recovery preview after lease barrier: %+v %v", preview, err) + } + grant, err := ws.MoveWorkspace(ctx, q) + if err != nil { + t.Fatal("same-host recovery must return a new epoch and loss record", err) + } + if grant.NewEpoch != line.Epoch+1 || grant.LostRange == nil || grant.LostRange.LostAfterLsn != 42 || grant.LostRange.OldEpoch != line.Epoch { + t.Fatalf("recovery omitted the abandoned suffix: %+v", grant) + } + if bindings, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || len(bindings) != 1 || bindings[0].Retired { + t.Fatalf("recovery retired its own target reservation: %+v %v", bindings, err) + } + if replay, err := ws.MoveWorkspace(ctx, q); err != nil || !proto.Equal(replay, grant) { + t.Fatalf("same-host recovery replay changed: %+v %v", replay, err) + } + // The binding is still live for this server. It cannot distinguish epochs; + // the predecessor's lease guard must independently refuse guest I/O. + if n, err := backend.Write(ctx, 4096, make([]byte, 4096)); n != 0 || !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("live old-epoch process served after the forced barrier: %d %v", n, err) + } + probe := func(locked bool) { + t.Helper() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestWorkspaceSameHostSuccessorLockProbe$", "-test.count=1") + for _, e := range os.Environ() { + if !strings.HasPrefix(e, "SWBLOCK_SAMEHOST_") { + cmd.Env = append(cmd.Env, e) + } + } + cmd.Env = append(cmd.Env, "SWBLOCK_SAMEHOST_LOCK_PROBE="+locks) + if locked { + cmd.Env = append(cmd.Env, "SWBLOCK_SAMEHOST_EXPECT_LOCKED=yes") + } + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("successor process locked=%t: %v\n%s", locked, err, out) + } + } + probe(true) + if err := old.Close(); err != nil { + t.Fatal(err) + } + probe(false) + id := leaseHolderIdentity(t, grant.NewEpoch, "node-a") + if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil { + t.Fatal(err) + } + if _, err := ws.RevokeWorkspace(ctx, id); err != nil { + t.Fatal(err) + } + // The successor's ACK requires its own stopped image, not the live + // predecessor HEAD used to exercise forced recovery above. + observed.Store(&authority.WorkspaceHead{Gen: 10, Epoch: grant.NewEpoch, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}) + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 10}); err != nil { + t.Fatal(err) + } + if bindings, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || len(bindings) != 1 || !bindings[0].Retired { + t.Fatalf("successor ACK did not retire its same-host binding: %+v %v", bindings, err) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 3e5a6c154d..7a9befae6f 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -26,6 +26,9 @@ func (s *services) workspaceVolume(volume string) error { if !ok || r.Spec.ReplicationFactor != 1 { return status.Error(codes.FailedPrecondition, "workspace move requires an existing RF1 volume") } + if !s.host.layoutStoreReady(volume) { + return status.Error(codes.FailedPrecondition, "workspace: created, store not ready; retry CreateVolume") + } if s.host.lifecycle.Deletions.Reserved(volume) { return status.Error(codes.FailedPrecondition, "workspace: volume is being deleted") } @@ -49,6 +52,9 @@ func (s *services) workspaceVolumeForRenewal(volume string) error { if !ok || r.Spec.ReplicationFactor != 1 { return status.Error(codes.FailedPrecondition, "workspace move requires an existing RF1 volume") } + if !s.host.layoutStoreReady(volume) { + return status.Error(codes.FailedPrecondition, "workspace: created, store not ready; retry CreateVolume") + } if s.host.lifecycle.Deletions.ReservedSnapshot(volume) { if s.host.lifecycle.Deletions.CommittedSnapshot(volume) { return leaseRefusal("workspace: volume is being deleted", control.WorkspaceLeaseRefusal_DELETED, 0) @@ -200,7 +206,19 @@ func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.Workspace } else if !ok { return nil, status.Error(codes.FailedPrecondition, "workspace ACK: server identity does not match the current holder") } - if err := s.host.Publisher().AckWorkspaceRevocation(ctx, id.GetVolumeId(), authority.WorkspaceRevokeAck{ReplicaID: id.GetReplicaId(), Epoch: id.GetEpoch(), HeadGen: q.GetHeadGen()}); err != nil { + // The holder ACK proves its local drain. Read the store-owned stop here: + // detached at this epoch is stable, but operator metadata may advance gen. + if s.host.cfg.WorkspaceHeadReader == nil { + return nil, status.Error(codes.Unavailable, "workspace ACK: detached HEAD reader unavailable") + } + readCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + head, err := s.host.cfg.WorkspaceHeadReader(readCtx, id.GetVolumeId()) + cancel() + if err != nil { + return nil, status.Errorf(codes.Unavailable, "workspace ACK: read detached HEAD: %v", err) + } + holder := id.GetServerId() + "/" + id.GetReplicaId() + if err := s.host.Publisher().AckWorkspaceRevocation(ctx, id.GetVolumeId(), authority.WorkspaceRevokeAck{ReplicaID: id.GetReplicaId(), Epoch: id.GetEpoch(), HeadGen: q.GetHeadGen(), Holder: holder}, head); err != nil { return nil, workspaceError(err) } if err := s.host.reconcileWorkspaceBindings(); err != nil { @@ -411,10 +429,8 @@ func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req autho refusal = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch()) case !ok: refusal = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId()) - // INV-WS-SAME-HOST-CLEAN-MOVE-001: the authority clean-proof - // checks still run after these endpoint and binding checks. - case target.ServerID == oldHost && (q.GetKind() != "clean" || q.GetForce()): - refusal = fmt.Sprintf("move target %q is the current source host", target.ServerID) + // The authority still checks the clean seal/ACK or forced lease barrier + // after these endpoint and binding checks, also for a same-host target. case !replay && s.host.colocatedTargetRefused(target.ServerID): refusal = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID) case !matched: diff --git a/seaweed-block/core/host/master/workspace_service_test.go b/seaweed-block/core/host/master/workspace_service_test.go index 6261450cf5..809042508b 100644 --- a/seaweed-block/core/host/master/workspace_service_test.go +++ b/seaweed-block/core/host/master/workspace_service_test.go @@ -3,13 +3,12 @@ package master import ( "context" "fmt" - "net/http" - "net/http/httptest" "reflect" "sync/atomic" "testing" "time" + "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/host/volume" "github.com/seaweedfs/seaweed-block/core/lifecycle" @@ -37,34 +36,26 @@ func (c lostAckReply) AckWorkspaceRevoked(ctx context.Context, q *control.Worksp } func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) { + // The HEAD the master reads for vol-a: held by node-a/r2 at epoch 1, + // detached once the holder's final cut is in. var detached atomic.Bool - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/vol-a/HEAD" { - http.NotFound(w, r) - return + var generation atomic.Uint64 + generation.Store(9) + reader := func(_ context.Context, vol string) (authority.WorkspaceHead, error) { + if vol != "vol-a" { + return authority.WorkspaceHead{}, fmt.Errorf("no HEAD for %s", vol) } - state := "active" - proof := "" - if detached.Load() { - state = "detached" - proof = `,"detachedBy":{"holder":"node-a/r2","epoch":1,"gen":9}` - } - fmt.Fprintf(w, `{"format":1,"gen":9,"epoch":1,"holder":"node-a/r2","remote_lsn":42,"state":%q%s}`, state, proof) - })) - defer server.Close() - reader, err := NewWorkspaceHEADReader(server.URL) - if err != nil { - t.Fatal(err) + return authority.WorkspaceHead{Gen: generation.Load(), Epoch: 1, Holder: "node-a/r2", RemoteLSN: 42, Detached: detached.Load()}, nil } authDir, lifeDir := t.TempDir(), t.TempDir() - cfg := Config{AuthorityStoreDir: authDir, LifecycleStoreDir: lifeDir, Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceHeadReader: reader} + cfg := Config{AuthorityStoreDir: authDir, LifecycleStoreDir: lifeDir, Listen: "127.0.0.1:0", WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceHeadReader: reader} h, err := New(cfg) if err != nil { t.Fatal(err) } h.Start() defer closeTestMaster(t, h) - if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + if _, err := testCreateReadyVolume(h.Lifecycle().Volumes, lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { t.Fatal(err) } if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101"}); err != nil { @@ -107,6 +98,7 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) { } // The stop/ACK path keeps its production timeout. Resolve a lost reply // from the master's exact ACK, never from elapsed time or the stop alone. + detached.Store(true) if err := g.Refresh(ctx); status.Code(err) != codes.DeadlineExceeded { t.Fatalf("expected unknown ACK reply, got %v", err) } @@ -121,6 +113,7 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) { if g.Projection().Healthy || stops != 1 { t.Fatal("revoked frontend remained admitted") } + detached.Store(false) // malformed/live store evidence must still refuse if _, err := client.MoveWorkspace(ctx, q); err == nil { t.Fatal("ACK without detached HEAD accepted") } @@ -150,11 +143,12 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) { t.Fatal("refusal consumed ACK or wrote a move", unchanged, err) } q.TargetReplicaId = "r2" + generation.Store(10) // operator metadata changed after the recorded ACK grant, err := client.MoveWorkspace(ctx, q) if err != nil { t.Fatal(err) } - if !grant.Issued || grant.NewEpoch != 2 || grant.HeadGen != 9 || grant.RemoteLsn != 42 || grant.OldHost != "node-a" || grant.NewHost != "node-b" { + if !grant.Issued || grant.NewEpoch != 2 || grant.HeadGen != 10 || grant.RemoteLsn != 42 || grant.OldHost != "node-a" || grant.NewHost != "node-b" { t.Fatal(grant) } delivered, err := stream.Recv() diff --git a/seaweed-block/core/host/master/workspace_skew_test.go b/seaweed-block/core/host/master/workspace_skew_test.go index 129667348c..7292f5f817 100644 --- a/seaweed-block/core/host/master/workspace_skew_test.go +++ b/seaweed-block/core/host/master/workspace_skew_test.go @@ -121,13 +121,13 @@ func seedSkewPublisher(t *testing.T, p *authority.Publisher, d *skewDirective) { } func TestWorkspaceClockSkewConfigReachesLeaseReply(t *testing.T) { - h, err := New(Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceMaxClockSkew: 4 * time.Second, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + h, err := New(Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceMaxClockSkew: 4 * time.Second, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) if err != nil { t.Fatal(err) } h.Start() defer closeTestMaster(t, h) - if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + if _, err := testCreateReadyVolume(h.Lifecycle().Volumes, lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { t.Fatal(err) } registerWorkspaceHolder(t, h, "node-a") // a workspace holder's server id must be registered (INV-AUTH-HOLDER-IDENTITY-001) diff --git a/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go b/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go index 5696a78b7e..ff759a065d 100644 --- a/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go +++ b/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go @@ -2,7 +2,6 @@ package master import ( "context" - "errors" "strings" "sync/atomic" "testing" @@ -52,7 +51,7 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) { return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached}, nil } const skew = 100 * time.Millisecond - m, err := New(Config{WorkspaceMaxClockSkew: skew, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) + m, err := New(Config{WorkspaceMaxClockSkew: skew, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LayoutCreateVolume: testLayoutCreateVolume, WorkspaceHeadReader: reader}) if err != nil { t.Fatal(err) } @@ -151,40 +150,4 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) { if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: "r1", Epoch: grantee}); err == nil { t.Fatal("the dead grantee's epoch renewed after the forced move") } - - // A late grantee claim. (b) Its CAS lands after the forced move's HEAD - // read but before the new owner claims: the new owner still takes HEAD - // at the higher epoch, and the grantee is fenced afterwards. - granteeCfg := storage.ChunkLayerConfig{Epoch: grantee, Holder: "node-b/r1"} - ownerCfg := storage.ChunkLayerConfig{Epoch: grant.NewEpoch, Holder: "node-c/r1"} - late, err := storage.ClaimChunkHead(ctx, remote, granteeCfg) - if err != nil { - t.Fatal("late grantee claim landing first:", err) - } - owned, err := storage.ClaimChunkHead(ctx, remote, ownerCfg) - if err != nil || owned.Epoch != grant.NewEpoch || owned.Holder != "node-c/r1" || owned.RemoteLSN != seed.RemoteLSN { - t.Fatalf("new owner's claim over the late grantee: %+v %v", owned, err) - } - if _, err := storage.ClaimChunkHead(ctx, remote, granteeCfg); !errors.Is(err, storage.ErrChunkLayerFenced) { - t.Fatalf("grantee re-claim after the new owner: %v; want fenced", err) - } - stale := late - stale.State = storage.ChunkHeadActive - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: late.Gen, Epoch: late.Epoch}, stale); !errors.Is(err, storage.ErrChunkHeadPrecondition) { - t.Fatalf("grantee HEAD write after the new owner: %v; want a CAS precondition failure", err) - } - // (a) The new owner claims first; the late grantee claim is fenced. - fresh := storage.NewMemChunkRemote() - seedDetachedHead(t, ctx, fresh, "node-a/"+oldLine.ReplicaID, oldLine.Epoch, 42) - if _, err := storage.ClaimChunkHead(ctx, fresh, ownerCfg); err != nil { - t.Fatal(err) - } - if _, err := storage.ClaimChunkHead(ctx, fresh, granteeCfg); !errors.Is(err, storage.ErrChunkLayerFenced) { - t.Fatalf("late grantee claim after the new owner: %v; want fenced", err) - } - for _, r := range []*storage.MemChunkRemote{remote, fresh} { - if h, err := r.GetHead(ctx); err != nil || h.Epoch != grant.NewEpoch || h.Holder != "node-c/r1" { - t.Fatalf("HEAD after the late claim: %+v %v; want the new owner", h, err) - } - } } diff --git a/seaweed-block/core/host/volume/chunk_b_catalog_test.go b/seaweed-block/core/host/volume/chunk_b_catalog_test.go new file mode 100644 index 0000000000..31534ebb3c --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_b_catalog_test.go @@ -0,0 +1,147 @@ +package volume + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +func TestChunkControlUsesTheBoundLayoutIdentity(t *testing.T) { + ctx := context.Background() + f := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(f, f, "/chunks") + if err != nil { + t.Fatal(err) + } + id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff") + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + h, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}) + if err != nil { + t.Fatal(err) + } + h, _, err = cat.ReadHead(ctx, ref) + if err != nil { + t.Fatal(err) + } + r := layout.RootName{Hash: layout.Sum([]byte("root"))} + h.Snapshots = map[string]layout.Snapshot{"a": {Root: r}, "b": {Root: r}, "c": {Root: r}} + s, _ := cat.Store(ref) + if err := s.UpdateHead(ctx, h.Gen, h); err != nil { + t.Fatal(err) + } + ctl := NewChunkControl(&fakeChunkProvider{}, cat, ref) + list, next, err := ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{Limit: 1}) + if err != nil || len(list) != 1 || list[0].Name != "a" || next != "a" { + t.Fatalf("first page: %+v %q %v", list, next, err) + } + if list[0].Root != r.String() { + t.Fatalf("snapshot root lost: %+v", list[0]) + } + server := chunkServer(t, ctl, true) + w := serve(t, server, http.MethodGet, "/chunk/snapshots?volume=v1&limit=1", "", "") + var body chunkstore.SnapshotListBody + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != http.StatusOK || len(body.Snapshots) != 1 || body.Snapshots[0].Root != r.String() { + t.Fatalf("HTTP root: %d %s %v", w.Code, w.Body, err) + } + list, next, err = ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{StartAfter: next, Limit: 2}) + if err != nil || len(list) != 2 || list[0].Name != "b" || list[1].Name != "c" || next != "" { + t.Fatalf("next page: %+v %q %v", list, next, err) + } + if _, _, err := ctl.ListSnapshots(ctx, "other", chunkstore.ListOptions{}); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("wrong name: %v", err) + } + if _, err := ctl.DeleteSnapshot(ctx, "v1", "b"); err != nil { + t.Fatal(err) + } + h, found, err := cat.ReadHead(ctx, ref) + if err != nil || !found || len(h.Snapshots) != 2 { + t.Fatalf("HEAD after delete: %+v %v", h, err) + } + u, err := ctl.Usage(ctx, "v1") + if err != nil || u.Snapshots != 2 || u.OwnChunks != 0 || u.ForeignChunks != 0 { + t.Fatalf("usage: %+v %v", u, err) + } + missing := NewChunkControl(&fakeChunkProvider{}, cat, chunkstore.VolumeRef{Name: "v1", ID: layout.VolumeID{1}}) + if _, _, err := missing.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("another incarnation fell back: %v", err) + } + h.Snapshots["a"] = layout.Snapshot{Root: r, Dependents: []layout.Dependent{{Target: "child", TargetID: layout.VolumeID{2}, Root: r}}} + h.Snapshots["a"] = layout.Snapshot{Root: r, Meta: layout.SnapshotMeta{CreatedNs: 7, Class: layout.ClassPinned, ExpiresNs: 20, Labels: map[string]string{"kind": "backup"}}, Dependents: h.Snapshots["a"].Dependents} + if err := s.UpdateHead(ctx, h.Gen, h); err != nil { + t.Fatal(err) + } + list, _, err = ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{Prefix: "a"}) + if err != nil || len(list) != 1 || list[0].CreatedNs != 7 || list[0].Class != layout.ClassPinned || list[0].ExpiresAtNs != 20 || list[0].Labels["kind"] != "backup" { + t.Fatalf("retention facts dropped from listing: %+v %v", list, err) + } + w = serve(t, server, http.MethodGet, "/chunk/snapshots?volume=v1&prefix=a", "", "") + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != http.StatusOK || len(body.Snapshots) != 1 || body.Snapshots[0].CreatedNs != 7 || body.Snapshots[0].Class != layout.ClassPinned || body.Snapshots[0].ExpiresAtNs != 20 || body.Snapshots[0].Labels["kind"] != "backup" { + t.Fatalf("HTTP retention facts: %d %s %v", w.Code, w.Body, err) + } + if _, err := ctl.DeleteSnapshot(ctx, "v1", "a"); !errors.Is(err, layout.ErrHasDependents) { + t.Fatalf("dependent snapshot deleted: %v", err) + } + if _, err := ctl.DeleteSnapshot(ctx, "other", "a"); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("wrong-name delete: %v", err) + } + u, err = ctl.Usage(ctx, "v1") + if err != nil || u.Dependents != 1 { + t.Fatalf("dependents missing: %+v %v", u, err) + } +} + +func TestChunkControlPassesRetentionFactsToTheNamedCommit(t *testing.T) { + fp, ctl := adapterFixture(t) + labels := map[string]string{"a": "1", "b": "2", "c": "3", "d": "4"} + info, err := ctl.Snapshot(context.Background(), "v1", ChunkSnapshotRequest{Name: "daily", Class: layout.ClassPinned, ExpiresAtNs: 123, Labels: labels}) + if err != nil || fp.snapshotName != "daily" || fp.snapshotMeta.CreatedNs <= 0 || fp.snapshotMeta.Class != layout.ClassPinned || fp.snapshotMeta.ExpiresNs != 123 || len(fp.snapshotMeta.Labels) != 4 { + t.Fatalf("capture lost retention facts: %+v %v", fp.snapshotMeta, err) + } + if info.CreatedNs != fp.snapshotMeta.CreatedNs || info.ExpiresAtNs != 123 || info.Class != layout.ClassPinned { + t.Fatalf("capture changed sampled facts: %+v", info) + } + fp.snapshotMeta.Labels["a"] = "changed" + if labels["a"] != "1" { + t.Fatal("the data path aliases the request's labels") + } + labels["e"] = "5" + before := fp.cuts + if _, err := ctl.Snapshot(context.Background(), "v1", ChunkSnapshotRequest{Name: "five", Labels: labels}); chunkstore.CodeOf(err) != chunkstore.CodeInvalidLabel || fp.cuts != before { + t.Fatalf("five labels admitted a capture: %v cuts=%d", err, fp.cuts) + } +} + +type unavailableCatalogFiler struct { + chunkstore.Filer + err error +} + +func (f unavailableCatalogFiler) LookupEntry(context.Context, string, string) (*filerpb.Entry, error) { + return nil, f.err +} + +func TestChunkControlCatalogLookupErrorIsNotAbsence(t *testing.T) { + ctx := context.Background() + want := errors.New("filer lookup failed") + f := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(unavailableCatalogFiler{Filer: f, err: want}, f, "/chunks") + if err != nil { + t.Fatal(err) + } + ctl := NewChunkControl(&fakeChunkProvider{}, cat, chunkstore.VolumeRef{Name: "v1", ID: layout.VolumeID{1}}) + if _, _, err := ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}); !errors.Is(err, want) { + t.Fatalf("lookup became empty list: %v", err) + } + if _, err := ctl.Usage(ctx, "v1"); !errors.Is(err, want) { + t.Fatalf("lookup became empty usage: %v", err) + } + if _, err := ctl.DeleteSnapshot(ctx, "v1", "s"); !errors.Is(err, want) { + t.Fatalf("unknown deletion reported success: %v", err) + } +} diff --git a/seaweed-block/core/host/volume/chunk_bootstrap_test.go b/seaweed-block/core/host/volume/chunk_bootstrap_test.go index a7b35ef46a..cf66fb5099 100644 --- a/seaweed-block/core/host/volume/chunk_bootstrap_test.go +++ b/seaweed-block/core/host/volume/chunk_bootstrap_test.go @@ -13,9 +13,9 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/replication" control "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/storage" ) func TestWALStoreChunk_ProductionStartupPublishesUnderAssignedEpoch(t *testing.T) { @@ -39,16 +39,18 @@ func TestWALStoreChunk_ProductionStartupPublishesUnderAssignedEpoch(t *testing.T t.Fatalf("assignment applied while readiness was blocked: %+v", p) } - remote := storage.NewMemChunkRemote() - dp, err := durable.NewDurableProvider(durable.ProviderConfig{ + fixture := testutil.NewLayoutFixture(t, "v1", 256, 16) + cfg := durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16, ChunkCaptureInterval: 20 * time.Millisecond, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, h.ProjectionView()) + ChunkHolder: "s1/r1", + } + fixture.Configure(&cfg) + dp, err := durable.NewDurableProvider(cfg, h.ProjectionView()) if err != nil { t.Fatal(err) } @@ -97,9 +99,9 @@ func TestWALStoreChunk_ProductionStartupPublishesUnderAssignedEpoch(t *testing.T if err != nil { t.Fatalf("on-demand capture after startup: %v", err) } - head, _ := remote.GetHead(context.Background()) - if head.Epoch != 5 || head.Holder != "r1" || head.RemoteLSN != lsn { - t.Fatalf("HEAD after on-demand capture: epoch %d holder %q remote_lsn %d (want 5, r1, %d)", head.Epoch, head.Holder, head.RemoteLSN, lsn) + head, found, err := fixture.Catalog.ReadHead(context.Background(), fixture.Ref) + if err != nil || !found || head.Epoch != 5 || head.Holder != "s1/r1" || head.Position != lsn || head.Current == nil { + t.Fatalf("HEAD after on-demand capture: %+v found=%v err=%v (want epoch 5, s1/r1, position %d)", head, found, err, lsn) } // Periodic capture under the same lineage. @@ -111,12 +113,15 @@ func TestWALStoreChunk_ProductionStartupPublishesUnderAssignedEpoch(t *testing.T } deadline = time.Now().Add(10 * time.Second) for { - head, _ = remote.GetHead(context.Background()) - if _, ok := head.Chunks[200/16]; ok && head.RemoteLSN > lsn { + head, found, err = fixture.Catalog.ReadHead(context.Background(), fixture.Ref) + if err != nil { + t.Fatal(err) + } + if found && head.Current != nil && head.Position > lsn { break } if time.Now().After(deadline) { - t.Fatalf("periodic capture never published the second write (HEAD gen %d remote_lsn %d)", head.Gen, head.RemoteLSN) + t.Fatalf("periodic capture never published the second write (HEAD gen %d position %d)", head.Gen, head.Position) } time.Sleep(20 * time.Millisecond) } diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 715eb803c9..faff58922b 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -13,11 +13,15 @@ import ( "errors" "fmt" "io" + "maps" "net/http" + "sort" "strconv" + "strings" "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" @@ -32,9 +36,9 @@ type ChunkControl interface { ListSnapshots(ctx context.Context, volumeID string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) DeleteSnapshot(ctx context.Context, volumeID, name string) (string, error) Detach(ctx context.Context, volumeID string) (ChunkDetachResponse, error) - // Usage is the volume's space accounting and retention policy + // Usage counts snapshots, dependents, and current own/foreign chunks // (GET /status/chunk). - Usage(ctx context.Context, volumeID string) (chunkstore.VolumeUsage, error) + Usage(ctx context.Context, volumeID string) (chunkstore.Usage, error) } // ChunkCutResponse is the body of a successful POST /chunk/cut (§3.1). @@ -63,7 +67,6 @@ type ChunkCutStatsBody struct { PublishPrepareNs int64 `json:"publishPrepareNs"` ManifestNs int64 `json:"manifestNs"` CommitStateNs int64 `json:"commitStateNs"` - IntentCleanupNs int64 `json:"intentCleanupNs"` NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"` PayloadNs int64 `json:"payloadNs"` @@ -104,7 +107,6 @@ func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { PublishPrepareNs: s.PublishPrepareNs, ManifestNs: s.ManifestNs, CommitStateNs: s.CommitStateNs, - IntentCleanupNs: s.IntentCleanupNs, NonPayloadCopyNs: s.NonPayloadCopyNs, PayloadNs: s.PayloadNs, @@ -238,7 +240,6 @@ func (s *StatusServer) chunkMux() http.Handler { mux.HandleFunc("/chunk/snapshots", s.handleChunkSnapshots) mux.HandleFunc("/chunk/snapshot/delete", s.handleChunkSnapshotDelete) mux.HandleFunc("/chunk/detach", s.handleChunkDetach) - mux.HandleFunc("/chunk/restore", s.handleChunkRestore) // Any other /chunk path: a typed JSON 404, like every other /chunk // error, not net/http's plain-text page. mux.HandleFunc("/chunk/", func(w http.ResponseWriter, r *http.Request) { @@ -299,6 +300,12 @@ func chunkErrorCode(err error) (int, string, bool) { case errors.Is(err, durable.ErrDetachOutcomeUnknown): // Before any cause: the detach may still have landed; I/O stays stopped. return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true + case errors.Is(err, layout.ErrGeometryMismatch): + return http.StatusConflict, chunkstore.CodeGeometryMismatch, false + case errors.Is(err, layout.ErrHeadAbsent), errors.Is(err, layout.ErrNoSnapshot): + return http.StatusNotFound, "not_found", false + case errors.Is(err, layout.ErrHasDependents), errors.Is(err, layout.ErrVolumeDeleting), errors.Is(err, layout.ErrDetached), errors.Is(err, layout.ErrIdentity): + return http.StatusConflict, "layout_refused", false case errors.As(err, &ce): return catalogStatus(ce.Code), ce.Code, ce.Retryable case errors.Is(err, storage.ErrChunkLayerFenced): @@ -620,15 +627,21 @@ type ChunkProvider interface { var errFrozenDetachUnsupported = errors.New("frozen detach unsupported by provider") type chunkControl struct { - p ChunkProvider - cat *chunkstore.Catalog - restores restoreRuns + p ChunkProvider + cat *chunkstore.BCatalog + volume chunkstore.VolumeRef } -// NewChunkControl serves the routes from a durable provider (cut, detach) -// and the catalog under the provider's chunk base (snapshots). -func NewChunkControl(p ChunkProvider, cat *chunkstore.Catalog) ChunkControl { - return &chunkControl{p: p, cat: cat} +// NewChunkControl binds catalog operations to the master's immutable volume identity. +func NewChunkControl(p ChunkProvider, cat *chunkstore.BCatalog, volume chunkstore.VolumeRef) ChunkControl { + return &chunkControl{p: p, cat: cat, volume: volume} +} + +func (c *chunkControl) catalogVolume(name string) (chunkstore.VolumeRef, error) { + if c.cat == nil || name != c.volume.Name || c.volume.ID.IsZero() { + return chunkstore.VolumeRef{}, layout.ErrIdentity + } + return c.volume, nil } func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) (ChunkCutResponse, error) { @@ -640,64 +653,88 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) Noop: r.Noop, FullHash: r.FullHash, CandidateTail: r.CandidateTail, Stats: cutStatsBody(r.Stats)}, nil } -// Snapshot resolves the request against the catalog first (§3.2 step 1): -// a retry of a recorded request returns that snapshot and another request -// for the name gets snapshot_exists, both without cutting. Only a free name -// is cut, and the HEAD that cut installed is stored. +// Snapshot belongs to the data path: its commit names the snapshot in HEAD. +// The control never records a second catalog entry after an ordinary cut. func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkSnapshotRequest) (chunkstore.SnapshotInfo, error) { - // Admit the request before anything can cut: an invalid class must - // not advance HEAD (review of #142). + if _, err := c.catalogVolume(volumeID); err != nil { + return chunkstore.SnapshotInfo{}, err + } if err := chunkstore.ValidateSnapshotClass(req.Class); err != nil { return chunkstore.SnapshotInfo{}, err } - sreq := chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID, Labels: req.Labels, - Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume", Class: req.Class} - return sealSnapshot(ctx, c.cat, volumeID, sreq, func(ctx context.Context) (storage.ChunkHead, error) { - // A named seal is urgent even without a minimum LSN. - r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) - return r.Head, err + if len(req.Labels) > layout.MaxSnapshotLabels { + return chunkstore.SnapshotInfo{}, &chunkstore.CatalogError{Code: chunkstore.CodeInvalidLabel, Message: fmt.Sprintf("snapshot has %d labels; at most %d", len(req.Labels), layout.MaxSnapshotLabels)} + } + p, ok := c.p.(interface { + SnapshotVolume(context.Context, string, string, layout.SnapshotMeta) (layout.Head, error) }) -} - -// sealSnapshot resolves sreq against the catalog first: a retry of a -// recorded request returns that snapshot and another request for the name -// fails, both without cutting. Only a free name is cut, and the HEAD that -// cut installed is stored. -func sealSnapshot(ctx context.Context, cat *chunkstore.Catalog, volumeID string, sreq chunkstore.SnapshotRequest, cut func(context.Context) (storage.ChunkHead, error)) (chunkstore.SnapshotInfo, error) { - if info, replayed, err := cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { - return info, err + if !ok { + return chunkstore.SnapshotInfo{}, errors.New("chunk snapshot data path is not configured") } - // The share begins before the cut that produces the sealed HEAD. - if g := cat.ShareGuard(); g != nil { - token, err := g.Begin(ctx, volumeID) - if err != nil { - return chunkstore.SnapshotInfo{}, err - } - sreq.ShareToken = token - } - head, err := cut(ctx) + // Sample once for this capture. The provider carries this value unchanged in + // CommitRequest.Meta; a replay returns the facts already recorded in HEAD. + meta := layout.SnapshotMeta{CreatedNs: time.Now().UnixNano(), Class: req.Class, ExpiresNs: req.ExpiresAtNs, Labels: maps.Clone(req.Labels)} + h, err := p.SnapshotVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, req.Name, meta) if err != nil { return chunkstore.SnapshotInfo{}, err } - sreq.SourceReadAt = time.Now() - return cat.CreateSnapshot(ctx, volumeID, sreq, head) + return chunkstore.SnapshotInfoFromHead(volumeID, req.Name, h), nil } func (c *chunkControl) ListSnapshots(ctx context.Context, volumeID string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) { - return c.cat.ListSnapshots(ctx, volumeID, opts) + v, err := c.catalogVolume(volumeID) + if err != nil { + return nil, "", err + } + h, found, err := c.cat.ReadHead(ctx, v) + if err != nil { + return nil, "", err + } + if !found { + return nil, "", layout.ErrHeadAbsent + } + names := make([]string, 0, len(h.Snapshots)) + for name := range h.Snapshots { + if strings.HasPrefix(name, opts.Prefix) && name > opts.StartAfter { + names = append(names, name) + } + } + sort.Strings(names) + next := "" + if opts.Limit > 0 && len(names) > opts.Limit { + names = names[:opts.Limit] + next = names[len(names)-1] + } + out := make([]chunkstore.SnapshotInfo, 0, len(names)) + for _, name := range names { + sn := h.Snapshots[name] + out = append(out, chunkstore.SnapshotInfo{VolumeID: volumeID, Name: name, Root: sn.Root.String(), Dependents: sn.Dependents, CreatedNs: sn.Meta.CreatedNs, Class: sn.Meta.Class, ExpiresAtNs: sn.Meta.ExpiresNs, Labels: maps.Clone(sn.Meta.Labels)}) + } + return out, next, nil } func (c *chunkControl) DeleteSnapshot(ctx context.Context, volumeID, name string) (string, error) { - return c.cat.DeleteSnapshot(ctx, volumeID, name) + v, err := c.catalogVolume(volumeID) + if err != nil { + return "", err + } + _, err = c.cat.DeleteSnapshot(ctx, v, name) + if err != nil { + return "", err + } + return "deleted", nil } -func (c *chunkControl) Usage(ctx context.Context, volumeID string) (chunkstore.VolumeUsage, error) { - return c.cat.Usage(ctx, volumeID) +func (c *chunkControl) Usage(ctx context.Context, volumeID string) (chunkstore.Usage, error) { + v, err := c.catalogVolume(volumeID) + if err != nil { + return chunkstore.Usage{}, err + } + return c.cat.Usage(ctx, v) } -// handleStatusChunk answers GET /status/chunk?volume=: the served -// volume's space accounting and retention policy, computed from manifests -// and filer listings (no chunk data reads). +// handleStatusChunk answers GET /status/chunk?volume= from HEAD and +// its current root (no chunk data reads). func (s *StatusServer) handleStatusChunk(w http.ResponseWriter, r *http.Request) { if !s.chunkAdmit(w, r, http.MethodGet) { return diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go index ce1ef835e7..fc23dc8c22 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -10,18 +10,21 @@ import ( "errors" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) type fakeChunkProvider struct { - cut storage.ChunkCutResult - cutErr error - cutCheck func(context.Context) error - detach storage.ChunkCutResult - last uint64 - cuts int - lastMin uint64 + cut storage.ChunkCutResult + cutErr error + cutCheck func(context.Context) error + detach storage.ChunkCutResult + last uint64 + cuts int + lastMin uint64 + snapshotMeta layout.SnapshotMeta + snapshotName string } type adapterManifestFiler struct { @@ -68,68 +71,28 @@ func (f *fakeChunkProvider) DetachVolume(context.Context, string) (storage.Chunk func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) { t.Helper() - fp, cat := adapterCatalog(t) - return fp, NewChunkControl(fp, cat) -} - -// adapterCatalog is a catalog holding volume v1 and a provider whose cut -// installs a published HEAD of v1. -func adapterCatalog(t *testing.T) (*fakeChunkProvider, *chunkstore.Catalog) { - t.Helper() - head := storage.ChunkHead{Gen: 3, Epoch: 2, Holder: "r1", RemoteLSN: 9, State: storage.ChunkHeadActive, - Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e2/c0/k1"}, 5: {Key: "chunks/e2/c5/k2"}}} + fp := &fakeChunkProvider{cut: storage.ChunkCutResult{H: 9, Head: storage.ChunkHead{Gen: 3, Epoch: 2, Holder: "r1", RemoteLSN: 9}}} f := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}} - r, err := chunkstore.NewChunkRemote(f, f, "/swblock/chunks/v1") + cat, err := chunkstore.NewBCatalog(f, f, "/chunks") if err != nil { t.Fatal(err) } - head, _, err = r.PrepareManifest(context.Background(), storage.ChunkHead{}, head, 8*4096) - if err != nil { + id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff") + v := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(context.Background(), v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { t.Fatal(err) } - fp := &fakeChunkProvider{cut: storage.ChunkCutResult{H: 9, Head: head}} - cat, err := chunkstore.NewCatalog(f, "/swblock/chunks") - if err != nil { - t.Fatal(err) - } - if _, err := cat.EnsureVolume(context.Background(), "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { - t.Fatal(err) - } - return fp, cat + return fp, NewChunkControl(fp, cat, v) } -// Snapshot validates before it cuts, then stores the HEAD its cut -// installed (§3.2); list and delete go to the catalog. -func TestChunkControl_SnapshotStoresTheCutHead(t *testing.T) { - ctx := context.Background() - fp, ctl := adapterFixture(t) - for _, bad := range []ChunkSnapshotRequest{{Name: "a/b", RequestID: "r"}, {Name: "s1"}} { - if _, err := ctl.Snapshot(ctx, "v1", bad); chunkstore.CodeOf(err) != chunkstore.CodeInvalidName { - t.Fatalf("snapshot %+v: %v, want invalid_name", bad, err) - } - } - if fp.cuts != 0 { - t.Fatalf("an invalid snapshot request cut %d times", fp.cuts) - } - info, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r", Labels: map[string]string{"agent.step": "x"}, Consistency: "app"}) - if err != nil || fp.cuts != 1 || info.HeadGen != 3 || info.HeadEpoch != 2 || info.CutLSN != 9 || info.ChunkCount != 2 || - info.Labels["agent.step"] != "x" || info.Consistency != "app" || info.Replayed { - t.Fatalf("snapshot: %+v %v (cuts %d)", info, err, fp.cuts) - } - again, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}) - if err != nil || !again.Replayed || again.HeadGen != 3 { - t.Fatalf("snapshot retry: %+v %v", again, err) - } - if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "other"}); chunkstore.CodeOf(err) != chunkstore.CodeSnapshotExists { - t.Fatalf("snapshot with another request id: %v, want snapshot_exists", err) - } - list, _, err := ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}) - if err != nil || len(list) != 1 || list[0].Name != "s1" { - t.Fatalf("list: %+v %v", list, err) - } - if st, err := ctl.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != chunkstore.SnapDeleting { - t.Fatalf("delete: %q %v", st, err) +func (f *fakeChunkProvider) SnapshotVolume(ctx context.Context, volumeID string, name string, meta layout.SnapshotMeta) (layout.Head, error) { + f.snapshotName = name + f.snapshotMeta = meta + r, err := f.CutVolume(ctx, volumeID, 0) + if err != nil { + return layout.Head{}, err } + return layout.Head{Gen: r.Head.Gen, Epoch: r.Head.Epoch, Position: r.H, Snapshots: map[string]layout.Snapshot{name: {Meta: meta}}}, nil } // The cut body carries the statistics the chunk layer measured for that diff --git a/seaweed-block/core/host/volume/chunk_control_class_test.go b/seaweed-block/core/host/volume/chunk_control_class_test.go index 89d333a9bc..bff75f0ce3 100644 --- a/seaweed-block/core/host/volume/chunk_control_class_test.go +++ b/seaweed-block/core/host/volume/chunk_control_class_test.go @@ -9,8 +9,7 @@ import ( ) // An invalid class is refused before anything cuts or writes, and as a -// client error (400); a valid class cuts once, and its replay cuts none -// (review of #142). +// client error (400). func TestChunkControl_InvalidClassRefusedBeforeCut(t *testing.T) { ctx := context.Background() fp, ctl := adapterFixture(t) @@ -30,12 +29,4 @@ func TestChunkControl_InvalidClassRefusedBeforeCut(t *testing.T) { } } - info, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: chunkstore.SnapshotClassPinned}) - if err != nil || info.Class != chunkstore.SnapshotClassPinned || fp.cuts != 1 { - t.Fatalf("valid class: %+v %v cuts=%d", info, err, fp.cuts) - } - info, err = ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: chunkstore.SnapshotClassPinned}) - if err != nil || !info.Replayed || fp.cuts != 1 { - t.Fatalf("replay: %+v %v cuts=%d; want a replay with no new cut", info, err, fp.cuts) - } } diff --git a/seaweed-block/core/host/volume/chunk_control_order_test.go b/seaweed-block/core/host/volume/chunk_control_order_test.go index 33e4da4f70..81931c42cd 100644 --- a/seaweed-block/core/host/volume/chunk_control_order_test.go +++ b/seaweed-block/core/host/volume/chunk_control_order_test.go @@ -1,44 +1,18 @@ package volume -// Operation order in the control adapter (review of #115): a snapshot -// resolves its request before it cuts (§3.2 step 1), and a cut to a minLSN -// never written publishes nothing (§3.1, MakeRemoteDurable's refusal). +// A refused minimum position never publishes an image. import ( "context" - "errors" "reflect" "testing" "github.com/seaweedfs/seaweed-block/core/frontend" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" ) -// After a recorded snapshot, the cut path fails (detached layer): a retry of -// the same request still returns the snapshot and another request gets -// snapshot_exists, neither cutting; only a free name reaches the cut. -func TestChunkControl_SnapshotResolvesRequestBeforeCutting(t *testing.T) { - ctx := context.Background() - fp, ctl := adapterFixture(t) - first, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}) - if err != nil || fp.cuts != 1 { - t.Fatalf("first snapshot: %+v %v (cuts %d)", first, err, fp.cuts) - } - fp.cutErr = storage.ErrChunkLayerDetached - again, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}) - if err != nil || !again.Replayed || again.HeadGen != first.HeadGen || fp.cuts != 1 { - t.Fatalf("retry after the cut path failed: %+v %v (cuts %d); want the recorded snapshot without a cut", again, err, fp.cuts) - } - if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "other"}); chunkstore.CodeOf(err) != chunkstore.CodeSnapshotExists || fp.cuts != 1 { - t.Fatalf("another request for the name: %v (cuts %d); want snapshot_exists without a cut", err, fp.cuts) - } - if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s2", RequestID: "r2"}); err == nil || fp.cuts != 2 { - t.Fatalf("a free name with the cut path failing: %v (cuts %d); want the cut's error", err, fp.cuts) - } -} - type healthyView struct{} func (healthyView) Projection() frontend.Projection { @@ -49,15 +23,16 @@ func (healthyView) Projection() frontend.Projection { // upload and no new HEAD; a written one cuts. func TestChunkControl_CutToUnwrittenMinLSNPublishesNothing(t *testing.T) { ctx := context.Background() - remote := storage.NewMemChunkRemote() - dp, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplWALStoreChunk, - StorageRoot: t.TempDir(), - BlockSize: 4096, - NumBlocks: 256, - ChunkBlocks: 16, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, healthyView{}) + fixture := testutil.NewLayoutFixture(t, "v1", 256, 16) + cfg := durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, + StorageRoot: t.TempDir(), + BlockSize: 4096, + NumBlocks: 256, + ChunkBlocks: 16, + } + fixture.Configure(&cfg) + dp, err := durable.NewDurableProvider(cfg, healthyView{}) if err != nil { t.Fatal(err) } @@ -69,96 +44,27 @@ func TestChunkControl_CutToUnwrittenMinLSNPublishesNothing(t *testing.T) { if _, err := dp.RecoverVolume(ctx, "v1"); err != nil { t.Fatal(err) } - claimed, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) + claimed, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || !found { + t.Fatalf("claimed layout HEAD: found=%v err=%v", found, err) } assigned := (healthyView{}).Projection() - if claimed.Gen != 1 || claimed.Epoch != assigned.Epoch || claimed.Holder != assigned.ReplicaID || - claimed.State != storage.ChunkHeadActive || claimed.RemoteLSN != 0 || claimed.DetachedBy != nil || - len(claimed.Chunks) != 0 || len(claimed.Segments) != 0 || claimed.ManifestChunkCount != 0 || claimed.ChunkBytes != 0 || remote.Puts() != 0 { - t.Fatalf("fresh open did not establish exactly one empty assigned active claim: HEAD=%+v PUTs=%d", claimed, remote.Puts()) + if claimed.Epoch != assigned.Epoch || claimed.Holder != assigned.ReplicaID || + claimed.State != layout.StateLive || claimed.Position != 0 || claimed.Current != nil { + t.Fatalf("fresh open did not establish an empty assigned live claim: HEAD=%+v", claimed) } if _, err := s.Write(1, make([]byte, 4096)); err != nil { t.Fatal(err) } - cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), "/swblock/chunks") - if err != nil { - t.Fatal(err) - } - ctl := NewChunkControl(dp, cat) + ctl := NewChunkControl(dp, fixture.Catalog, fixture.Ref) last := s.NextLSN() - 1 if _, err := ctl.Cut(ctx, "v1", last+5); err == nil { t.Fatal("a cut to an LSN never written succeeded") } - if head, err := remote.GetHead(ctx); err != nil || !reflect.DeepEqual(head, claimed) || remote.Puts() != 0 { - t.Fatalf("a refused minLSN published beyond the open claim: HEAD %+v (claim %+v), %d chunks stored, err=%v", head, claimed, remote.Puts(), err) + if head, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref); err != nil || !found || !reflect.DeepEqual(head, claimed) { + t.Fatalf("a refused minLSN published beyond the open claim: HEAD %+v (claim %+v), found=%v err=%v", head, claimed, found, err) } - if r, err := ctl.Cut(ctx, "v1", last); err != nil || r.CutLSN != last || r.HeadGen != claimed.Gen+1 { + if r, err := ctl.Cut(ctx, "v1", last); err != nil || r.CutLSN != last || r.HeadGen <= claimed.Gen { t.Fatalf("cut to the last written LSN: %+v %v", r, err) } } - -// A snapshot request with invalid labels is refused with invalid_label before -// any cut. -func TestChunkControl_InvalidLabelRefusedBeforeCutting(t *testing.T) { - fp, ctl := adapterFixture(t) - _, err := ctl.Snapshot(context.Background(), "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r", Labels: map[string]string{"Bad Key": "x"}}) - if chunkstore.CodeOf(err) != chunkstore.CodeInvalidLabel || fp.cuts != 0 { - t.Fatalf("snapshot with an invalid label: %v (cuts %d); want invalid_label without a cut", err, fp.cuts) - } -} - -// ownerGuard records, at Begin, how many cuts the provider had taken. -type ownerGuard struct { - cutsAtBegin []int - finishes []string - fp *fakeChunkProvider - beginErr error -} - -func (g *ownerGuard) Begin(context.Context, string) (string, error) { - g.cutsAtBegin = append(g.cutsAtBegin, g.fp.cuts) - if g.beginErr != nil { - return "", g.beginErr - } - return "owner", nil -} - -func (g *ownerGuard) Finish(_ context.Context, vol, token string, head storage.ChunkHead) error { - g.finishes = append(g.finishes, vol+":"+token) - return nil -} - -// The owner's seal begins the share BEFORE the cut that produces the sealed -// HEAD, and the catalog finishes it with that token (no second Begin). -func TestChunkControl_SnapshotBeginsShareBeforeTheCut(t *testing.T) { - ctx := context.Background() - fp, ctl := adapterFixture(t) - g := &ownerGuard{fp: fp} - ctl.(*chunkControl).cat.SetShareGuard(g) - if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}); err != nil { - t.Fatal(err) - } - if len(g.cutsAtBegin) != 1 || g.cutsAtBegin[0] != 0 || fp.cuts != 1 { - t.Fatalf("Begin saw %v cuts (cuts now %d); want one Begin before the one cut", g.cutsAtBegin, fp.cuts) - } - if len(g.finishes) != 1 || g.finishes[0] != "v1:owner" { - t.Fatalf("finishes %v; want one Finish with the owner's token", g.finishes) - } -} - -// A refused Begin stops the owner's seal before its cut: no cut, no Finish, -// no snapshot. -func TestChunkControl_SnapshotBeginRefusedCutsNothing(t *testing.T) { - ctx := context.Background() - fp, ctl := adapterFixture(t) - g := &ownerGuard{fp: fp, beginErr: errors.New("share refused")} - ctl.(*chunkControl).cat.SetShareGuard(g) - if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}); err == nil { - t.Fatal("snapshot after a refused Begin") - } - if fp.cuts != 0 || len(g.finishes) != 0 { - t.Fatalf("cuts %d finishes %v after a refused Begin; want none", fp.cuts, g.finishes) - } -} diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go index 0d357c704a..07749f709d 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -27,7 +27,7 @@ type fakeChunkControl struct { next string state string detach ChunkDetachResponse - usage chunkstore.VolumeUsage + usage chunkstore.Usage lastOpts chunkstore.ListOptions lastSnap ChunkSnapshotRequest lastMin uint64 @@ -62,7 +62,7 @@ func (f *fakeChunkControl) DeleteSnapshot(ctx context.Context, vol, name string) f.calls++ return f.state, f.err } -func (f *fakeChunkControl) Usage(ctx context.Context, vol string) (chunkstore.VolumeUsage, error) { +func (f *fakeChunkControl) Usage(ctx context.Context, vol string) (chunkstore.Usage, error) { f.calls++ f.remember(ctx) return f.usage, f.err diff --git a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go index 3002df004b..004d446fe9 100644 --- a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go +++ b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go @@ -1,6 +1,7 @@ package volume import ( + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "context" "encoding/json" "errors" @@ -25,7 +26,7 @@ func (p *frozenDetachProvider) DetachVolumeFrozen(_ context.Context, _ string, o } func TestChunkFrozenDetachWireContractAndPrecedence(t *testing.T) { p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{detach: storage.ChunkCutResult{H: 7, Head: storage.ChunkHead{Gen: 2, Epoch: 1, State: storage.ChunkHeadDetached}}, last: 7}} - s := chunkServer(t, NewChunkControl(p, nil), true) + s := chunkServer(t, NewChunkControl(p, nil, chunkstore.VolumeRef{}), true) at := time.Now().Add(-time.Second).UnixNano() body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d,"allowOverBudget":true}`, at) w := serve(t, s, http.MethodPost, "/chunk/detach", body, "") @@ -59,7 +60,7 @@ func TestChunkFrozenDetachWireContractAndPrecedence(t *testing.T) { func TestChunkCheckpointCarriesCandidateTail(t *testing.T) { tail := &storage.ChunkCandidateTail{Bytes: 4096, Estimate: time.Second, Known: true, RateSamples: 3, BytesPerSecond: 4096} p := &fakeChunkProvider{cut: storage.ChunkCutResult{CandidateTail: tail}} - s := chunkServer(t, NewChunkControl(p, nil), true) + s := chunkServer(t, NewChunkControl(p, nil, chunkstore.VolumeRef{}), true) w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v1"}`, "") var body ChunkCutResponse if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != 200 || body.CandidateTail == nil || *body.CandidateTail != *tail { @@ -69,7 +70,7 @@ func TestChunkCheckpointCarriesCandidateTail(t *testing.T) { func TestChunkFrozenValidationHasDistinctPreMutationCode(t *testing.T) { p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{}} - s := chunkServer(t, NewChunkControl(p, nil), true) + s := chunkServer(t, NewChunkControl(p, nil, chunkstore.VolumeRef{}), true) past := time.Now().Add(-time.Second).UnixNano() for _, body := range []string{ `{"volumeID":"v1","frozen":true}`, @@ -115,7 +116,7 @@ func TestChunkFrozenRequestRefusalCarriesNoBudget(t *testing.T) { report := storage.PrecopyReport{FrozenBudget: storage.FrozenBudget{FrozenEstimate: 5570 * time.Millisecond, FrozenEstimateKnown: true, FreezeLimit: 5 * time.Second}, Estimate: 5570 * time.Millisecond, RemainingFreeze: 4 * time.Second, GuestFreezeElapsed: time.Second, Reason: "frozen_tail_too_large"} refusal := &storage.FrozenRefusal{Report: report} p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{}, err: refusal} - srv := chunkServer(t, NewChunkControl(p, nil), true) + srv := chunkServer(t, NewChunkControl(p, nil, chunkstore.VolumeRef{}), true) body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, time.Now().Add(-time.Second).UnixNano()) w := serve(t, srv, http.MethodPost, "/chunk/detach", body, "") var got map[string]json.RawMessage diff --git a/seaweed-block/core/host/volume/chunk_frozen_refused_test.go b/seaweed-block/core/host/volume/chunk_frozen_refused_test.go index 81f1aa8a42..61c92f043c 100644 --- a/seaweed-block/core/host/volume/chunk_frozen_refused_test.go +++ b/seaweed-block/core/host/volume/chunk_frozen_refused_test.go @@ -1,6 +1,7 @@ package volume import ( + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "context" "encoding/json" "fmt" @@ -34,7 +35,7 @@ func (p *refusedDetachProvider) DetachVolumePlain(ctx context.Context, id string func TestChunkDetachFrozenRefusedBeforeProvider(t *testing.T) { p := &refusedDetachProvider{frozenDetachProvider: &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{ detach: storage.ChunkCutResult{H: 7, Head: storage.ChunkHead{Gen: 2, Epoch: 1, State: storage.ChunkHeadDetached}}, last: 7}}} - s := chunkServer(t, NewChunkControl(p, nil), true) + s := chunkServer(t, NewChunkControl(p, nil, chunkstore.VolumeRef{}), true) at := time.Now().Add(-time.Second).UnixNano() for _, body := range []string{ fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, at), diff --git a/seaweed-block/core/host/volume/chunk_plain_detach_test.go b/seaweed-block/core/host/volume/chunk_plain_detach_test.go index b6825b347a..096584a7e5 100644 --- a/seaweed-block/core/host/volume/chunk_plain_detach_test.go +++ b/seaweed-block/core/host/volume/chunk_plain_detach_test.go @@ -1,6 +1,7 @@ package volume import ( + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "context" "encoding/json" "errors" @@ -49,7 +50,7 @@ func (p *plainDetachProvider) DetachVolumePlain(ctx context.Context, id string) } func TestChunkDetachPlainAdapterAndBusyResponse(t *testing.T) { p := &plainDetachProvider{fakeChunkProvider: &fakeChunkProvider{detach: storage.ChunkCutResult{H: 9, Head: storage.ChunkHead{Gen: 3, Epoch: 2, State: storage.ChunkHeadDetached}}, last: 9}} - s := chunkServer(t, NewChunkControl(p, nil), true) + s := chunkServer(t, NewChunkControl(p, nil, chunkstore.VolumeRef{}), true) w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true,"timeoutMs":60000}`, "") if w.Code != 200 || p.plainCalls != 1 { t.Fatalf("plain adapter: %d %s calls=%d", w.Code, w.Body, p.plainCalls) diff --git a/seaweed-block/core/host/volume/chunk_restore.go b/seaweed-block/core/host/volume/chunk_restore.go deleted file mode 100644 index 94521f0134..0000000000 --- a/seaweed-block/core/host/volume/chunk_restore.go +++ /dev/null @@ -1,246 +0,0 @@ -package volume - -import ( - "context" - "errors" - "fmt" - "net/http" - "strings" - "sync" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Independent restore driver (M6.Restore). A restored volume serves at once; -// the driver then makes every chunk local (Restoring>Hydrating), re-uploads -// the chunks whose HEAD keys name another volume under the volume's own keys -// in bounded batch cuts (Hydrating>Owning, Owning>Owning; the walker and the -// batches may overlap), and writes the independence marker once HEAD holds -// no foreign ref (Owning>Independent). Every decision is read from the -// target's own facts (its VOLUME, HEAD and marker), never from the source, so -// a rerun after a crash resumes where the remote state is, and a deleted -// source snapshot or volume is a normal state. - -// Restore quantities (invariants.md Part E). -const ( - DefaultRestoreBatchChunks = 64 - DefaultRestoreBytesPerSecond = 64 << 20 -) - -// RestoreProvider is the chunk layer's restore surface for an attached volume. -type RestoreProvider interface { - HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) - OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) -} - -// RestoreConfig bounds one restore run; zero fields take the defaults. -type RestoreConfig struct { - BatchChunks int - BytesPerSecond int64 -} - -// Restore phases. -const ( - RestoreHydrating = "hydrating" - RestoreOwning = "owning" - RestoreIndependent = "independent" - RestoreFailed = "failed" -) - -// RestoreStatus is the body of /chunk/restore. -type RestoreStatus struct { - VolumeID string `json:"volumeID"` - Phase string `json:"phase"` - Running bool `json:"running"` - Filled int `json:"filled"` // chunks the walker made local - Owned int `json:"owned"` // chunks re-uploaded under own keys - Foreign int `json:"foreign"` // HEAD chunks still naming another volume - NotLocal int `json:"notLocal"` // of those, not local yet - Batches int `json:"batches"` // batch cuts run - MarkedGen uint64 `json:"markedGen"` // HEAD gen the marker names (independent) - ErrorCode string `json:"errorCode,omitempty"` - ErrorText string `json:"error,omitempty"` -} - -// foreignKey reports whether key names another volume's object: an -// owner-qualified key whose owner is not vol. -func foreignKey(vol string) func(string) bool { - own := "@" + vol + "/" - return func(key string) bool { return strings.HasPrefix(key, "@") && !strings.HasPrefix(key, own) } -} - -var ( - errRestoreStuck = errors.New("restore: foreign chunks remain but none is local and the walker fills none") - errNotRestore = errors.New("restore: not a restore") -) - -// runRestore drives one restore of vol to independence, reporting progress. -func runRestore(ctx context.Context, cat *chunkstore.Catalog, p RestoreProvider, vol string, cfg RestoreConfig, report func(RestoreStatus)) (RestoreStatus, error) { - if cfg.BatchChunks <= 0 { - cfg.BatchChunks = DefaultRestoreBatchChunks - } - if cfg.BytesPerSecond <= 0 { - cfg.BytesPerSecond = DefaultRestoreBytesPerSecond - } - st := RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} - if m, ok, err := cat.ReadIndependence(ctx, vol); err != nil { - return st, err - } else if ok { - st.Phase, st.MarkedGen = RestoreIndependent, m.HeadGen - return st, nil - } - v, ok, err := cat.ReadVolume(ctx, vol) - if err != nil { - return st, err - } - if !ok || v.Origin != chunkstore.OriginRestore { - return st, fmt.Errorf("volume %s was not made by restore: %w", vol, errNotRestore) - } - foreign := foreignKey(vol) - for stalls := 0; ; { - h, err := p.HydrateVolume(ctx, vol, cfg.BytesPerSecond) - st.Filled += h.Filled - report(st) - if err != nil { - return st, err - } - st.Phase = RestoreOwning - progressed := h.Filled > 0 - for { - o, err := p.OwnVolumeBatch(ctx, vol, cfg.BatchChunks, foreign) - st.Owned, st.Foreign, st.NotLocal = st.Owned+o.Owned, o.Remaining, o.NotLocal - if o.Owned > 0 { - st.Batches++ - progressed = true - } - report(st) - if err != nil { - return st, err - } - if o.Remaining == 0 { - m, err := cat.MarkIndependent(ctx, vol) - if err != nil { - return st, err - } - st.Phase, st.MarkedGen, st.Running = RestoreIndependent, m.HeadGen, false - report(st) - return st, nil - } - if o.Owned == 0 { - break // what is left is not local: walk again - } - } - if !progressed { - if stalls++; stalls > 2 { - return st, errRestoreStuck - } - } else { - stalls = 0 - } - } -} - -// restoreRuns holds at most one running restore per volume and the last -// status of each. -type restoreRuns struct { - mu sync.Mutex - runs map[string]*RestoreStatus -} - -// Restore reports vol's restore status and, with start, starts a run unless -// one is running (POST /chunk/restore). A run outlives the request but not -// the serving provider (RestoreOwner); it ends independent, or failed with -// the error (a later start resumes from the target's remote facts). -func (c *chunkControl) Restore(ctx context.Context, vol string, start bool) (RestoreStatus, error) { - p, ok := c.p.(RestoreProvider) - owner, owned := c.p.(RestoreOwner) - if !ok || !owned { - return RestoreStatus{}, fmt.Errorf("restore: provider has no restore surface: %w", errNotRestore) - } - c.restores.mu.Lock() - defer c.restores.mu.Unlock() - if c.restores.runs == nil { - c.restores.runs = map[string]*RestoreStatus{} - } - cur := c.restores.runs[vol] - if cur != nil && (cur.Running || !start) { - return *cur, nil - } - if !start { - return RestoreStatus{VolumeID: vol}, nil - } - st := &RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} - c.restores.runs[vol] = st - report := func(s RestoreStatus) { - c.restores.mu.Lock() - *st = s - c.restores.mu.Unlock() - } - run := func(ctx context.Context) { - final, err := runRestore(ctx, c.cat, p, vol, RestoreConfig{}, report) - final.Running = false - if err != nil { - _, code, _ := chunkErrorCode(err) - final.Phase, final.ErrorCode, final.ErrorText = RestoreFailed, code, err.Error() - } - report(final) - } - if err := owner.GoOwned(run); err != nil { - delete(c.restores.runs, vol) - return RestoreStatus{}, err - } - return *st, nil -} - -// RestoreOwner runs the driver inside the serving volume's lifetime: the -// driver's ctx ends when the owner closes, and the owner waits for it -// (DurableProvider.GoOwned). -type RestoreOwner interface { - GoOwned(fn func(ctx context.Context)) error -} - -// handleChunkRestore serves GET /chunk/restore?volume=V (status) and -// POST /chunk/restore {"volumeID": V} (start or join a run; with -// "statusOnly": true, status only). Both answer 200 with the status. -func (s *StatusServer) handleChunkRestore(w http.ResponseWriter, r *http.Request) { - method := http.MethodGet - if r.Method == http.MethodPost { - method = http.MethodPost - } - if !s.chunkAdmit(w, r, method) { - return - } - vol := r.URL.Query().Get("volume") - if method == http.MethodPost { - var req struct { - VolumeID string `json:"volumeID"` - StatusOnly bool `json:"statusOnly"` - TimeoutMs int64 `json:"timeoutMs"` - } - if !decodeChunkBody(w, r, &req) { - return - } - vol = req.VolumeID - if req.StatusOnly { - method = http.MethodGet - } - } - ctl := s.chunkTarget(w, vol) - if ctl == nil { - return - } - rc, ok := ctl.(interface { - Restore(context.Context, string, bool) (RestoreStatus, error) - }) - if !ok { - writeChunkErr(w, http.StatusNotFound, codeNotFound, false, "restore is not served here") - return - } - st, err := rc.Restore(r.Context(), vol, method == http.MethodPost) - if err != nil { - writeChunkFailure(w, err) - return - } - writeChunkJSON(w, http.StatusOK, st) -} diff --git a/seaweed-block/core/host/volume/chunk_restore_test.go b/seaweed-block/core/host/volume/chunk_restore_test.go deleted file mode 100644 index d70420b8b4..0000000000 --- a/seaweed-block/core/host/volume/chunk_restore_test.go +++ /dev/null @@ -1,394 +0,0 @@ -package volume - -import ( - "context" - "crypto/sha256" - "errors" - "fmt" - "path" - "sort" - "strings" - "sync" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -const restoreBase = "/swblock/chunks" - -var restoreGeo = chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} - -// sourceReadGuard fails every catalog read of the source volume's own -// entries (VOLUME, HEAD, snapshots) once armed; chunk bindings stay readable -// (hydration reads the source's chunks through T's qualified refs). -type sourceReadGuard struct { - *adapterManifestFiler - armed bool - reads []string -} - -func (g *sourceReadGuard) denied(dir string) bool { - src := path.Join(restoreBase, "v1") - return g.armed && (dir == src || strings.HasPrefix(dir, src+"/snap")) -} - -func (g *sourceReadGuard) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { - if g.denied(dir) { - g.reads = append(g.reads, path.Join(dir, name)) - return nil, errors.New("test: the restore driver read the source") - } - return g.adapterManifestFiler.LookupEntry(ctx, dir, name) -} - -func (g *sourceReadGuard) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { - if g.denied(dir) { - g.reads = append(g.reads, dir) - return nil, errors.New("test: the restore driver listed the source") - } - return g.adapterManifestFiler.ListEntries(ctx, dir, prefix, after, limit) -} - -// fakeRestoreProvider stands in for the chunk layer: the walk makes every -// chunk local, and a batch is one HEAD CAS replacing up to n foreign keys. -type fakeRestoreProvider struct { - r *chunkstore.ChunkRemote - local bool - hydrations int - batches int - failAtBatch int // a batch with this 1-based number fails (0: never) - mu sync.Mutex - entered chan struct{} // if set, HydrateVolume signals entry and - gate chan struct{} // then waits for gate or its ctx -} - -func (p *fakeRestoreProvider) HydrateVolume(ctx context.Context, vol string, bps int64) (storage.HydrateProgress, error) { - p.mu.Lock() - p.hydrations++ - entered, gate := p.entered, p.gate - p.mu.Unlock() - if entered != nil { - entered <- struct{}{} - select { - case <-gate: - case <-ctx.Done(): - return storage.HydrateProgress{}, ctx.Err() - } - } - if bps != DefaultRestoreBytesPerSecond { - return storage.HydrateProgress{}, fmt.Errorf("walker pace %d, want the default %d", bps, DefaultRestoreBytesPerSecond) - } - if p.local { - return storage.HydrateProgress{}, nil - } - h, err := p.r.GetHead(ctx) - if err != nil { - return storage.HydrateProgress{}, err - } - p.local = true - return storage.HydrateProgress{Filled: len(h.Chunks)}, nil -} - -func (p *fakeRestoreProvider) OwnVolumeBatch(ctx context.Context, vol string, n int, foreign func(string) bool) (storage.OwnProgress, error) { - h, err := p.r.GetHead(ctx) - if err != nil { - return storage.OwnProgress{}, err - } - var todo []uint64 - for idx, ref := range h.Chunks { - if foreign(ref.Key) { - todo = append(todo, idx) - } - } - sort.Slice(todo, func(i, j int) bool { return todo[i] < todo[j] }) - if !p.local || len(todo) == 0 { - nl := 0 - if !p.local { - nl = len(todo) - } - return storage.OwnProgress{Remaining: len(todo), NotLocal: nl}, nil - } - p.batches++ - if p.batches == p.failAtBatch { - return storage.OwnProgress{Remaining: len(todo)}, errors.New("test: batch cut failed") - } - next := storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}} - for idx, ref := range h.Chunks { - next.Chunks[idx] = ref - } - owned := 0 - for _, idx := range todo { - if owned == n { - break - } - data, err := p.r.Get(ctx, h.Chunks[idx].Key) - if err != nil { - return storage.OwnProgress{}, err - } - key := fmt.Sprintf("chunks/e3/c%d/b%d", idx, p.batches) - if err := p.r.Put(ctx, key, data); err != nil { - return storage.OwnProgress{}, err - } - next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} - owned++ - } - next, intents, err := p.r.PrepareManifest(ctx, h, next, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) - if err != nil { - return storage.OwnProgress{}, err - } - if _, err := p.r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { - return storage.OwnProgress{}, err - } - for _, id := range intents { - _ = p.r.DeleteIntent(ctx, id) - } - return storage.OwnProgress{Owned: owned, Remaining: len(todo) - owned}, nil -} - -// restoreFixtureHost publishes source v1 (chunks), snapshots it and restores -// it into v2; it returns the guard filer, the catalog and v2's provider. -func restoreFixtureHost(t *testing.T, chunks int) (*sourceReadGuard, *chunkstore.Catalog, *fakeRestoreProvider) { - t.Helper() - ctx := context.Background() - f := &sourceReadGuard{adapterManifestFiler: &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}} - cat, err := chunkstore.NewCatalog(f, restoreBase) - if err != nil { - t.Fatal(err) - } - if _, err := cat.EnsureVolume(ctx, "v1", restoreGeo); err != nil { - t.Fatal(err) - } - r1, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v1")) - if err != nil { - t.Fatal(err) - } - cur, err := r1.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} - for idx := 0; idx < chunks; idx++ { - data := make([]byte, int(restoreGeo.BlockSize)*int(restoreGeo.ChunkBlocks)) - data[0] = byte(0x60 + idx) - key := fmt.Sprintf("chunks/e1/c%d/k", idx) - if err := r1.Put(ctx, key, data); err != nil { - t.Fatal(err) - } - h.Chunks[uint64(idx)] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} - } - h, intents, err := r1.PrepareManifest(ctx, cur, h, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) - if err != nil { - t.Fatal(err) - } - if h.Gen, err = r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { - t.Fatal(err) - } - for _, id := range intents { - _ = r1.DeleteIntent(ctx, id) - } - if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { - t.Fatal(err) - } - if _, err := cat.Restore(ctx, chunkstore.ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs"}); err != nil { - t.Fatal(err) - } - r2, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v2")) - if err != nil { - t.Fatal(err) - } - return f, cat, &fakeRestoreProvider{r: r2} -} - -func noReport(RestoreStatus) {} - -// The driver walks, cuts bounded batches until no foreign ref is left and -// writes the marker, reading only the target's facts (Restoring>Hydrating> -// Owning>Owning>Independent). -func TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly(t *testing.T) { - f, cat, p := restoreFixtureHost(t, 5) - f.armed = true // from here, any read of the source's catalog entries fails - ctx := context.Background() - st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) - if err != nil { - t.Fatalf("restore: %+v %v (source reads %v)", st, err, f.reads) - } - if len(f.reads) != 0 { - t.Fatalf("the driver read the source: %v", f.reads) - } - if st.Phase != RestoreIndependent || st.Owned != 5 || st.Foreign != 0 || st.Batches != 3 || st.Filled != 5 { - t.Fatalf("status %+v, want independent after 3 batches of at most 2", st) - } - m, ok, err := cat.ReadIndependence(ctx, "v2") - if err != nil || !ok || m.HeadGen != st.MarkedGen { - t.Fatalf("marker: %+v ok=%v %v", m, ok, err) - } - again, err := runRestore(ctx, cat, p, "v2", RestoreConfig{}, noReport) - if err != nil || again.Phase != RestoreIndependent || p.batches != 3 { - t.Fatalf("a rerun of an independent restore must do nothing: %+v %v", again, err) - } -} - -// A failed batch leaves HEAD as it was; the next run resumes from the -// target's HEAD and finishes. -func TestRestoreDriver_ResumesAfterAFailedBatch(t *testing.T) { - _, cat, p := restoreFixtureHost(t, 5) - ctx := context.Background() - p.failAtBatch = 2 - st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) - if err == nil || st.Owned != 2 || st.Foreign != 3 { - t.Fatalf("first run: %+v %v, want the failure after 2 owned", st, err) - } - if _, ok, _ := cat.ReadIndependence(ctx, "v2"); ok { - t.Fatal("marker written with foreign refs left") - } - p.failAtBatch = 0 - st, err = runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) - if err != nil || st.Phase != RestoreIndependent || st.Owned != 3 { - t.Fatalf("resumed run: %+v %v, want the 3 left owned and the marker", st, err) - } -} - -// Only a restore volume is driven. -func TestRestoreDriver_RefusesAVolumeNotMadeByRestore(t *testing.T) { - _, cat, p := restoreFixtureHost(t, 1) - if _, err := runRestore(context.Background(), cat, p, "v1", RestoreConfig{}, noReport); !errors.Is(err, errNotRestore) { - t.Fatalf("driving the source volume: %v, want not a restore", err) - } -} - -// testOwner runs owned goroutines until close, which cancels and joins them -// (bounded), like DurableProvider.Close. -type testOwner struct { - ctx context.Context - cancel context.CancelFunc - wg sync.WaitGroup -} - -func newTestOwner(t *testing.T) *testOwner { - o := &testOwner{} - o.ctx, o.cancel = context.WithCancel(context.Background()) - t.Cleanup(func() { o.close(t) }) - return o -} - -func (o *testOwner) GoOwned(fn func(context.Context)) error { - o.wg.Add(1) - go func() { defer o.wg.Done(); fn(o.ctx) }() - return nil -} - -func (o *testOwner) close(t *testing.T) { - o.cancel() - done := make(chan struct{}) - go func() { o.wg.Wait(); close(done) }() - select { - case <-done: - case <-time.After(5 * time.Second): - t.Error("owned restore run did not return after close") - } -} - -// restoreOnlyProvider is a ChunkProvider (cut and detach unused) with the -// restore surface and an owner. -type restoreOnlyProvider struct { - *fakeRestoreProvider - *testOwner -} - -func (restoreOnlyProvider) CutVolume(context.Context, string, uint64) (storage.ChunkCutResult, error) { - return storage.ChunkCutResult{}, errors.New("unused") -} -func (restoreOnlyProvider) DetachVolume(context.Context, string) (storage.ChunkCutResult, uint64, error) { - return storage.ChunkCutResult{}, 0, errors.New("unused") -} - -func waitRestore(t *testing.T, ctl *chunkControl, vol string) RestoreStatus { - t.Helper() - deadline := time.Now().Add(5 * time.Second) - for { - st, err := ctl.Restore(context.Background(), vol, false) - if err != nil { - t.Fatal(err) - } - if !st.Running { - return st - } - if time.Now().After(deadline) { - t.Fatalf("restore still running: %+v", st) - } - time.Sleep(time.Millisecond) - } -} - -// POST /chunk/restore starts one background run: a second start while the -// first is held joins it (one walk), and the run is reported to the end. -func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { - _, cat, p := restoreFixtureHost(t, 3) - owner := newTestOwner(t) - p.entered, p.gate = make(chan struct{}, 2), make(chan struct{}) - release := func() { - select { - case <-p.gate: - default: - close(p.gate) - } - } - t.Cleanup(release) // registered before launch; the owner joins after it - ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} - ctx := context.Background() - if st, err := ctl.Restore(ctx, "v2", false); err != nil || st.Phase != "" { - t.Fatalf("status before any run: %+v %v", st, err) - } - if _, err := ctl.Restore(ctx, "v2", true); err != nil { - t.Fatal(err) - } - select { - case <-p.entered: - case <-time.After(5 * time.Second): - t.Fatal("the run never reached the walker") - } - if st, err := ctl.Restore(ctx, "v2", true); err != nil || !st.Running { - t.Fatalf("second start while the first runs: %+v %v, want it joined", st, err) - } - release() - st := waitRestore(t, ctl, "v2") - p.mu.Lock() - walks := p.hydrations - p.mu.Unlock() - if walks != 1 || st.Phase != RestoreIndependent || st.Owned != 3 { - t.Fatalf("walks=%d status %+v, want one run to independence", walks, st) - } -} - -// Closing the serving owner cancels a run held in a provider call and joins -// it: the run ends failed and publishes no marker after the close. -func TestRestoreDriver_OwnerCloseCancelsAndJoinsTheRun(t *testing.T) { - _, cat, p := restoreFixtureHost(t, 3) - owner := newTestOwner(t) - p.entered, p.gate = make(chan struct{}, 1), make(chan struct{}) // opened only at teardown - // Registered after the owner: it runs first, so a run that ignored the - // owner's cancel (the red case) is released before the owner's join. - t.Cleanup(func() { close(p.gate) }) - ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} - if _, err := ctl.Restore(context.Background(), "v2", true); err != nil { - t.Fatal(err) - } - select { - case <-p.entered: - case <-time.After(5 * time.Second): - t.Fatal("the run never reached the walker") - } - owner.close(t) // cancel and bounded join, like DurableProvider.Close - st, err := ctl.Restore(context.Background(), "v2", false) - if err != nil || st.Running || st.Phase != RestoreFailed { - t.Fatalf("status after the owner closed: %+v %v, want a finished failed run", st, err) - } - if _, ok, _ := cat.ReadIndependence(context.Background(), "v2"); ok { - t.Fatal("a marker was published after the owner closed") - } -} - -var _ RestoreProvider = (*durable.DurableProvider)(nil) diff --git a/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go b/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go index f75c995d00..b552790991 100644 --- a/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go +++ b/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go @@ -6,30 +6,23 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) -// ScheduledSnapshotName is the name of the scheduled snapshot attempted -// at at (UTC, to the second). +// ScheduledSnapshotName binds retries of one scheduled attempt to one name. func ScheduledSnapshotName(at time.Time) string { return "sched-" + at.UTC().Format("20060102T150405Z") } -// ScheduledSnapshot returns the provider's scheduled-snapshot callback -// (durable.ProviderConfig.ChunkScheduledSnapshot) over cat. Each attempt -// is one named snapshot of class "scheduled", labelled with keep (the -// count retention keeps), sealed through the same path as an explicit -// named snapshot: the request is resolved first, then one cut, then the -// record of that cut's HEAD. A failure carries the code the control -// endpoint would report. -func ScheduledSnapshot(cat *chunkstore.Catalog, keep int) func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error { - labels := map[string]string{chunkstore.LabelScheduleKeep: strconv.Itoa(keep)} - return func(ctx context.Context, volumeID string, at time.Time, cut func(context.Context) (storage.ChunkHead, error)) error { - name := ScheduledSnapshotName(at) - sreq := chunkstore.SnapshotRequest{Name: name, RequestID: name, Labels: labels, - CreatedBy: "blockvolume-schedule", Class: chunkstore.SnapshotClassScheduled} - if _, err := sealSnapshot(ctx, cat, volumeID, sreq, cut); err != nil { +// ScheduledSnapshot uses the same snapshot commit as an explicit snapshot; +// it never follows an ordinary cut with a second catalog write. +func ScheduledSnapshot(snapshot func(context.Context, string, string, layout.SnapshotMeta) (chunkstore.SnapshotInfo, error), keep int) func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error { + return func(ctx context.Context, volumeID string, at time.Time, _ func(context.Context) (storage.ChunkHead, error)) error { + meta := layout.SnapshotMeta{CreatedNs: at.UnixNano(), Class: layout.ClassScheduled, Labels: map[string]string{retain.LabelScheduleKeep: strconv.Itoa(keep)}} + if _, err := snapshot(ctx, volumeID, ScheduledSnapshotName(at), meta); err != nil { _, code, _ := chunkErrorCode(err) return &durable.SnapshotFailure{Code: code, Err: err} } diff --git a/seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go b/seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go index 4290703cee..ec4b042411 100644 --- a/seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go +++ b/seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go @@ -7,39 +7,35 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) -// A scheduled snapshot is one named snapshot of class "scheduled", named -// for its attempt time and labelled with the schedule's keep, recording -// exactly the HEAD its own cut installed. A retry of the same attempt -// replays without cutting again. +// A scheduled attempt uses the provider's atomic snapshot path and stable +// name/metadata on retry; it never invokes an ordinary cut or catalog write. func TestScheduledSnapshot_SealsTheCutHeadAsScheduled(t *testing.T) { ctx := context.Background() - fp, cat := adapterCatalog(t) - take := ScheduledSnapshot(cat, 7) at := time.Date(2026, 11, 21, 3, 4, 5, 0, time.UTC) - cuts := 0 - cut := func(ctx context.Context) (storage.ChunkHead, error) { - cuts++ - r, err := fp.CutVolume(ctx, "v1", 0) - return r.Head, err + calls := 0 + take := ScheduledSnapshot(func(_ context.Context, volume, name string, meta layout.SnapshotMeta) (chunkstore.SnapshotInfo, error) { + calls++ + if volume != "v1" || name != "sched-20261121T030405Z" || meta.Class != layout.ClassScheduled || meta.CreatedNs != at.UnixNano() || meta.Labels[retain.LabelScheduleKeep] != "7" { + t.Fatalf("snapshot %s %s %+v", volume, name, meta) + } + return chunkstore.SnapshotInfo{}, nil + }, 7) + for i := 0; i < 2; i++ { + if err := take(ctx, "v1", at, func(context.Context) (storage.ChunkHead, error) { + t.Fatal("ordinary cut bypasses snapshot commit") + return storage.ChunkHead{}, nil + }); err != nil { + t.Fatal(err) + } } - if err := take(ctx, "v1", at, cut); err != nil { - t.Fatal(err) - } - if err := take(ctx, "v1", at, cut); err != nil || cuts != 1 { - t.Fatalf("retry of the same attempt: %v, %d cuts; want a replay without a second cut", err, cuts) - } - list, _, err := cat.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}) - if err != nil || len(list) != 1 { - t.Fatalf("list: %+v %v", list, err) - } - s := list[0] - if s.Name != "sched-20261121T030405Z" || s.Class != chunkstore.SnapshotClassScheduled || s.Labels[chunkstore.LabelScheduleKeep] != "7" || - s.HeadGen != fp.cut.Head.Gen || s.HeadEpoch != fp.cut.Head.Epoch || s.CutLSN != fp.cut.Head.RemoteLSN { - t.Fatalf("snapshot %+v; want sched-20261121T030405Z, class scheduled, keep 7, the cut's HEAD", s) + if calls != 2 { + t.Fatalf("snapshot calls=%d", calls) } } @@ -47,8 +43,6 @@ func TestScheduledSnapshot_SealsTheCutHeadAsScheduled(t *testing.T) { // the control endpoint gives the same error, and records nothing. func TestScheduledSnapshot_FailureCarriesTheEndpointCode(t *testing.T) { ctx := context.Background() - _, cat := adapterCatalog(t) - take := ScheduledSnapshot(cat, 7) for _, c := range []struct { err error code string @@ -57,13 +51,13 @@ func TestScheduledSnapshot_FailureCarriesTheEndpointCode(t *testing.T) { {storage.ErrChunkRemoteUnavailable, chunkstore.CodeRemoteUnavailable}, {context.DeadlineExceeded, chunkstore.CodeDeadlineExceeded}, } { - err := take(ctx, "v1", time.Now(), func(context.Context) (storage.ChunkHead, error) { return storage.ChunkHead{}, c.err }) + take := ScheduledSnapshot(func(context.Context, string, string, layout.SnapshotMeta) (chunkstore.SnapshotInfo, error) { + return chunkstore.SnapshotInfo{}, c.err + }, 7) + err := take(ctx, "v1", time.Now(), nil) var f *durable.SnapshotFailure if !errors.As(err, &f) || f.Code != c.code || !errors.Is(err, c.err) { t.Fatalf("cut error %v: got %v; want a SnapshotFailure with code %s", c.err, err, c.code) } } - if list, _, _ := cat.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}); len(list) != 0 { - t.Fatalf("failed attempts recorded %+v", list) - } } diff --git a/seaweed-block/core/host/volume/chunk_seed_replication_test.go b/seaweed-block/core/host/volume/chunk_seed_replication_test.go index a687a309fd..cf72ba5247 100644 --- a/seaweed-block/core/host/volume/chunk_seed_replication_test.go +++ b/seaweed-block/core/host/volume/chunk_seed_replication_test.go @@ -14,10 +14,11 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" "github.com/seaweedfs/seaweed-block/core/replication" control "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/storage" ) // RED: a remote HEAD at LSN 5000 is inherited, so the frontier jumps after @@ -38,12 +39,32 @@ func TestWALStoreChunk_NewLineageHostWritesWithoutSeed(t *testing.T) { func restoredHostWrites(t *testing.T, inheritedLSN uint64, observerAfterSeed bool) { ctx := context.Background() - remote := storage.NewMemChunkRemote() + fixture := testutil.NewLayoutFixture(t, "v1", 256, 16) if inheritedLSN > 0 { - // The remote HEAD a previous holder (epoch 1) published. - if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{ - Epoch: 1, Holder: "old/r1", RemoteLSN: inheritedLSN, Chunks: map[uint64]storage.ChunkRef{}, - }); err != nil { + // The previous holder committed an empty image at the inherited + // frontier. The returning host's first guest write is beyond it. + st, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + t.Fatal(err) + } + root, _, err := layout.Build(nil) + if err != nil { + t.Fatal(err) + } + name, raw, err := layout.NameRoot(root) + if err != nil { + t.Fatal(err) + } + if err := layout.EnsureObject(ctx, st, name.Path(), raw, "seed-fixture"); err != nil { + t.Fatal(err) + } + head, found, err := st.ReadHead(ctx) + if err != nil || !found { + t.Fatalf("initial HEAD: found=%v err=%v", found, err) + } + head.Epoch, head.Holder, head.ClaimID = 1, "old/r1", "old-claim" + head.Current, head.Position = &name, inheritedLSN + if err := st.UpdateHead(ctx, head.Gen, head); err != nil { t.Fatal(err) } } @@ -64,14 +85,15 @@ func restoredHostWrites(t *testing.T, inheritedLSN uint64, observerAfterSeed boo h.BlockLocalReadiness("awaiting durable recovery") h.applyFixtureFact(&control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 5, EndpointVersion: 2, PeerSetGeneration: 1}) - dp, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplWALStoreChunk, - StorageRoot: t.TempDir(), // empty: a fresh host - BlockSize: 4096, - NumBlocks: 256, - ChunkBlocks: 16, - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, - }, h.ProjectionView()) + cfg := durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, + StorageRoot: t.TempDir(), // empty: a fresh host + BlockSize: 4096, + NumBlocks: 256, + ChunkBlocks: 16, + } + fixture.Configure(&cfg) + dp, err := durable.NewDurableProvider(cfg, h.ProjectionView()) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/host/volume/status_chunk_test.go b/seaweed-block/core/host/volume/status_chunk_test.go index 469b129eea..4c33eef1ed 100644 --- a/seaweed-block/core/host/volume/status_chunk_test.go +++ b/seaweed-block/core/host/volume/status_chunk_test.go @@ -7,28 +7,26 @@ import ( "testing" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) // GET /status/chunk?volume= answers the served volume's space accounting // and retention policy; the usual chunk-route guards apply. func TestStatusServer_StatusChunkUsage(t *testing.T) { - fake := &fakeChunkControl{usage: chunkstore.VolumeUsage{ - VolumeID: "v1", ChunkBytes: 32768, LiveChunks: 2, LiveBytes: 65536, StoredBindings: 3, StoredBytes: 98304, StoredUpperBound: true, - Snapshots: []chunkstore.SnapshotUsage{{Name: "s1", Class: chunkstore.SnapshotClassSemantic, Chunks: 2, ExclusiveBytes: 32768}}, - Policy: chunkstore.DefaultRetentionPolicy(), - }} + fake := &fakeChunkControl{usage: chunkstore.Usage{Snapshots: 1, Dependents: 2, OwnChunks: 3, ForeignChunks: 4}} s := chunkServer(t, fake, true) w := serveStatusChunk(t, s, http.MethodGet, "/status/chunk?volume=v1") if w.Code != http.StatusOK { t.Fatalf("status %d: %s", w.Code, w.Body) } - var got chunkstore.VolumeUsage + var got chunkstore.Usage if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { t.Fatal(err) } - if got.LiveBytes != 65536 || got.StoredBytes != 98304 || !got.StoredUpperBound || len(got.Snapshots) != 1 || got.Snapshots[0].ExclusiveBytes != 32768 || got.Policy.KeepNewest != chunkstore.DefaultKeepNewest { + if got != fake.usage { t.Fatalf("usage body %+v", got) } + if w := serveStatusChunk(t, s, http.MethodGet, "/status/chunk?volume=v9"); w.Code != http.StatusNotFound { t.Fatalf("other volume: %d", w.Code) } @@ -44,7 +42,7 @@ func TestStatusServer_ChunkSnapshotCarriesClass(t *testing.T) { if w := serve(t, s, http.MethodPost, "/chunk/snapshot", `{"volumeID":"v1","name":"s1","requestID":"r","class":"pinned"}`, ""); w.Code != http.StatusOK { t.Fatalf("snapshot: %d %s", w.Code, w.Body) } - if fake.lastSnap.Class != chunkstore.SnapshotClassPinned { + if fake.lastSnap.Class != layout.ClassPinned { t.Fatalf("class not passed through: %+v", fake.lastSnap) } } diff --git a/seaweed-block/core/host/volume/status_schema_test.go b/seaweed-block/core/host/volume/status_schema_test.go index 348909f843..583c0f5d56 100644 --- a/seaweed-block/core/host/volume/status_schema_test.go +++ b/seaweed-block/core/host/volume/status_schema_test.go @@ -29,7 +29,7 @@ var statusRoutes = []struct { {"/status/peers", "replication peers of the served volume", reflect.TypeOf(peersStatusBody{})}, {"/status/durable", "durable store state of the served volume", reflect.TypeOf(durableStatusBody{})}, {"/status/recovery", "the engine's replica projection (only with recovery enabled)", reflect.TypeOf(engine.ReplicaProjection{})}, - {"/status/chunk", "chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint)", reflect.TypeOf(chunkstore.VolumeUsage{})}, + {"/status/chunk", "chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint)", reflect.TypeOf(chunkstore.Usage{})}, {"/status/nvme", "NVMe/TCP frontend counters", reflect.TypeOf(NVMeStatus{})}, {"/status/ublk", "ublk frontend counters", reflect.TypeOf(UblkStatus{})}, {"/status/frontend-capabilities", "the frontends this host can serve", reflect.TypeOf(FrontendCapabilitiesStatus{})}, diff --git a/seaweed-block/core/host/volume/workspace_lease_stop_pending_test.go b/seaweed-block/core/host/volume/workspace_lease_stop_pending_test.go index a9643e7bb3..910df07fbd 100644 --- a/seaweed-block/core/host/volume/workspace_lease_stop_pending_test.go +++ b/seaweed-block/core/host/volume/workspace_lease_stop_pending_test.go @@ -8,7 +8,10 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -253,30 +256,30 @@ func TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt(t *testing.T) { } } -// detachFaultRemote makes the next detach fail one way. +// detachFaultRemote makes the next B-layout detach fail one way. type detachFaultRemote struct { - *storage.MemChunkRemote - mu sync.Mutex - casMode string // "refuse": precondition, not applied; "lost": not applied, error - getHeadErr error + *chunkstore.LayoutRemote + mu sync.Mutex + casMode string // "refuse": precondition, not applied; "lost": not applied, error + abortErr error } var errInjectedRemote = errors.New("injected remote fault") -func (r *detachFaultRemote) set(mode string, headErr error) { +func (r *detachFaultRemote) set(mode string, abortErr error) { r.mu.Lock() - r.casMode, r.getHeadErr = mode, headErr + r.casMode, r.abortErr = mode, abortErr r.mu.Unlock() } -func (r *detachFaultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { +func (r *detachFaultRemote) AbortOpenSession(ctx context.Context) (string, error) { r.mu.Lock() - err := r.getHeadErr + err := r.abortErr r.mu.Unlock() if err != nil { - return storage.ChunkHead{}, err + return "", err } - return r.MemChunkRemote.GetHead(ctx) + return r.LayoutRemote.AbortOpenSession(ctx) } func (r *detachFaultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { @@ -290,28 +293,38 @@ func (r *detachFaultRemote) CASHead(ctx context.Context, expected storage.ChunkH case "lost": return 0, errInjectedRemote } - return r.MemChunkRemote.CASHead(ctx, expected, next) + return r.LayoutRemote.CASHead(ctx, expected, next) } // detachHost is a leased workspace host whose provider reports detaches to // it through both hooks, as blockvolume wires them. type detachHost struct { - h *Host - p *durable.DurableProvider - wire *runtimeLeaseServer - remote *detachFaultRemote - done <-chan error + h *Host + p *durable.DurableProvider + wire *runtimeLeaseServer + remote *detachFaultRemote + fixture *testutil.LayoutFixture + done <-chan error } func newDetachHost(t *testing.T) *detachHost { t.Helper() var stopped atomic.Bool - d := &detachHost{wire: &runtimeLeaseServer{ttl: 30 * time.Second, stopped: &stopped}, remote: &detachFaultRemote{MemChunkRemote: storage.NewMemChunkRemote()}} + d := &detachHost{wire: &runtimeLeaseServer{ttl: 30 * time.Second, stopped: &stopped}, remote: &detachFaultRemote{}, fixture: testutil.NewLayoutFixture(t, "v1", 64, 8)} d.h = workspaceRuntimeHost(t, runtimeWire(t, d.wire), true) - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1", - ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return d.remote, nil }, + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1", OnChunkDetach: d.h.WorkspaceStopPending, - OnChunkDetachResumed: d.h.WorkspaceStopResumed}, d.h.ProjectionView()) + OnChunkDetachResumed: d.h.WorkspaceStopResumed} + d.fixture.Configure(&cfg) + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + inner, err := chunkstore.NewLayoutRemote(d.fixture.Catalog, d.fixture.Ref, me) + if err != nil { + return nil, err + } + d.remote.LayoutRemote = inner + return d.remote, nil + } + p, err := durable.NewDurableProvider(cfg, d.h.ProjectionView()) if err != nil { t.Fatal(err) } @@ -337,7 +350,10 @@ func newDetachHost(t *testing.T) *detachHost { return 0, err } stopped.Store(true) - head, err := d.remote.MemChunkRemote.GetHead(c) + head, found, err := d.fixture.Catalog.ReadHead(c, d.fixture.Ref) + if err == nil && !found { + err = errors.New("HEAD absent") + } return head.Gen, err }) }, func() { _ = p.Close() }) @@ -433,13 +449,14 @@ func TestWorkspaceHostFailedDetachStopPendingByOutcome(t *testing.T) { t.Run("fenced-stays-pending", func(t *testing.T) { d := newDetachHost(t) ctx := context.Background() - cur, err := d.remote.MemChunkRemote.GetHead(ctx) + cur := runtimeLayoutHead(t, d.fixture) + newer := cur + newer.Epoch, newer.Holder, newer.ClaimID = max(cur.Epoch, 3)+1, "another-holder", "foreign-claim" // above assignment epoch 3 + st, err := d.fixture.Catalog.Store(d.fixture.Ref) if err != nil { t.Fatal(err) } - newer := cur - newer.Epoch, newer.Holder = max(cur.Epoch, 3)+1, "another-holder" // above the host's assignment epoch 3 - if _, err := d.remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil { + if err := st.UpdateHead(ctx, cur.Gen, newer); err != nil { t.Fatal(err) } if _, _, err := d.p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) { diff --git a/seaweed-block/core/host/volume/workspace_runtime_test.go b/seaweed-block/core/host/volume/workspace_runtime_test.go index b8ea211a20..bedb68f751 100644 --- a/seaweed-block/core/host/volume/workspace_runtime_test.go +++ b/seaweed-block/core/host/volume/workspace_runtime_test.go @@ -6,9 +6,10 @@ import ( "errors" "github.com/seaweedfs/seaweed-block/core/engine" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" control "github.com/seaweedfs/seaweed-block/core/rpc/control" - "github.com/seaweedfs/seaweed-block/core/storage" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -42,8 +43,10 @@ func TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut(t *testing.T) { if h.ProjectionView().Projection().Healthy { t.Fatal("workspace host reports healthy without ever acquiring a lease") } - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, h.ProjectionView()) + fixture := testutil.NewLayoutFixture(t, "v1", 64, 8) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1"} + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, h.ProjectionView()) if err != nil { t.Fatal(err) } @@ -61,8 +64,8 @@ func TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut(t *testing.T) { if _, err = p.CaptureVolume(context.Background(), "v1"); err == nil { t.Fatal("unleased cut succeeded") } - if head, err := remote.GetHead(context.Background()); err != nil || head.Gen != 0 { - t.Fatal("unleased HEAD mutation", head, err) + if head := runtimeLayoutHead(t, fixture); head.Gen != 1 || head.Holder != "" { + t.Fatal("unleased HEAD mutation", head) } legacy := workspaceRuntimeHost(t, "127.0.0.1:1", false) if !legacy.ProjectionView().Projection().Healthy { @@ -139,10 +142,50 @@ func runtimeAwait(t *testing.T, what string, fn func() bool) { } } } -func runtimeStore(t *testing.T, h *Host) (*durable.DurableProvider, *storage.MemChunkRemote) { +func runtimeLayoutHead(t *testing.T, fixture *testutil.LayoutFixture) layout.Head { t.Helper() - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1", ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, h.ProjectionView()) + head, found, err := fixture.Catalog.ReadHead(context.Background(), fixture.Ref) + if err != nil || !found { + t.Fatalf("layout HEAD: found=%v err=%v", found, err) + } + return head +} + +func runtimePublishedBlock(t *testing.T, fixture *testutil.LayoutFixture, block uint64) []byte { + t.Helper() + head := runtimeLayoutHead(t, fixture) + if head.Current == nil { + t.Fatal("published HEAD has no image") + } + st, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + t.Fatal(err) + } + reader, err := layout.NewReader("/provider-test", fixture.Ref.Dir(), st.Fetch) + if err != nil { + t.Fatal(err) + } + image, err := reader.Open(context.Background(), *head.Current) + if err != nil { + t.Fatal(err) + } + chunk, err := image.Chunk(context.Background(), block/8) + if err != nil { + t.Fatal(err) + } + if chunk.Zero { + return make([]byte, 4096) + } + off := (block % 8) * 4096 + return chunk.Data[off : off+4096] +} + +func runtimeStore(t *testing.T, h *Host) (*durable.DurableProvider, *testutil.LayoutFixture) { + t.Helper() + fixture := testutil.NewLayoutFixture(t, "v1", 64, 8) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1"} + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, h.ProjectionView()) if err != nil { t.Fatal(err) } @@ -153,7 +196,7 @@ func runtimeStore(t *testing.T, h *Host) (*durable.DurableProvider, *storage.Mem if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil { t.Fatal(err) } - return p, remote + return p, fixture } func runtimeDone(t *testing.T, ch <-chan error) error { t.Helper() @@ -175,7 +218,7 @@ func TestWorkspaceHostLeaseExpiryAndRevokeCloseRealProvider(t *testing.T) { // switches to 300 ms below. wire := &runtimeLeaseServer{ttl: 3 * time.Second, stopped: &stopped} h := workspaceRuntimeHost(t, runtimeWire(t, wire), true) - p, remote := runtimeStore(t, h) + p, fixture := runtimeStore(t, h) ctx, cancel := context.WithCancel(context.Background()) defer cancel() done := make(chan error, 1) @@ -188,7 +231,10 @@ func TestWorkspaceHostLeaseExpiryAndRevokeCloseRealProvider(t *testing.T) { return 0, err } stopped.Store(true) - head, err := remote.GetHead(c) + head, found, err := fixture.Catalog.ReadHead(c, fixture.Ref) + if err == nil && !found { + err = errors.New("HEAD absent") + } return head.Gen, err }) }() @@ -207,16 +253,16 @@ func TestWorkspaceHostLeaseExpiryAndRevokeCloseRealProvider(t *testing.T) { if _, err := p.CaptureVolume(ctx, "v1"); err != nil { t.Fatal(err) } - before, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } + before := runtimeLayoutHead(t, fixture) if kind == "detach-then-revoke" { cut, _, err := p.DetachVolume(ctx, "v1") if err != nil { t.Fatal(err) } - before = cut.Head + before = runtimeLayoutHead(t, fixture) + if before.Gen != cut.Head.Gen { + t.Fatal("detach result did not name HEAD generation", cut.Head.Gen, before.Gen) + } wire.mu.Lock() wire.revoking = true wire.mu.Unlock() @@ -273,20 +319,18 @@ func TestWorkspaceHostLeaseExpiryAndRevokeCloseRealProvider(t *testing.T) { if _, err := p.CaptureVolume(context.Background(), "v1"); err == nil { t.Fatal("fenced cut succeeded") } - after, err := remote.GetHead(context.Background()) - if err != nil || after.Gen != before.Gen || after.RemoteLSN != before.RemoteLSN { - t.Fatal("shutdown published an extra cut", before, after, err) + after := runtimeLayoutHead(t, fixture) + if after.Gen != before.Gen || after.Position != before.Position { + t.Fatal("shutdown published an extra cut", before, after) } - ref := after.Chunks[0] - data, err := remote.Get(context.Background(), ref.Key) - if err != nil || !bytes.Equal(data[4096:8192], want) { - t.Fatal("leased data changed", err) + if data := runtimePublishedBlock(t, fixture, 1); !bytes.Equal(data, want) { + t.Fatal("leased data changed") } wire.mu.Lock() acks, gen := wire.acks, wire.ackGen wire.mu.Unlock() if kind == "detach-then-revoke" { - if acks != 1 || gen != before.Gen || before.State != storage.ChunkHeadDetached { + if acks != 1 || gen != before.Gen || before.State != layout.StateDetached { t.Fatal("ACK not joined to real detach", acks, gen, before) } } else if acks != 0 { diff --git a/seaweed-block/core/launcher/k8s_renderer.go b/seaweed-block/core/launcher/k8s_renderer.go index 1853da991b..1e889df0b2 100644 --- a/seaweed-block/core/launcher/k8s_renderer.go +++ b/seaweed-block/core/launcher/k8s_renderer.go @@ -7,6 +7,7 @@ import ( "path" "strings" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/lifecycle" "gopkg.in/yaml.v3" ) @@ -245,6 +246,13 @@ func ownerReferences(plan lifecycle.BlockVolumeWorkloadPlan, cfg K8sRenderConfig } func blockVolumeArgs(plan lifecycle.BlockVolumeWorkloadPlan, replica lifecycle.BlockVolumeReplicaWorkload, cfg K8sRenderConfig) ([]string, error) { + rootArg := durableRoot(plan, replica, cfg) + if plan.LayoutID != "" { + if _, err := layout.ParseVolumeID(plan.LayoutID); err != nil { + return nil, err + } + rootArg = path.Join(cfg.DurableRootBase, replica.ReplicaID) + } args := []string{ "--master=" + cfg.MasterAddr, "--server-id=" + replica.ServerID, @@ -252,13 +260,16 @@ func blockVolumeArgs(plan lifecycle.BlockVolumeWorkloadPlan, replica lifecycle.B "--replica-id=" + replica.ReplicaID, "--data-addr=" + replica.DataAddr, "--ctrl-addr=" + replica.CtrlAddr, - "--durable-root=" + durableRoot(plan, replica, cfg), + "--durable-root=" + rootArg, "--durable-impl=" + cfg.DurableImpl, fmt.Sprintf("--durable-blocks=%d", plan.SizeBytes/4096), "--durable-blocksize=4096", "--recovery-mode=" + cfg.RecoveryMode, "--replication-ack=" + cfg.ReplicationAck, } + if plan.LayoutID != "" { + args = append(args, "--layout-id="+plan.LayoutID) + } if cfg.WALMultiBlockRecords { args = append(args, "--durable-wal-multiblock-records") } @@ -405,6 +416,10 @@ func blockVolumeInitContainers(plan lifecycle.BlockVolumeWorkloadPlan, replica l } func durableRoot(plan lifecycle.BlockVolumeWorkloadPlan, replica lifecycle.BlockVolumeReplicaWorkload, cfg K8sRenderConfig) string { + if plan.LayoutID != "" { + id, _ := layout.ParseVolumeID(plan.LayoutID) // blockVolumeArgs validates before rendering. + return path.Join(cfg.DurableRootBase, replica.ReplicaID, layout.VolumeDir(plan.VolumeID, id)) + } return path.Join(cfg.DurableRootBase, plan.VolumeID, replica.ReplicaID) } diff --git a/seaweed-block/core/launcher/layout_identity_test.go b/seaweed-block/core/launcher/layout_identity_test.go new file mode 100644 index 0000000000..798f9ed30a --- /dev/null +++ b/seaweed-block/core/launcher/layout_identity_test.go @@ -0,0 +1,26 @@ +package launcher + +import ( + "strings" + "testing" +) + +func TestLauncherCarriesTheMasterLayoutIdentity(t *testing.T) { + plan := sampleWorkloadPlan() + plan.LayoutID = "1234567890abcdef1234567890abcdef" + manifests, err := RenderBlockVolumeDeployments(plan, K8sRenderConfig{MasterAddr: "master:9333", DurableRootBase: "/data"}) + if err != nil { + t.Fatal(err) + } + raw := string(manifests[0].YAML) + if !strings.Contains(raw, "--layout-id="+plan.LayoutID) { + t.Fatal("master identity missing from launch args", raw) + } + if root := durableRoot(plan, plan.Replicas[0], K8sRenderConfig{DurableRootBase: "/data"}); root != "/data/r1/pvc-a-12345678" { + t.Fatal("local root is not keyed by layout identity", root) + } + plan.LayoutID = "bad" + if _, err := RenderBlockVolumeDeployments(plan, K8sRenderConfig{MasterAddr: "master:9333"}); err == nil { + t.Fatal("launcher accepted a malformed layout identity") + } +} diff --git a/seaweed-block/core/lifecycle/deletion_reservations.go b/seaweed-block/core/lifecycle/deletion_reservations.go index 86994e7a67..e1d750fc0a 100644 --- a/seaweed-block/core/lifecycle/deletion_reservations.go +++ b/seaweed-block/core/lifecycle/deletion_reservations.go @@ -145,6 +145,22 @@ func (s *DeletionReservationStore) CommittedSnapshot(vol string) bool { return ok && r.State == ReservationCommitted } +// CommittedVolumes returns the permanent exclusions for publisher recovery +// before the master serves its first request. +func (s *DeletionReservationStore) CommittedVolumes() []string { + m := s.snap.Load() + var volumes []string + if m != nil { + for volume, r := range *m { + if r.State == ReservationCommitted { + volumes = append(volumes, volume) + } + } + } + sort.Strings(volumes) + return volumes +} + // Get returns vol's reservation. func (s *DeletionReservationStore) Get(vol string) (DeletionReservation, bool) { s.mu.Lock() diff --git a/seaweed-block/core/lifecycle/geometry_test.go b/seaweed-block/core/lifecycle/geometry_test.go new file mode 100644 index 0000000000..71ca941c1c --- /dev/null +++ b/seaweed-block/core/lifecycle/geometry_test.go @@ -0,0 +1,52 @@ +package lifecycle + +import ( + "errors" + "testing" +) + +func TestCreateVolumePersistsV1GeometryAndRejectsChangedReplay(t *testing.T) { + s, err := OpenFileStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + spec := VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1} + first, err := s.CreateVolume(spec) + if err != nil { + t.Fatal(err) + } + if first.Spec.BlockSize != 4096 || first.Spec.ChunkBytes != 4<<20 { + t.Fatalf("default geometry not persisted: %+v", first.Spec) + } + if first.StoreReady { + t.Fatal("new record advertised store readiness before VOLUME and HEAD") + } + again, err := s.CreateVolume(spec) + if err != nil { + t.Fatal(err) + } + if again.Spec != first.Spec { + t.Fatalf("replay changed geometry: first=%+v replay=%+v", first.Spec, again.Spec) + } + ready, err := s.MarkStoreReady("v", first.Spec.LayoutID) + if err != nil || !ready.StoreReady { + t.Fatalf("mark ready: record=%+v err=%v", ready, err) + } + if _, err := s.MarkStoreReady("v", "00000000000000000000000000000000"); !errors.Is(err, ErrVolumeConflict) { + t.Fatalf("foreign layout id changed readiness: %v", err) + } + replayed, err := s.CreateVolume(spec) + if err != nil || !replayed.StoreReady { + t.Fatalf("ready replay: record=%+v err=%v", replayed, err) + } + changed := spec + changed.BlockSize = 8192 + if _, err := s.CreateVolume(changed); !errors.Is(err, ErrInvalidVolumeSpec) { + t.Fatalf("unsupported v1 geometry: %v", err) + } + changed.BlockSize = 4096 + changed.ChunkBytes = 1 << 20 + if _, err := s.CreateVolume(changed); !errors.Is(err, ErrInvalidVolumeSpec) { + t.Fatalf("unsupported v1 chunk size: %v", err) + } +} diff --git a/seaweed-block/core/lifecycle/layout_identity_guard_test.go b/seaweed-block/core/lifecycle/layout_identity_guard_test.go new file mode 100644 index 0000000000..ee341237f1 --- /dev/null +++ b/seaweed-block/core/lifecycle/layout_identity_guard_test.go @@ -0,0 +1,144 @@ +package lifecycle + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "strings" + "testing" +) + +func TestLayoutIdentityWriterAndReaders(t *testing.T) { + want := map[string]bool{ + "core/lifecycle/store.go CreateVolume": true, + "core/lifecycle/store.go volumeSpecsCompatible": true, + "core/lifecycle/store.go validateSpec": true, + "core/lifecycle/store.go MarkStoreReady": true, + "core/lifecycle/workload_plan.go PlanBlockVolumeWorkloads": true, + "core/host/master/services.go lifecycleVolumeResponse": true, + "core/host/master/services.go CreateVolume": true, + "core/host/master/services.go createLifecycleVolume": true, + "core/host/master/workspace_layout_head.go WorkspaceLayoutVolume": true, + "core/launcher/k8s_renderer.go blockVolumeArgs": true, + "core/launcher/k8s_renderer.go durableRoot": true, + "cmd/blockvolume/main.go runVolume": true, + "cmd/blockvolume/main.go parseFlags": true, + "cmd/blockmaster/layout_create.go layoutVolumeCreator": true, + "cmd/blockmaster/layout_create.go layoutVolumeReader": true, + "cmd/blockmaster/layout_create.go layoutHeadReader": true, + "cmd/blockmaster/layout_create.go layoutTargetCreator": true, + "cmd/sw-block/chunk_b.go chunkRestore": true, + "core/rpc/lifecycleclient/identity.go ResolveVolume": true, + } + seen := map[string]bool{} + root := filepath.Join("..", "..") + for _, top := range []string{"core", "cmd"} { + err := filepath.WalkDir(filepath.Join(root, top), func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return err + } + rel, _ := filepath.Rel(root, p) + // durable/testutil contains fixture identities, not product identity sites. + if strings.HasPrefix(filepath.ToSlash(rel), "core/frontend/durable/testutil/") { + return nil + } + f, err := parser.ParseFile(token.NewFileSet(), p, nil, 0) + if err != nil { + return err + } + for _, decl := range f.Decls { + name := "" + if fn, ok := decl.(*ast.FuncDecl); ok { + name = fn.Name.Name + } + site := filepath.ToSlash(rel) + " " + name + ast.Inspect(decl, func(n ast.Node) bool { + if kv, ok := n.(*ast.KeyValueExpr); ok { + if key, ok := kv.Key.(*ast.Ident); ok && key.Name == "LayoutID" && !want[site] { + t.Errorf("layout identity literal writer needs a probe: %s", site) + } + } + if call, ok := n.(*ast.CallExpr); ok { + if fn, ok := call.Fun.(*ast.Ident); ok && fn.Name == "NewVolumeID" { + t.Errorf("unclassified local identity mint: %s", site) + } + } + if s, ok := n.(*ast.SelectorExpr); ok { + if s.Sel.Name == "LayoutID" || s.Sel.Name == "layoutID" || s.Sel.Name == "GetLayoutId" { + seen[site] = true + if !want[site] { + t.Errorf("layout identity reader/writer needs a probe: %s", site) + } + } + if s.Sel.Name == "NewVolumeID" && site != "core/lifecycle/store.go CreateVolume" { + t.Errorf("layout identity minted outside lifecycle create: %s", site) + } + } + return true + }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + for site := range want { + if !seen[site] { + t.Errorf("missing identity probe site %s", site) + } + } +} + +// A restore's source identity is persisted once and compared on every retry. +// Adding a new reader or writer requires a binding probe at that site. +func TestRestoreSourceIdentitySites(t *testing.T) { + want := map[string]bool{ + "core/lifecycle/store.go CreateVolume": true, + "core/lifecycle/store.go volumeSpecsCompatible": true, + "core/lifecycle/store.go validateSpec": true, + "core/host/master/services.go CreateVolume": true, + "core/host/master/services.go createLifecycleVolume": true, + } + seen := map[string]bool{} + root := filepath.Join("..", "..") + for _, top := range []string{"core", "cmd"} { + err := filepath.WalkDir(filepath.Join(root, top), func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return err + } + f, err := parser.ParseFile(token.NewFileSet(), p, nil, 0) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, p) + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok { + continue + } + site := filepath.ToSlash(rel) + " " + fn.Name.Name + ast.Inspect(decl, func(n ast.Node) bool { + if s, ok := n.(*ast.SelectorExpr); ok && s.Sel.Name == "SourceLayoutID" { + seen[site] = true + if !want[site] { + t.Errorf("new source identity site needs a probe: %s", site) + } + } + return true + }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + for site := range want { + if !seen[site] { + t.Errorf("missing source identity site %s", site) + } + } +} diff --git a/seaweed-block/core/lifecycle/layout_identity_test.go b/seaweed-block/core/lifecycle/layout_identity_test.go new file mode 100644 index 0000000000..da9a6fb8e5 --- /dev/null +++ b/seaweed-block/core/lifecycle/layout_identity_test.go @@ -0,0 +1,133 @@ +package lifecycle + +import ( + "encoding/json" + "errors" + "os" + "os/exec" + "runtime" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +func TestLifecycleLayoutIdentity(t *testing.T) { + // Isolate the persistence seams. Windows cannot sync a directory handle; + // its child exercises record identity, not filesystem crash durability. + if os.Getenv("SWB_LAYOUT_ID_CHILD") != "1" { + cmd := exec.Command(os.Args[0], "-test.run=^TestLifecycleLayoutIdentity$", "-test.v") + cmd.Env = append(os.Environ(), "SWB_LAYOUT_ID_CHILD=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("identity child: %v\n%s", err, out) + } + return + } + hooks := &durableRecordHooks{} + if runtime.GOOS == "windows" { + hooks.dirSync = func(string) error { return nil } + } + durableRecordHooksForTest.Store(hooks) + defer durableRecordHooksForTest.Store(nil) + dir := t.TempDir() + s, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + spec := VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1} + a, err := s.CreateVolume(spec) + if err != nil { + t.Fatal(err) + } + if _, err := layout.ParseVolumeID(a.Spec.LayoutID); err != nil { + t.Fatal("create did not mint a layout id", err) + } + b, err := s.CreateVolume(spec) + if err != nil || a.Spec.LayoutID != b.Spec.LayoutID { + t.Fatalf("retry changed identity: %v %+v", err, b) + } + metadata := spec + metadata.PVCName = "claim" + if rec, err := s.CreateVolume(metadata); err != nil || rec.Spec.LayoutID != a.Spec.LayoutID { + t.Fatalf("metadata changed identity: %v", err) + } + if rec, err := s.AttachVolume("v", "node"); err != nil || rec.Spec.LayoutID != a.Spec.LayoutID { + t.Fatalf("attach changed identity: %v", err) + } + if rec, err := s.DetachVolume("v", "node"); err != nil || rec.Spec.LayoutID != a.Spec.LayoutID { + t.Fatalf("detach changed identity: %v", err) + } + concurrent := spec + concurrent.VolumeID = "concurrent" + type result struct { + rec VolumeRecord + err error + } + results := make(chan result, 16) + for i := 0; i < 16; i++ { + go func() { rec, err := s.CreateVolume(concurrent); results <- result{rec, err} }() + } + var minted string + for i := 0; i < 16; i++ { + r := <-results + if r.err != nil { + t.Fatal(r.err) + } + if minted == "" { + minted = r.rec.Spec.LayoutID + } + if minted != r.rec.Spec.LayoutID { + t.Fatal("concurrent creates minted multiple identities") + } + } + loaded, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + b, err = loaded.CreateVolume(spec) + if err != nil || a.Spec.LayoutID != b.Spec.LayoutID { + t.Fatalf("restart changed identity: %v %+v", err, b) + } + other, _ := layout.NewVolumeID() + bad := spec + bad.LayoutID = other.String() + if _, err := loaded.CreateVolume(bad); !errors.Is(err, ErrVolumeConflict) { + t.Fatalf("replacement id accepted: %v", err) + } + if err := loaded.DeleteVolume("v"); err != nil { + t.Fatal(err) + } + b, err = loaded.CreateVolume(spec) + if err != nil || a.Spec.LayoutID == b.Spec.LayoutID { + t.Fatalf("recreate reused identity: %v %+v", err, b) + } + // A failed directory sync may have left the complete first record on disk. + // Its retry must settle that same identity, without publishing on failure. + failed := true + hooks.dirSync = func(string) error { + if failed { + return errors.New("sync failed") + } + return nil + } + failedSpec := spec + failedSpec.VolumeID = "uncertain" + if _, err := loaded.CreateVolume(failedSpec); err == nil { + t.Fatal("sync failure hidden") + } + if _, ok := loaded.GetVolume("uncertain"); ok { + t.Fatal("failed put published memory") + } + raw, err := os.ReadFile(loaded.path("uncertain")) + if err != nil { + t.Fatal(err) + } + var written VolumeRecord + if err := json.Unmarshal(raw, &written); err != nil { + t.Fatal(err) + } + failed = false + b, err = loaded.CreateVolume(failedSpec) + if err != nil || b.Spec.LayoutID != written.Spec.LayoutID { + t.Fatalf("unknown put retry changed identity: %v %+v", err, b) + } +} diff --git a/seaweed-block/core/lifecycle/restore_request_test.go b/seaweed-block/core/lifecycle/restore_request_test.go new file mode 100644 index 0000000000..ec78c114bc --- /dev/null +++ b/seaweed-block/core/lifecycle/restore_request_test.go @@ -0,0 +1,56 @@ +package lifecycle + +import ( + "errors" + "strings" + "testing" +) + +// A restore retry keeps the original source, snapshot and request identity. +// A target name cannot be rebound to a different image after an uncertain RPC. +func TestRestoreRequestBindsTargetName(t *testing.T) { + dir := t.TempDir() + s, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + spec := VolumeSpec{VolumeID: "target", SizeBytes: 1 << 20, ReplicationFactor: 1, + SourceVolume: "source", SourceLayoutID: "11111111111111111111111111111111", SourceSnapshot: "daily", CreateRequestID: "restore-1"} + first, err := s.CreateVolume(spec) + if err != nil { + t.Fatal(err) + } + s, err = OpenFileStore(dir) // restart between the record and filer writes + if err != nil { + t.Fatal(err) + } + if record, ok := s.GetVolume(spec.VolumeID); !ok || record.StoreReady || record.Spec.SourceVolume != spec.SourceVolume || record.Spec.SourceSnapshot != spec.SourceSnapshot || record.Spec.CreateRequestID != spec.CreateRequestID { + t.Fatalf("restart lost the pending restore request: %+v found=%t", record, ok) + } + again, err := s.CreateVolume(spec) + if err != nil || again.Spec.LayoutID != first.Spec.LayoutID { + t.Fatalf("same request replay: %+v %v", again, err) + } + for _, mutation := range []func(*VolumeSpec){ + func(v *VolumeSpec) { v.SourceVolume = "another" }, + func(v *VolumeSpec) { v.SourceLayoutID = "22222222222222222222222222222222" }, + func(v *VolumeSpec) { v.SourceSnapshot = "weekly" }, + func(v *VolumeSpec) { v.CreateRequestID = "restore-2" }, + func(v *VolumeSpec) { v.SourceVolume, v.SourceSnapshot, v.CreateRequestID = "", "", "" }, + } { + changed := spec + mutation(&changed) + if _, err := s.CreateVolume(changed); !errors.Is(err, ErrVolumeConflict) { + t.Fatalf("rebound target %+v: %v; want conflict", changed, err) + } + } + bad := spec + bad.VolumeID = "new-target" + bad.SourceSnapshot = strings.Repeat("x", 65) + if _, err := s.CreateVolume(bad); !errors.Is(err, ErrInvalidVolumeSpec) { + t.Fatalf("invalid source snapshot was persisted: %v", err) + } + if _, ok := s.GetVolume(bad.VolumeID); ok { + t.Fatal("invalid restore created a target record") + } +} diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 01f297c9d4..01e9fa3156 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -18,6 +18,7 @@ import ( "sync" "sync/atomic" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/geometry" ) @@ -34,8 +35,17 @@ var volumeIDPattern = regexp.MustCompile(`^[A-Za-z0-9._-]+$`) // VolumeSpec is the product-level desired volume shape. It carries no // authority lineage and no placement decision. type VolumeSpec struct { - VolumeID string `json:"volume_id"` - SizeBytes uint64 `json:"size_bytes"` + VolumeID string `json:"volume_id"` + LayoutID string `json:"layout_id,omitempty"` + SizeBytes uint64 `json:"size_bytes"` + BlockSize uint32 `json:"block_size"` + ChunkBytes uint64 `json:"chunk_bytes"` + // A restore request is bound to one source snapshot before the target's + // layout is created. These fields never change on a replay. + SourceVolume string `json:"source_volume,omitempty"` + SourceLayoutID string `json:"source_layout_id,omitempty"` + SourceSnapshot string `json:"source_snapshot,omitempty"` + CreateRequestID string `json:"create_request_id,omitempty"` ReplicationFactor int `json:"replication_factor"` Protocol string `json:"protocol,omitempty"` FrontendTransport string `json:"frontend_transport,omitempty"` @@ -49,6 +59,10 @@ type VolumeSpec struct { type VolumeRecord struct { Spec VolumeSpec `json:"spec"` AttachedTo string `json:"attached_to,omitempty"` + // StoreReady is a one-way placement hint, set only after the matching + // VOLUME and unclaimed HEAD have been created in the filer. Start still + // checks those records independently before serving. + StoreReady bool `json:"store_ready,omitempty"` } // FileStore persists one JSON record per volume ID. @@ -121,12 +135,15 @@ func OpenFileStore(dir string) (*FileStore, error) { // idempotent; changing a previously-created spec is rejected. func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { spec = normalizeVolumeSpec(spec) - if err := validateSpec(spec); err != nil { - return VolumeRecord{}, err - } s.mu.Lock() defer s.mu.Unlock() if existing, ok := s.records[spec.VolumeID]; ok { + if existing.Spec.SourceVolume != spec.SourceVolume || existing.Spec.SourceLayoutID != spec.SourceLayoutID || existing.Spec.SourceSnapshot != spec.SourceSnapshot || existing.Spec.CreateRequestID != spec.CreateRequestID { + return VolumeRecord{}, ErrVolumeConflict + } + if err := validateSpec(spec); err != nil { + return VolumeRecord{}, err + } if !volumeSpecsCompatible(existing.Spec, spec) { return VolumeRecord{}, ErrVolumeConflict } @@ -145,6 +162,40 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { if err := geometry.ValidateVolumeSize(spec.SizeBytes); err != nil { return VolumeRecord{}, fmt.Errorf("%w: %w", ErrInvalidVolumeSpec, err) } + if err := validateSpec(spec); err != nil { + return VolumeRecord{}, err + } + // A previous create may have renamed its complete record but lost the + // directory-sync result. Settle that identity instead of minting another. + if raw, err := os.ReadFile(s.path(spec.VolumeID)); err == nil { + var rec VolumeRecord + if err := json.Unmarshal(raw, &rec); err != nil { + return VolumeRecord{}, err + } + if !volumeSpecsCompatible(rec.Spec, spec) { + return VolumeRecord{}, ErrVolumeConflict + } + if _, err := layout.ParseVolumeID(rec.Spec.LayoutID); err != nil { + return VolumeRecord{}, fmt.Errorf("%w: existing layout identity: %v; recreate", ErrInvalidVolumeSpec, err) + } + rec.Spec = mergeVolumeSpecMetadata(rec.Spec, spec) + if err := s.putLocked(rec); err != nil { + return VolumeRecord{}, err + } + s.records[spec.VolumeID] = rec + s.publishLocked() + return rec, nil + } else if !errors.Is(err, os.ErrNotExist) { + return VolumeRecord{}, err + } + if spec.LayoutID != "" { + return VolumeRecord{}, fmt.Errorf("%w: layout_id is minted by the master", ErrInvalidVolumeSpec) + } + id, err := layout.NewVolumeID() + if err != nil { + return VolumeRecord{}, err + } + spec.LayoutID = id.String() rec := VolumeRecord{Spec: spec} if err := s.putLocked(rec); err != nil { return VolumeRecord{}, err @@ -154,11 +205,43 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { return rec, nil } +// MarkStoreReady publishes the durable placement hint after the filer has +// accepted both exclusive creates. A retry of the same create may repeat it; +// another layout identity may not mark this record ready. +func (s *FileStore) MarkStoreReady(volumeID, layoutID string) (VolumeRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + rec, ok := s.records[volumeID] + if !ok { + return VolumeRecord{}, ErrVolumeNotFound + } + if rec.Spec.LayoutID != layoutID { + return VolumeRecord{}, ErrVolumeConflict + } + if rec.StoreReady { + return rec, nil + } + rec.StoreReady = true + if err := s.putLocked(rec); err != nil { + return VolumeRecord{}, err + } + s.records[volumeID] = rec + s.publishLocked() + return rec, nil +} + func volumeSpecsCompatible(a, b VolumeSpec) bool { a = normalizeVolumeSpec(a) b = normalizeVolumeSpec(b) return a.VolumeID == b.VolumeID && + (b.LayoutID == "" || a.LayoutID == b.LayoutID) && a.SizeBytes == b.SizeBytes && + a.BlockSize == b.BlockSize && + a.ChunkBytes == b.ChunkBytes && + a.SourceVolume == b.SourceVolume && + a.SourceLayoutID == b.SourceLayoutID && + a.SourceSnapshot == b.SourceSnapshot && + a.CreateRequestID == b.CreateRequestID && a.ReplicationFactor == b.ReplicationFactor && a.Protocol == b.Protocol && a.FrontendTransport == b.FrontendTransport @@ -319,9 +402,34 @@ func validateSpec(spec VolumeSpec) error { if err := validateVolumeID(spec.VolumeID); err != nil { return err } + if spec.SourceVolume != "" || spec.SourceLayoutID != "" || spec.SourceSnapshot != "" || spec.CreateRequestID != "" { + if err := validateVolumeID(spec.SourceVolume); err != nil || spec.SourceSnapshot == "" || spec.CreateRequestID == "" || spec.SourceVolume == spec.VolumeID { + return fmt.Errorf("%w: restore needs a distinct source volume, snapshot and request id", ErrInvalidVolumeSpec) + } + if _, err := layout.ParseVolumeID(spec.SourceLayoutID); err != nil { + return fmt.Errorf("%w: restore needs the source layout id: %v", ErrInvalidVolumeSpec, err) + } + if err := layout.CheckSnapshot(spec.SourceSnapshot, layout.SnapshotMeta{}); err != nil { + return fmt.Errorf("%w: restore snapshot: %v", ErrInvalidVolumeSpec, err) + } + if len(spec.CreateRequestID) > 128 { + return fmt.Errorf("%w: restore request id is over 128 bytes", ErrInvalidVolumeSpec) + } + } + if spec.LayoutID != "" { + if _, err := layout.ParseVolumeID(spec.LayoutID); err != nil { + return fmt.Errorf("%w: layout_id: %v", ErrInvalidVolumeSpec, err) + } + } if spec.SizeBytes == 0 { return fmt.Errorf("%w: size_bytes must be > 0", ErrInvalidVolumeSpec) } + if err := (layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes}).Check(); err != nil { + return fmt.Errorf("%w: geometry: %v", ErrInvalidVolumeSpec, err) + } + if spec.BlockSize != 4096 || spec.ChunkBytes != 4<<20 { + return fmt.Errorf("%w: v1 accepts only block_size=4096 and chunk_bytes=4194304", ErrInvalidVolumeSpec) + } if spec.ReplicationFactor <= 0 { return fmt.Errorf("%w: replication_factor must be > 0", ErrInvalidVolumeSpec) } @@ -341,6 +449,12 @@ func validateSpec(spec VolumeSpec) error { } func normalizeVolumeSpec(spec VolumeSpec) VolumeSpec { + if spec.BlockSize == 0 { + spec.BlockSize = 4096 + } + if spec.ChunkBytes == 0 { + spec.ChunkBytes = 4 << 20 + } if spec.Protocol == "" { spec.Protocol = "iscsi" } diff --git a/seaweed-block/core/lifecycle/store_crash_test.go b/seaweed-block/core/lifecycle/store_crash_test.go index c28e073981..0c9e1e89d1 100644 --- a/seaweed-block/core/lifecycle/store_crash_test.go +++ b/seaweed-block/core/lifecycle/store_crash_test.go @@ -26,6 +26,23 @@ type recordCrashFixture struct { get func() (any, bool) } +func (f *recordCrashFixture) captureLayoutIdentity(t *testing.T) { + old, volume := f.old.(VolumeRecord) + if !volume { + return + } + got, ok := f.get() + if !ok || got.(VolumeRecord).Spec.LayoutID == "" { + t.Fatal("fixture did not persist its layout identity") + } + old.Spec.LayoutID = got.(VolumeRecord).Spec.LayoutID + old.Spec.BlockSize, old.Spec.ChunkBytes = 4096, 4<<20 + next := f.next.(VolumeRecord) + next.Spec.LayoutID = old.Spec.LayoutID + next.Spec.BlockSize, next.Spec.ChunkBytes = old.Spec.BlockSize, old.Spec.ChunkBytes + f.old, f.next = old, next +} + func openRecordCrashFixture(t *testing.T, kind, dir string, hook func(string)) recordCrashFixture { t.Helper() durableRecordHooksForTest.Store(nil) @@ -113,6 +130,7 @@ func checkStoreCrash(t *testing.T, kind string) { if err := f.put(false); err != nil { t.Fatal(err) } + f.captureLayoutIdentity(t) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestRecordStoreCrashChild$", "-test.timeout=8s") @@ -197,6 +215,7 @@ func TestLifecyclePutSyncChild(t *testing.T) { if err := f.put(false); err != nil { t.Fatal(err) } + f.captureLayoutIdentity(t) fault := errors.New("injected sync failure") var events []string if failure != "nil-hooks" { diff --git a/seaweed-block/core/lifecycle/store_test.go b/seaweed-block/core/lifecycle/store_test.go index 2e4cfef4b1..31f63d4c88 100644 --- a/seaweed-block/core/lifecycle/store_test.go +++ b/seaweed-block/core/lifecycle/store_test.go @@ -30,6 +30,11 @@ func TestFileStore_CreateVolumePersistsAndIsIdempotent(t *testing.T) { if err != nil { t.Fatalf("create: %v", err) } + if rec.Spec.LayoutID == "" { + t.Fatal("missing minted layout identity") + } + spec.LayoutID = rec.Spec.LayoutID + spec.BlockSize, spec.ChunkBytes = 4096, 4<<20 if rec.Spec != spec { t.Fatalf("record spec=%+v want %+v", rec.Spec, spec) } diff --git a/seaweed-block/core/lifecycle/workload_plan.go b/seaweed-block/core/lifecycle/workload_plan.go index 60758e14fc..37cadc4201 100644 --- a/seaweed-block/core/lifecycle/workload_plan.go +++ b/seaweed-block/core/lifecycle/workload_plan.go @@ -10,6 +10,7 @@ import ( // authority-shaped: no epoch, endpoint_version, primary, ready, or healthy. type BlockVolumeWorkloadPlan struct { VolumeID string + LayoutID string SizeBytes uint64 Protocol string NVMeTransport string @@ -72,6 +73,7 @@ func PlanBlockVolumeWorkloads(volume VolumeRecord, placement PlacementIntent, no out := BlockVolumeWorkloadPlan{ VolumeID: volume.Spec.VolumeID, + LayoutID: volume.Spec.LayoutID, SizeBytes: volume.Spec.SizeBytes, Protocol: protocol, NVMeTransport: volume.Spec.FrontendTransport, diff --git a/seaweed-block/core/lifecycle/workload_plan_test.go b/seaweed-block/core/lifecycle/workload_plan_test.go index dcc14b23c9..54e1056a3d 100644 --- a/seaweed-block/core/lifecycle/workload_plan_test.go +++ b/seaweed-block/core/lifecycle/workload_plan_test.go @@ -5,6 +5,7 @@ import "testing" func TestG15d_WorkloadPlan_BlankPoolRF2CreatesReplicaWorkloads(t *testing.T) { volume := VolumeRecord{Spec: VolumeSpec{ VolumeID: "pvc-a", + LayoutID: "1234567890abcdef1234567890abcdef", SizeBytes: 1 << 20, ReplicationFactor: 2, PVCName: "demo-pvc", @@ -35,6 +36,9 @@ func TestG15d_WorkloadPlan_BlankPoolRF2CreatesReplicaWorkloads(t *testing.T) { if plan.PVCName != "demo-pvc" || plan.PVCNamespace != "default" || plan.PVCUID != "uid-123" { t.Fatalf("pvc metadata=%+v", plan) } + if plan.LayoutID != "1234567890abcdef1234567890abcdef" { + t.Fatal("workload lost master layout identity") + } if plan.Replicas[0].ReplicaID != "r1" || plan.Replicas[1].ReplicaID != "r2" { t.Fatalf("replica ids=%q/%q want r1/r2", plan.Replicas[0].ReplicaID, plan.Replicas[1].ReplicaID) } diff --git a/seaweed-block/core/rpc/control/control.pb.go b/seaweed-block/core/rpc/control/control.pb.go index 007a8d755d..f905991b7e 100644 --- a/seaweed-block/core/rpc/control/control.pb.go +++ b/seaweed-block/core/rpc/control/control.pb.go @@ -2585,6 +2585,11 @@ type CreateVolumeRequest struct { PvcUid string `protobuf:"bytes,7,opt,name=pvc_uid,json=pvcUid,proto3" json:"pvc_uid,omitempty"` Protocol string `protobuf:"bytes,8,opt,name=protocol,proto3" json:"protocol,omitempty"` // "iscsi" default | "nvme" FrontendTransport string `protobuf:"bytes,9,opt,name=frontend_transport,json=frontendTransport,proto3" json:"frontend_transport,omitempty"` // NVMe: "tcp" default | "rdma" + BlockSize uint32 `protobuf:"varint,10,opt,name=block_size,json=blockSize,proto3" json:"block_size,omitempty"` // omitted: 4096, persisted on first create + ChunkBytes uint64 `protobuf:"varint,11,opt,name=chunk_bytes,json=chunkBytes,proto3" json:"chunk_bytes,omitempty"` // omitted: 4 MiB, persisted on first create + SourceVolume string `protobuf:"bytes,12,opt,name=source_volume,json=sourceVolume,proto3" json:"source_volume,omitempty"` // restore only: source lifecycle name + SourceSnapshot string `protobuf:"bytes,13,opt,name=source_snapshot,json=sourceSnapshot,proto3" json:"source_snapshot,omitempty"` // restore only: named source snapshot + CreateRequestId string `protobuf:"bytes,14,opt,name=create_request_id,json=createRequestId,proto3" json:"create_request_id,omitempty"` // restore retry identity, bound to name/source/snapshot } func (x *CreateVolumeRequest) Reset() { @@ -2682,6 +2687,41 @@ func (x *CreateVolumeRequest) GetFrontendTransport() string { return "" } +func (x *CreateVolumeRequest) GetBlockSize() uint32 { + if x != nil { + return x.BlockSize + } + return 0 +} + +func (x *CreateVolumeRequest) GetChunkBytes() uint64 { + if x != nil { + return x.ChunkBytes + } + return 0 +} + +func (x *CreateVolumeRequest) GetSourceVolume() string { + if x != nil { + return x.SourceVolume + } + return "" +} + +func (x *CreateVolumeRequest) GetSourceSnapshot() string { + if x != nil { + return x.SourceSnapshot + } + return "" +} + +func (x *CreateVolumeRequest) GetCreateRequestId() string { + if x != nil { + return x.CreateRequestId + } + return "" +} + type CreateVolumeResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2696,6 +2736,10 @@ type CreateVolumeResponse struct { PvcUid string `protobuf:"bytes,7,opt,name=pvc_uid,json=pvcUid,proto3" json:"pvc_uid,omitempty"` Protocol string `protobuf:"bytes,8,opt,name=protocol,proto3" json:"protocol,omitempty"` // "iscsi" default | "nvme" FrontendTransport string `protobuf:"bytes,9,opt,name=frontend_transport,json=frontendTransport,proto3" json:"frontend_transport,omitempty"` // NVMe: "tcp" default | "rdma" + LayoutId string `protobuf:"bytes,10,opt,name=layout_id,json=layoutId,proto3" json:"layout_id,omitempty"` // master-minted, immutable 32 lower-case hex digits + BlockSize uint32 `protobuf:"varint,11,opt,name=block_size,json=blockSize,proto3" json:"block_size,omitempty"` + ChunkBytes uint64 `protobuf:"varint,12,opt,name=chunk_bytes,json=chunkBytes,proto3" json:"chunk_bytes,omitempty"` + StoreReady bool `protobuf:"varint,13,opt,name=store_ready,json=storeReady,proto3" json:"store_ready,omitempty"` // false: created, store not ready; retry CreateVolume } func (x *CreateVolumeResponse) Reset() { @@ -2793,6 +2837,81 @@ func (x *CreateVolumeResponse) GetFrontendTransport() string { return "" } +func (x *CreateVolumeResponse) GetLayoutId() string { + if x != nil { + return x.LayoutId + } + return "" +} + +func (x *CreateVolumeResponse) GetBlockSize() uint32 { + if x != nil { + return x.BlockSize + } + return 0 +} + +func (x *CreateVolumeResponse) GetChunkBytes() uint64 { + if x != nil { + return x.ChunkBytes + } + return 0 +} + +func (x *CreateVolumeResponse) GetStoreReady() bool { + if x != nil { + return x.StoreReady + } + return false +} + +type GetLifecycleVolumeRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` // lifecycle name +} + +func (x *GetLifecycleVolumeRequest) Reset() { + *x = GetLifecycleVolumeRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_control_proto_msgTypes[28] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetLifecycleVolumeRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetLifecycleVolumeRequest) ProtoMessage() {} + +func (x *GetLifecycleVolumeRequest) ProtoReflect() protoreflect.Message { + mi := &file_control_proto_msgTypes[28] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetLifecycleVolumeRequest.ProtoReflect.Descriptor instead. +func (*GetLifecycleVolumeRequest) Descriptor() ([]byte, []int) { + return file_control_proto_rawDescGZIP(), []int{28} +} + +func (x *GetLifecycleVolumeRequest) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + type DeleteVolumeRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2804,7 +2923,7 @@ type DeleteVolumeRequest struct { func (x *DeleteVolumeRequest) Reset() { *x = DeleteVolumeRequest{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[28] + mi := &file_control_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2817,7 +2936,7 @@ func (x *DeleteVolumeRequest) String() string { func (*DeleteVolumeRequest) ProtoMessage() {} func (x *DeleteVolumeRequest) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[28] + mi := &file_control_proto_msgTypes[29] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2830,7 +2949,7 @@ func (x *DeleteVolumeRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteVolumeRequest.ProtoReflect.Descriptor instead. func (*DeleteVolumeRequest) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{28} + return file_control_proto_rawDescGZIP(), []int{29} } func (x *DeleteVolumeRequest) GetVolumeId() string { @@ -2849,7 +2968,7 @@ type DeleteVolumeResponse struct { func (x *DeleteVolumeResponse) Reset() { *x = DeleteVolumeResponse{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[29] + mi := &file_control_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2862,7 +2981,7 @@ func (x *DeleteVolumeResponse) String() string { func (*DeleteVolumeResponse) ProtoMessage() {} func (x *DeleteVolumeResponse) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[29] + mi := &file_control_proto_msgTypes[30] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2875,7 +2994,7 @@ func (x *DeleteVolumeResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteVolumeResponse.ProtoReflect.Descriptor instead. func (*DeleteVolumeResponse) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{29} + return file_control_proto_rawDescGZIP(), []int{30} } type MarkVolumeDeletingRequest struct { @@ -2891,7 +3010,7 @@ type MarkVolumeDeletingRequest struct { func (x *MarkVolumeDeletingRequest) Reset() { *x = MarkVolumeDeletingRequest{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[30] + mi := &file_control_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2904,7 +3023,7 @@ func (x *MarkVolumeDeletingRequest) String() string { func (*MarkVolumeDeletingRequest) ProtoMessage() {} func (x *MarkVolumeDeletingRequest) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[30] + mi := &file_control_proto_msgTypes[31] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2917,7 +3036,7 @@ func (x *MarkVolumeDeletingRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use MarkVolumeDeletingRequest.ProtoReflect.Descriptor instead. func (*MarkVolumeDeletingRequest) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{30} + return file_control_proto_rawDescGZIP(), []int{31} } func (x *MarkVolumeDeletingRequest) GetVolumeId() string { @@ -2950,7 +3069,7 @@ type MarkVolumeDeletingResponse struct { func (x *MarkVolumeDeletingResponse) Reset() { *x = MarkVolumeDeletingResponse{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[31] + mi := &file_control_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2963,7 +3082,7 @@ func (x *MarkVolumeDeletingResponse) String() string { func (*MarkVolumeDeletingResponse) ProtoMessage() {} func (x *MarkVolumeDeletingResponse) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[31] + mi := &file_control_proto_msgTypes[32] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2976,7 +3095,7 @@ func (x *MarkVolumeDeletingResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use MarkVolumeDeletingResponse.ProtoReflect.Descriptor instead. func (*MarkVolumeDeletingResponse) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{31} + return file_control_proto_rawDescGZIP(), []int{32} } func (x *MarkVolumeDeletingResponse) GetKnown() bool { @@ -3014,7 +3133,7 @@ type FailbackRequest struct { func (x *FailbackRequest) Reset() { *x = FailbackRequest{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[32] + mi := &file_control_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3027,7 +3146,7 @@ func (x *FailbackRequest) String() string { func (*FailbackRequest) ProtoMessage() {} func (x *FailbackRequest) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[32] + mi := &file_control_proto_msgTypes[33] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3040,7 +3159,7 @@ func (x *FailbackRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use FailbackRequest.ProtoReflect.Descriptor instead. func (*FailbackRequest) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{32} + return file_control_proto_rawDescGZIP(), []int{33} } func (x *FailbackRequest) GetVolumeId() string { @@ -3137,7 +3256,7 @@ type FailbackResponse struct { func (x *FailbackResponse) Reset() { *x = FailbackResponse{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[33] + mi := &file_control_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3150,7 +3269,7 @@ func (x *FailbackResponse) String() string { func (*FailbackResponse) ProtoMessage() {} func (x *FailbackResponse) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[33] + mi := &file_control_proto_msgTypes[34] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3163,7 +3282,7 @@ func (x *FailbackResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use FailbackResponse.ProtoReflect.Descriptor instead. func (*FailbackResponse) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{33} + return file_control_proto_rawDescGZIP(), []int{34} } func (x *FailbackResponse) GetFailbackStarted() bool { @@ -3227,7 +3346,7 @@ type ProbeRoundSubscription struct { func (x *ProbeRoundSubscription) Reset() { *x = ProbeRoundSubscription{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[34] + mi := &file_control_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3240,7 +3359,7 @@ func (x *ProbeRoundSubscription) String() string { func (*ProbeRoundSubscription) ProtoMessage() {} func (x *ProbeRoundSubscription) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[34] + mi := &file_control_proto_msgTypes[35] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3253,7 +3372,7 @@ func (x *ProbeRoundSubscription) ProtoReflect() protoreflect.Message { // Deprecated: Use ProbeRoundSubscription.ProtoReflect.Descriptor instead. func (*ProbeRoundSubscription) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{34} + return file_control_proto_rawDescGZIP(), []int{35} } func (x *ProbeRoundSubscription) GetServerId() string { @@ -3285,7 +3404,7 @@ type ProbeRound struct { func (x *ProbeRound) Reset() { *x = ProbeRound{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[35] + mi := &file_control_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3298,7 +3417,7 @@ func (x *ProbeRound) String() string { func (*ProbeRound) ProtoMessage() {} func (x *ProbeRound) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[35] + mi := &file_control_proto_msgTypes[36] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3311,7 +3430,7 @@ func (x *ProbeRound) ProtoReflect() protoreflect.Message { // Deprecated: Use ProbeRound.ProtoReflect.Descriptor instead. func (*ProbeRound) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{35} + return file_control_proto_rawDescGZIP(), []int{36} } func (x *ProbeRound) GetVolumeId() string { @@ -3379,7 +3498,7 @@ type ProbeAnswer struct { func (x *ProbeAnswer) Reset() { *x = ProbeAnswer{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[36] + mi := &file_control_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3392,7 +3511,7 @@ func (x *ProbeAnswer) String() string { func (*ProbeAnswer) ProtoMessage() {} func (x *ProbeAnswer) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[36] + mi := &file_control_proto_msgTypes[37] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3405,7 +3524,7 @@ func (x *ProbeAnswer) ProtoReflect() protoreflect.Message { // Deprecated: Use ProbeAnswer.ProtoReflect.Descriptor instead. func (*ProbeAnswer) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{36} + return file_control_proto_rawDescGZIP(), []int{37} } func (x *ProbeAnswer) GetServerId() string { @@ -3508,7 +3627,7 @@ type ProbeAck struct { func (x *ProbeAck) Reset() { *x = ProbeAck{} if protoimpl.UnsafeEnabled { - mi := &file_control_proto_msgTypes[37] + mi := &file_control_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3521,7 +3640,7 @@ func (x *ProbeAck) String() string { func (*ProbeAck) ProtoMessage() {} func (x *ProbeAck) ProtoReflect() protoreflect.Message { - mi := &file_control_proto_msgTypes[37] + mi := &file_control_proto_msgTypes[38] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3534,7 +3653,7 @@ func (x *ProbeAck) ProtoReflect() protoreflect.Message { // Deprecated: Use ProbeAck.ProtoReflect.Descriptor instead. func (*ProbeAck) Descriptor() ([]byte, []int) { - return file_control_proto_rawDescGZIP(), []int{37} + return file_control_proto_rawDescGZIP(), []int{38} } var File_control_proto protoreflect.FileDescriptor @@ -3997,7 +4116,7 @@ var file_control_proto_rawDesc = []byte{ 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, - 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x22, 0xbd, 0x02, 0x0a, + 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x22, 0xf7, 0x03, 0x0a, 0x13, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, @@ -4017,285 +4136,331 @@ var file_control_proto_rawDesc = []byte{ 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x2d, 0x0a, 0x12, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x66, 0x72, 0x6f, 0x6e, 0x74, - 0x65, 0x6e, 0x64, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x22, 0xbe, 0x02, 0x0a, - 0x14, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, - 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, - 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x69, 0x7a, 0x65, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x09, 0x73, 0x69, 0x7a, 0x65, 0x42, 0x79, 0x74, 0x65, - 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x5f, 0x66, 0x61, 0x63, 0x74, 0x6f, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x11, 0x72, - 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x46, 0x61, 0x63, 0x74, 0x6f, 0x72, - 0x12, 0x19, 0x0a, 0x08, 0x70, 0x76, 0x63, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x07, 0x70, 0x76, 0x63, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x70, - 0x76, 0x63, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x05, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x0c, 0x70, 0x76, 0x63, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, - 0x12, 0x17, 0x0a, 0x07, 0x70, 0x76, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x06, 0x70, 0x76, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x70, 0x76, 0x63, - 0x5f, 0x75, 0x69, 0x64, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x70, 0x76, 0x63, 0x55, - 0x69, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x08, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x2d, - 0x0a, 0x12, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, - 0x70, 0x6f, 0x72, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x66, 0x72, 0x6f, 0x6e, - 0x74, 0x65, 0x6e, 0x64, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x22, 0x32, 0x0a, - 0x13, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, - 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, - 0x64, 0x22, 0x16, 0x0a, 0x14, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, - 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x4e, 0x0a, 0x19, 0x4d, 0x61, 0x72, - 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, + 0x65, 0x6e, 0x64, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x1d, 0x0a, 0x0a, + 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0d, + 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x63, + 0x68, 0x75, 0x6e, 0x6b, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x04, + 0x52, 0x0a, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x23, 0x0a, 0x0d, + 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x18, 0x0c, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x0c, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x73, 0x6e, 0x61, 0x70, + 0x73, 0x68, 0x6f, 0x74, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x73, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x53, 0x6e, 0x61, 0x70, 0x73, 0x68, 0x6f, 0x74, 0x12, 0x2a, 0x0a, 0x11, 0x63, 0x72, + 0x65, 0x61, 0x74, 0x65, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, + 0x0e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x22, 0xbc, 0x03, 0x0a, 0x14, 0x43, 0x72, 0x65, 0x61, 0x74, + 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, + 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, + 0x73, 0x69, 0x7a, 0x65, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, + 0x52, 0x09, 0x73, 0x69, 0x7a, 0x65, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x72, + 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x66, 0x61, 0x63, 0x74, 0x6f, + 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x11, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x46, 0x61, 0x63, 0x74, 0x6f, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x70, 0x76, + 0x63, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x70, 0x76, + 0x63, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x70, 0x76, 0x63, 0x5f, 0x6e, 0x61, 0x6d, + 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x70, 0x76, + 0x63, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x70, 0x76, + 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x70, 0x76, 0x4e, + 0x61, 0x6d, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x70, 0x76, 0x63, 0x5f, 0x75, 0x69, 0x64, 0x18, 0x07, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x70, 0x76, 0x63, 0x55, 0x69, 0x64, 0x12, 0x1a, 0x0a, 0x08, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x2d, 0x0a, 0x12, 0x66, 0x72, 0x6f, 0x6e, + 0x74, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x09, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x54, 0x72, + 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x6c, 0x61, 0x79, 0x6f, 0x75, + 0x74, 0x5f, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6c, 0x61, 0x79, 0x6f, + 0x75, 0x74, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x73, 0x69, + 0x7a, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x53, + 0x69, 0x7a, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x5f, 0x62, 0x79, 0x74, + 0x65, 0x73, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0a, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x42, + 0x79, 0x74, 0x65, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x72, 0x65, + 0x61, 0x64, 0x79, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x73, 0x74, 0x6f, 0x72, 0x65, + 0x52, 0x65, 0x61, 0x64, 0x79, 0x22, 0x38, 0x0a, 0x19, 0x47, 0x65, 0x74, 0x4c, 0x69, 0x66, 0x65, + 0x63, 0x79, 0x63, 0x6c, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x22, + 0x32, 0x0a, 0x13, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, - 0x65, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x48, 0x0a, 0x1a, 0x4d, 0x61, 0x72, - 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x05, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x12, 0x14, 0x0a, - 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x73, 0x74, - 0x61, 0x74, 0x65, 0x22, 0xa5, 0x04, 0x0a, 0x0f, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, - 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, - 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, - 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, - 0x61, 0x49, 0x64, 0x12, 0x28, 0x0a, 0x10, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x64, 0x61, - 0x74, 0x61, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x74, - 0x61, 0x72, 0x67, 0x65, 0x74, 0x44, 0x61, 0x74, 0x61, 0x41, 0x64, 0x64, 0x72, 0x12, 0x28, 0x0a, - 0x10, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x63, 0x74, 0x72, 0x6c, 0x5f, 0x61, 0x64, 0x64, - 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x43, - 0x74, 0x72, 0x6c, 0x41, 0x64, 0x64, 0x72, 0x12, 0x3d, 0x0a, 0x1b, 0x65, 0x78, 0x70, 0x65, 0x63, - 0x74, 0x65, 0x64, 0x5f, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x72, 0x65, 0x70, 0x6c, - 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x18, 0x65, 0x78, - 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x43, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x70, - 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x34, 0x0a, 0x16, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, - 0x65, 0x64, 0x5f, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x65, 0x70, 0x6f, 0x63, 0x68, - 0x18, 0x06, 0x20, 0x01, 0x28, 0x04, 0x52, 0x14, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, - 0x43, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x45, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x21, 0x0a, 0x0c, - 0x61, 0x63, 0x6b, 0x5f, 0x65, 0x6c, 0x69, 0x67, 0x69, 0x62, 0x6c, 0x65, 0x18, 0x07, 0x20, 0x01, - 0x28, 0x08, 0x52, 0x0b, 0x61, 0x63, 0x6b, 0x45, 0x6c, 0x69, 0x67, 0x69, 0x62, 0x6c, 0x65, 0x12, - 0x45, 0x0a, 0x1f, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x5f, 0x66, 0x65, 0x6e, 0x63, - 0x65, 0x64, 0x5f, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x5f, 0x66, 0x61, 0x69, 0x6c, 0x62, 0x61, - 0x63, 0x6b, 0x18, 0x08, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1c, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, - 0x6e, 0x64, 0x46, 0x65, 0x6e, 0x63, 0x65, 0x64, 0x42, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x46, 0x61, - 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x75, 0x72, 0x61, 0x62, 0x6c, - 0x65, 0x5f, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x5f, 0x63, 0x6f, 0x76, 0x65, 0x72, - 0x65, 0x64, 0x18, 0x09, 0x20, 0x01, 0x28, 0x08, 0x52, 0x16, 0x64, 0x75, 0x72, 0x61, 0x62, 0x6c, - 0x65, 0x46, 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x43, 0x6f, 0x76, 0x65, 0x72, 0x65, 0x64, - 0x12, 0x44, 0x0a, 0x1f, 0x6e, 0x6f, 0x5f, 0x63, 0x72, 0x6f, 0x73, 0x73, 0x5f, 0x76, 0x6f, 0x6c, - 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x63, 0x68, 0x61, - 0x6e, 0x67, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1b, 0x6e, 0x6f, 0x43, 0x72, 0x6f, - 0x73, 0x73, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, - 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x76, 0x69, 0x64, 0x65, 0x6e, - 0x63, 0x65, 0x5f, 0x72, 0x65, 0x66, 0x73, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x65, - 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x52, 0x65, 0x66, 0x73, 0x22, 0xa7, 0x03, 0x0a, 0x10, - 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x12, 0x29, 0x0a, 0x10, 0x66, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x5f, 0x73, 0x74, 0x61, - 0x72, 0x74, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0f, 0x66, 0x61, 0x69, 0x6c, - 0x62, 0x61, 0x63, 0x6b, 0x53, 0x74, 0x61, 0x72, 0x74, 0x65, 0x64, 0x12, 0x38, 0x0a, 0x18, 0x61, - 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x5f, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x5f, 0x61, - 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x16, 0x61, - 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x45, 0x70, 0x6f, 0x63, 0x68, 0x41, 0x64, 0x76, - 0x61, 0x6e, 0x63, 0x65, 0x64, 0x12, 0x41, 0x0a, 0x1d, 0x73, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x5f, - 0x70, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x5f, 0x61, 0x66, 0x74, 0x65, 0x72, 0x5f, 0x66, 0x61, - 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1a, 0x73, 0x69, - 0x6e, 0x67, 0x6c, 0x65, 0x50, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x66, 0x74, 0x65, 0x72, - 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x12, 0x50, 0x0a, 0x25, 0x70, 0x75, 0x62, 0x6c, - 0x69, 0x73, 0x68, 0x5f, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x73, 0x77, 0x61, 0x70, 0x70, - 0x65, 0x64, 0x5f, 0x61, 0x66, 0x74, 0x65, 0x72, 0x5f, 0x66, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, - 0x6b, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x21, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, - 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x53, 0x77, 0x61, 0x70, 0x70, 0x65, 0x64, 0x41, 0x66, 0x74, - 0x65, 0x72, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x12, 0x2e, 0x0a, 0x13, 0x6e, 0x6f, - 0x5f, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x5f, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x6e, 0x6f, 0x53, 0x74, 0x6f, 0x72, 0x61, - 0x67, 0x65, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x44, 0x0a, 0x1f, 0x6e, 0x6f, - 0x5f, 0x63, 0x72, 0x6f, 0x73, 0x73, 0x5f, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, - 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x18, 0x06, 0x20, - 0x01, 0x28, 0x08, 0x52, 0x1b, 0x6e, 0x6f, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x56, 0x6f, 0x6c, 0x75, - 0x6d, 0x65, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, - 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x5f, 0x72, 0x65, 0x66, - 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, - 0x65, 0x52, 0x65, 0x66, 0x73, 0x22, 0x35, 0x0a, 0x16, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x52, 0x6f, - 0x75, 0x6e, 0x64, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, - 0x1b, 0x0a, 0x09, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x08, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x64, 0x22, 0xb0, 0x01, 0x0a, - 0x0a, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x52, 0x6f, 0x75, 0x6e, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x76, - 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, - 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6c, - 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, - 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x72, 0x6f, 0x75, 0x6e, 0x64, - 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x72, 0x6f, 0x75, 0x6e, 0x64, - 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x66, 0x65, 0x6e, 0x63, 0x65, 0x5f, 0x65, 0x70, 0x6f, 0x63, - 0x68, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0a, 0x66, 0x65, 0x6e, 0x63, 0x65, 0x45, 0x70, - 0x6f, 0x63, 0x68, 0x12, 0x2a, 0x0a, 0x11, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, - 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, - 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x49, 0x64, 0x22, - 0xba, 0x03, 0x0a, 0x0b, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x12, - 0x1b, 0x0a, 0x09, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x08, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, - 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, - 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, - 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x72, 0x6f, 0x75, 0x6e, - 0x64, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x72, 0x6f, 0x75, 0x6e, - 0x64, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x69, 0x64, 0x18, - 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x49, 0x64, 0x12, 0x1f, - 0x0a, 0x0b, 0x64, 0x75, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x65, 0x6e, 0x64, 0x18, 0x06, 0x20, - 0x01, 0x28, 0x04, 0x52, 0x0a, 0x64, 0x75, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x45, 0x6e, 0x64, 0x12, - 0x26, 0x0a, 0x0f, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x65, 0x70, 0x6f, - 0x63, 0x68, 0x18, 0x07, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0d, 0x6c, 0x61, 0x73, 0x74, 0x44, 0x61, - 0x74, 0x61, 0x45, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x2d, 0x0a, 0x13, 0x6c, 0x61, 0x73, 0x74, 0x5f, - 0x64, 0x61, 0x74, 0x61, 0x5f, 0x66, 0x69, 0x72, 0x73, 0x74, 0x5f, 0x6c, 0x73, 0x6e, 0x18, 0x08, - 0x20, 0x01, 0x28, 0x04, 0x52, 0x10, 0x6c, 0x61, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x46, 0x69, - 0x72, 0x73, 0x74, 0x4c, 0x73, 0x6e, 0x12, 0x23, 0x0a, 0x0d, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x5f, - 0x70, 0x72, 0x65, 0x73, 0x65, 0x6e, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x74, - 0x61, 0x62, 0x6c, 0x65, 0x50, 0x72, 0x65, 0x73, 0x65, 0x6e, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x74, - 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x08, - 0x52, 0x0a, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x12, 0x23, 0x0a, 0x0d, - 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x72, 0x65, 0x61, 0x64, 0x79, 0x18, 0x0b, 0x20, - 0x01, 0x28, 0x08, 0x52, 0x0c, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x52, 0x65, 0x61, 0x64, - 0x79, 0x12, 0x23, 0x0a, 0x0d, 0x70, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x5f, 0x72, 0x65, 0x61, - 0x64, 0x79, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x70, 0x72, 0x69, 0x6d, 0x61, 0x72, - 0x79, 0x52, 0x65, 0x61, 0x64, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x6c, 0x6f, 0x6f, 0x72, 0x18, - 0x0d, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x66, 0x6c, 0x6f, 0x6f, 0x72, 0x22, 0x0a, 0x0a, 0x08, - 0x50, 0x72, 0x6f, 0x62, 0x65, 0x41, 0x63, 0x6b, 0x2a, 0x7c, 0x0a, 0x0b, 0x50, 0x72, 0x69, 0x6d, - 0x61, 0x72, 0x79, 0x4b, 0x69, 0x6e, 0x64, 0x12, 0x1c, 0x0a, 0x18, 0x50, 0x52, 0x49, 0x4d, 0x41, - 0x52, 0x59, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, - 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x1a, 0x0a, 0x16, 0x50, 0x52, 0x49, 0x4d, 0x41, 0x52, 0x59, - 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x42, 0x4f, 0x4f, 0x54, 0x53, 0x54, 0x52, 0x41, 0x50, 0x10, - 0x01, 0x12, 0x1a, 0x0a, 0x16, 0x50, 0x52, 0x49, 0x4d, 0x41, 0x52, 0x59, 0x5f, 0x4b, 0x49, 0x4e, - 0x44, 0x5f, 0x50, 0x52, 0x4f, 0x4d, 0x4f, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x02, 0x12, 0x17, 0x0a, - 0x13, 0x50, 0x52, 0x49, 0x4d, 0x41, 0x52, 0x59, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x46, 0x4f, - 0x52, 0x43, 0x45, 0x44, 0x10, 0x03, 0x32, 0xb7, 0x02, 0x0a, 0x12, 0x4f, 0x62, 0x73, 0x65, 0x72, - 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x62, 0x0a, - 0x0f, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, - 0x12, 0x28, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, - 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x48, 0x65, 0x61, 0x72, 0x74, - 0x62, 0x65, 0x61, 0x74, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x1a, 0x25, 0x2e, 0x73, 0x65, 0x61, - 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, - 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x41, 0x63, - 0x6b, 0x12, 0x56, 0x0a, 0x0b, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x50, 0x72, 0x6f, 0x62, 0x65, - 0x12, 0x24, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, - 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x50, 0x72, 0x6f, 0x62, 0x65, - 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x1a, 0x21, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, - 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, - 0x2e, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x41, 0x63, 0x6b, 0x12, 0x65, 0x0a, 0x12, 0x52, 0x65, 0x70, - 0x6f, 0x72, 0x74, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, - 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, - 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, - 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x1a, 0x28, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, - 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, - 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x41, 0x63, 0x6b, - 0x32, 0xf1, 0x01, 0x0a, 0x11, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x53, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x6c, 0x0a, 0x14, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, - 0x69, 0x62, 0x65, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x29, - 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, - 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, - 0x62, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, - 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, - 0x72, 0x6f, 0x6c, 0x2e, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x46, 0x61, - 0x63, 0x74, 0x30, 0x01, 0x12, 0x6e, 0x0a, 0x14, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, - 0x65, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x52, 0x6f, 0x75, 0x6e, 0x64, 0x73, 0x12, 0x2f, 0x2e, 0x73, + 0x65, 0x49, 0x64, 0x22, 0x16, 0x0a, 0x14, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, + 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x4e, 0x0a, 0x19, 0x4d, + 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, + 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, + 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, + 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x48, 0x0a, 0x1a, 0x4d, + 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, + 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x6b, 0x6e, 0x6f, + 0x77, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x05, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x12, + 0x14, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, + 0x73, 0x74, 0x61, 0x74, 0x65, 0x22, 0xa5, 0x04, 0x0a, 0x0f, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, + 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x76, 0x6f, 0x6c, + 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x76, 0x6f, + 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, + 0x61, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6c, + 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x28, 0x0a, 0x10, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, + 0x64, 0x61, 0x74, 0x61, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x0e, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x44, 0x61, 0x74, 0x61, 0x41, 0x64, 0x64, 0x72, 0x12, + 0x28, 0x0a, 0x10, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x63, 0x74, 0x72, 0x6c, 0x5f, 0x61, + 0x64, 0x64, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x74, 0x61, 0x72, 0x67, 0x65, + 0x74, 0x43, 0x74, 0x72, 0x6c, 0x41, 0x64, 0x64, 0x72, 0x12, 0x3d, 0x0a, 0x1b, 0x65, 0x78, 0x70, + 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x72, 0x65, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x18, + 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x43, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x52, + 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x34, 0x0a, 0x16, 0x65, 0x78, 0x70, 0x65, + 0x63, 0x74, 0x65, 0x64, 0x5f, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x65, 0x70, 0x6f, + 0x63, 0x68, 0x18, 0x06, 0x20, 0x01, 0x28, 0x04, 0x52, 0x14, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, + 0x65, 0x64, 0x43, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x45, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x21, + 0x0a, 0x0c, 0x61, 0x63, 0x6b, 0x5f, 0x65, 0x6c, 0x69, 0x67, 0x69, 0x62, 0x6c, 0x65, 0x18, 0x07, + 0x20, 0x01, 0x28, 0x08, 0x52, 0x0b, 0x61, 0x63, 0x6b, 0x45, 0x6c, 0x69, 0x67, 0x69, 0x62, 0x6c, + 0x65, 0x12, 0x45, 0x0a, 0x1f, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x5f, 0x66, 0x65, + 0x6e, 0x63, 0x65, 0x64, 0x5f, 0x62, 0x65, 0x66, 0x6f, 0x72, 0x65, 0x5f, 0x66, 0x61, 0x69, 0x6c, + 0x62, 0x61, 0x63, 0x6b, 0x18, 0x08, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1c, 0x66, 0x72, 0x6f, 0x6e, + 0x74, 0x65, 0x6e, 0x64, 0x46, 0x65, 0x6e, 0x63, 0x65, 0x64, 0x42, 0x65, 0x66, 0x6f, 0x72, 0x65, + 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x75, 0x72, 0x61, + 0x62, 0x6c, 0x65, 0x5f, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x5f, 0x63, 0x6f, 0x76, + 0x65, 0x72, 0x65, 0x64, 0x18, 0x09, 0x20, 0x01, 0x28, 0x08, 0x52, 0x16, 0x64, 0x75, 0x72, 0x61, + 0x62, 0x6c, 0x65, 0x46, 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x43, 0x6f, 0x76, 0x65, 0x72, + 0x65, 0x64, 0x12, 0x44, 0x0a, 0x1f, 0x6e, 0x6f, 0x5f, 0x63, 0x72, 0x6f, 0x73, 0x73, 0x5f, 0x76, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x63, + 0x68, 0x61, 0x6e, 0x67, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1b, 0x6e, 0x6f, 0x43, + 0x72, 0x6f, 0x73, 0x73, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, + 0x74, 0x79, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x76, 0x69, 0x64, + 0x65, 0x6e, 0x63, 0x65, 0x5f, 0x72, 0x65, 0x66, 0x73, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x09, 0x52, + 0x0c, 0x65, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x52, 0x65, 0x66, 0x73, 0x22, 0xa7, 0x03, + 0x0a, 0x10, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x66, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x5f, 0x73, + 0x74, 0x61, 0x72, 0x74, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0f, 0x66, 0x61, + 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x53, 0x74, 0x61, 0x72, 0x74, 0x65, 0x64, 0x12, 0x38, 0x0a, + 0x18, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x5f, 0x65, 0x70, 0x6f, 0x63, 0x68, + 0x5f, 0x61, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x16, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x45, 0x70, 0x6f, 0x63, 0x68, 0x41, + 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x64, 0x12, 0x41, 0x0a, 0x1d, 0x73, 0x69, 0x6e, 0x67, 0x6c, + 0x65, 0x5f, 0x70, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x5f, 0x61, 0x66, 0x74, 0x65, 0x72, 0x5f, + 0x66, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1a, + 0x73, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x50, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x66, 0x74, + 0x65, 0x72, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x12, 0x50, 0x0a, 0x25, 0x70, 0x75, + 0x62, 0x6c, 0x69, 0x73, 0x68, 0x5f, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x5f, 0x73, 0x77, 0x61, + 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x66, 0x74, 0x65, 0x72, 0x5f, 0x66, 0x61, 0x69, 0x6c, 0x62, + 0x61, 0x63, 0x6b, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x21, 0x70, 0x75, 0x62, 0x6c, 0x69, + 0x73, 0x68, 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x53, 0x77, 0x61, 0x70, 0x70, 0x65, 0x64, 0x41, + 0x66, 0x74, 0x65, 0x72, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x12, 0x2e, 0x0a, 0x13, + 0x6e, 0x6f, 0x5f, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x5f, 0x6d, 0x75, 0x74, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x6e, 0x6f, 0x53, 0x74, 0x6f, + 0x72, 0x61, 0x67, 0x65, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x44, 0x0a, 0x1f, + 0x6e, 0x6f, 0x5f, 0x63, 0x72, 0x6f, 0x73, 0x73, 0x5f, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, + 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x18, + 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1b, 0x6e, 0x6f, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x56, 0x6f, + 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x43, 0x68, 0x61, 0x6e, + 0x67, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x5f, 0x72, + 0x65, 0x66, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x76, 0x69, 0x64, 0x65, + 0x6e, 0x63, 0x65, 0x52, 0x65, 0x66, 0x73, 0x22, 0x35, 0x0a, 0x16, 0x50, 0x72, 0x6f, 0x62, 0x65, + 0x52, 0x6f, 0x75, 0x6e, 0x64, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x12, 0x1b, 0x0a, 0x09, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x64, 0x22, 0xb0, + 0x01, 0x0a, 0x0a, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x52, 0x6f, 0x75, 0x6e, 0x64, 0x12, 0x1b, 0x0a, + 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, + 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x72, 0x6f, 0x75, + 0x6e, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x72, 0x6f, 0x75, + 0x6e, 0x64, 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x66, 0x65, 0x6e, 0x63, 0x65, 0x5f, 0x65, 0x70, + 0x6f, 0x63, 0x68, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0a, 0x66, 0x65, 0x6e, 0x63, 0x65, + 0x45, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x2a, 0x0a, 0x11, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, + 0x64, 0x5f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, + 0x52, 0x0f, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x49, + 0x64, 0x22, 0xba, 0x03, 0x0a, 0x0b, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x41, 0x6e, 0x73, 0x77, 0x65, + 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x64, 0x12, 0x1b, + 0x0a, 0x09, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x08, 0x76, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, + 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x09, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x72, 0x6f, + 0x75, 0x6e, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x72, 0x6f, + 0x75, 0x6e, 0x64, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x69, + 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x49, 0x64, + 0x12, 0x1f, 0x0a, 0x0b, 0x64, 0x75, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x65, 0x6e, 0x64, 0x18, + 0x06, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0a, 0x64, 0x75, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x45, 0x6e, + 0x64, 0x12, 0x26, 0x0a, 0x0f, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x65, + 0x70, 0x6f, 0x63, 0x68, 0x18, 0x07, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0d, 0x6c, 0x61, 0x73, 0x74, + 0x44, 0x61, 0x74, 0x61, 0x45, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x2d, 0x0a, 0x13, 0x6c, 0x61, 0x73, + 0x74, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x66, 0x69, 0x72, 0x73, 0x74, 0x5f, 0x6c, 0x73, 0x6e, + 0x18, 0x08, 0x20, 0x01, 0x28, 0x04, 0x52, 0x10, 0x6c, 0x61, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, + 0x46, 0x69, 0x72, 0x73, 0x74, 0x4c, 0x73, 0x6e, 0x12, 0x23, 0x0a, 0x0d, 0x74, 0x61, 0x62, 0x6c, + 0x65, 0x5f, 0x70, 0x72, 0x65, 0x73, 0x65, 0x6e, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x0c, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x50, 0x72, 0x65, 0x73, 0x65, 0x6e, 0x74, 0x12, 0x1f, 0x0a, + 0x0b, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x0a, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x12, 0x23, + 0x0a, 0x0d, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x5f, 0x72, 0x65, 0x61, 0x64, 0x79, 0x18, + 0x0b, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x72, 0x65, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x52, 0x65, + 0x61, 0x64, 0x79, 0x12, 0x23, 0x0a, 0x0d, 0x70, 0x72, 0x69, 0x6d, 0x61, 0x72, 0x79, 0x5f, 0x72, + 0x65, 0x61, 0x64, 0x79, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x70, 0x72, 0x69, 0x6d, + 0x61, 0x72, 0x79, 0x52, 0x65, 0x61, 0x64, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x6c, 0x6f, 0x6f, + 0x72, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x66, 0x6c, 0x6f, 0x6f, 0x72, 0x22, 0x0a, + 0x0a, 0x08, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x41, 0x63, 0x6b, 0x2a, 0x7c, 0x0a, 0x0b, 0x50, 0x72, + 0x69, 0x6d, 0x61, 0x72, 0x79, 0x4b, 0x69, 0x6e, 0x64, 0x12, 0x1c, 0x0a, 0x18, 0x50, 0x52, 0x49, + 0x4d, 0x41, 0x52, 0x59, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, + 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x1a, 0x0a, 0x16, 0x50, 0x52, 0x49, 0x4d, 0x41, + 0x52, 0x59, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x42, 0x4f, 0x4f, 0x54, 0x53, 0x54, 0x52, 0x41, + 0x50, 0x10, 0x01, 0x12, 0x1a, 0x0a, 0x16, 0x50, 0x52, 0x49, 0x4d, 0x41, 0x52, 0x59, 0x5f, 0x4b, + 0x49, 0x4e, 0x44, 0x5f, 0x50, 0x52, 0x4f, 0x4d, 0x4f, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x02, 0x12, + 0x17, 0x0a, 0x13, 0x50, 0x52, 0x49, 0x4d, 0x41, 0x52, 0x59, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, + 0x46, 0x4f, 0x52, 0x43, 0x45, 0x44, 0x10, 0x03, 0x32, 0xb7, 0x02, 0x0a, 0x12, 0x4f, 0x62, 0x73, + 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, + 0x62, 0x0a, 0x0f, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, + 0x61, 0x74, 0x12, 0x28, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, + 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x48, 0x65, 0x61, + 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x1a, 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x52, 0x6f, 0x75, 0x6e, - 0x64, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0x23, 0x2e, - 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, - 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x52, 0x6f, 0x75, - 0x6e, 0x64, 0x30, 0x01, 0x32, 0x77, 0x0a, 0x0f, 0x45, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, - 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x64, 0x0a, 0x11, 0x51, 0x75, 0x65, 0x72, 0x79, - 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x26, 0x2e, 0x73, - 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, - 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x53, - 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x32, 0xd1, 0x04, - 0x0a, 0x16, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, - 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x74, 0x0a, 0x10, 0x47, 0x65, 0x74, 0x43, - 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x30, 0x2e, 0x73, - 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x47, 0x65, 0x74, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, - 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2e, - 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, - 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, - 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x68, - 0x0a, 0x0b, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, 0x12, 0x2b, 0x2e, - 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, - 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x6f, 0x6c, 0x75, - 0x6d, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2c, 0x2e, 0x73, 0x65, 0x61, - 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, - 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6b, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x56, - 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2f, 0x2e, 0x73, 0x65, - 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, - 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x47, 0x65, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x53, - 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x73, - 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x45, 0x76, 0x69, - 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x77, 0x0a, 0x11, 0x47, 0x65, 0x74, 0x56, 0x6f, 0x6c, 0x75, - 0x6d, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x31, 0x2e, 0x73, 0x65, 0x61, - 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, - 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x47, 0x65, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x54, 0x69, - 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2f, 0x2e, - 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, - 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x54, 0x69, - 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x71, - 0x0a, 0x12, 0x57, 0x61, 0x74, 0x63, 0x68, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, - 0x65, 0x6e, 0x74, 0x73, 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, - 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x57, - 0x61, 0x74, 0x63, 0x68, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, - 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, + 0x41, 0x63, 0x6b, 0x12, 0x56, 0x0a, 0x0b, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x50, 0x72, 0x6f, + 0x62, 0x65, 0x12, 0x24, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, + 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x50, 0x72, 0x6f, + 0x62, 0x65, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x1a, 0x21, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, - 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x30, - 0x01, 0x32, 0xec, 0x04, 0x0a, 0x10, 0x4c, 0x69, 0x66, 0x65, 0x63, 0x79, 0x63, 0x6c, 0x65, 0x53, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x6b, 0x0a, 0x0c, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, - 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x12, 0x2c, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, - 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, - 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2d, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, - 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, - 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x6b, 0x0a, 0x0c, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, - 0x75, 0x6d, 0x65, 0x12, 0x2c, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, - 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x44, 0x65, - 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x1a, 0x2d, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, - 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x44, 0x65, 0x6c, 0x65, - 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x12, 0x7d, 0x0a, 0x12, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, - 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, - 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, - 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, - 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x73, 0x65, 0x61, - 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, - 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, - 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x7e, 0x0a, 0x13, 0x41, 0x62, 0x6f, 0x72, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, - 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, - 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, - 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, - 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x73, 0x65, 0x61, - 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, - 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, - 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x7f, 0x0a, 0x14, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, - 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, - 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, - 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, - 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x73, 0x65, + 0x6f, 0x6c, 0x2e, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x41, 0x63, 0x6b, 0x12, 0x65, 0x0a, 0x12, 0x52, + 0x65, 0x70, 0x6f, 0x72, 0x74, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, + 0x74, 0x12, 0x25, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, + 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, + 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x1a, 0x28, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, + 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x41, + 0x63, 0x6b, 0x32, 0xf1, 0x01, 0x0a, 0x11, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, + 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x6c, 0x0a, 0x14, 0x53, 0x75, 0x62, 0x73, + 0x63, 0x72, 0x69, 0x62, 0x65, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x73, + 0x12, 0x29, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, + 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x53, 0x75, 0x62, 0x73, 0x63, + 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, - 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, - 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x32, 0x79, 0x0a, 0x0f, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x53, 0x65, 0x72, 0x76, - 0x69, 0x63, 0x65, 0x12, 0x66, 0x0a, 0x0f, 0x45, 0x78, 0x65, 0x63, 0x75, 0x74, 0x65, 0x46, 0x61, - 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x12, 0x28, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x41, 0x73, 0x73, 0x69, 0x67, 0x6e, 0x6d, 0x65, 0x6e, 0x74, + 0x46, 0x61, 0x63, 0x74, 0x30, 0x01, 0x12, 0x6e, 0x0a, 0x14, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, + 0x69, 0x62, 0x65, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x52, 0x6f, 0x75, 0x6e, 0x64, 0x73, 0x12, 0x2f, + 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, + 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x52, 0x6f, + 0x75, 0x6e, 0x64, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x1a, + 0x23, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x50, 0x72, 0x6f, 0x62, 0x65, 0x52, + 0x6f, 0x75, 0x6e, 0x64, 0x30, 0x01, 0x32, 0x77, 0x0a, 0x0f, 0x45, 0x76, 0x69, 0x64, 0x65, 0x6e, + 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x64, 0x0a, 0x11, 0x51, 0x75, 0x65, + 0x72, 0x79, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x26, + 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, + 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, - 0x2e, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x29, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, - 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x46, 0x61, 0x69, 0x6c, 0x62, - 0x61, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x3d, 0x5a, 0x3b, 0x67, - 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, - 0x64, 0x66, 0x73, 0x2f, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x2d, 0x62, 0x6c, 0x6f, 0x63, - 0x6b, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, - 0x6f, 0x6c, 0x3b, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x33, + 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x32, + 0xd1, 0x04, 0x0a, 0x16, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x69, 0x64, 0x65, + 0x6e, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x74, 0x0a, 0x10, 0x47, 0x65, + 0x74, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x30, + 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, + 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x47, 0x65, 0x74, 0x43, 0x6c, 0x75, 0x73, + 0x74, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x2e, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, + 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, + 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x68, 0x0a, 0x0b, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x73, 0x12, + 0x2b, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x6f, + 0x6c, 0x75, 0x6d, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2c, 0x2e, 0x73, + 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6b, 0x0a, 0x0f, 0x47, 0x65, + 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2f, 0x2e, + 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, + 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x47, 0x65, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, + 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, + 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x45, + 0x76, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x77, 0x0a, 0x11, 0x47, 0x65, 0x74, 0x56, 0x6f, + 0x6c, 0x75, 0x6d, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x31, 0x2e, 0x73, + 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x47, 0x65, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, + 0x54, 0x69, 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x2f, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, + 0x54, 0x69, 0x6d, 0x65, 0x6c, 0x69, 0x6e, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x71, 0x0a, 0x12, 0x57, 0x61, 0x74, 0x63, 0x68, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, + 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, + 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x2e, 0x57, 0x61, 0x74, 0x63, 0x68, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, + 0x6e, 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x25, 0x2e, 0x73, 0x65, 0x61, + 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, + 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x45, 0x76, 0x65, 0x6e, + 0x74, 0x30, 0x01, 0x32, 0xe3, 0x07, 0x0a, 0x10, 0x4c, 0x69, 0x66, 0x65, 0x63, 0x79, 0x63, 0x6c, + 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x6b, 0x0a, 0x0c, 0x43, 0x72, 0x65, 0x61, + 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x12, 0x2c, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, + 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2d, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, + 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6e, 0x0a, 0x09, 0x47, 0x65, 0x74, 0x56, 0x6f, 0x6c, 0x75, + 0x6d, 0x65, 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, + 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x47, 0x65, 0x74, + 0x4c, 0x69, 0x66, 0x65, 0x63, 0x79, 0x63, 0x6c, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2d, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, + 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6b, 0x0a, 0x0c, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x12, 0x2c, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, + 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, + 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x2d, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, + 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x44, 0x65, + 0x6c, 0x65, 0x74, 0x65, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x7d, 0x0a, 0x12, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, + 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, + 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, + 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x73, + 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x7e, 0x0a, 0x13, 0x41, 0x62, 0x6f, 0x72, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, + 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, + 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, + 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x73, + 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x7f, 0x0a, 0x14, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x56, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, + 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, + 0x72, 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, + 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, + 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, + 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, + 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x80, 0x01, 0x0a, 0x15, 0x52, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x56, 0x6f, + 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x32, 0x2e, 0x73, + 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, + 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x33, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, + 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x81, 0x01, 0x0a, 0x16, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x56, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x4e, 0x6f, 0x4c, 0x69, 0x76, 0x65, 0x4c, 0x65, 0x61, 0x73, 0x65, + 0x12, 0x32, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, + 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4d, 0x61, 0x72, 0x6b, 0x56, + 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, + 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x4d, + 0x61, 0x72, 0x6b, 0x56, 0x6f, 0x6c, 0x75, 0x6d, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6e, + 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x32, 0x79, 0x0a, 0x0f, 0x46, 0x61, 0x69, + 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x66, 0x0a, 0x0f, + 0x45, 0x78, 0x65, 0x63, 0x75, 0x74, 0x65, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x12, + 0x28, 0x2e, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, + 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x29, 0x2e, 0x73, 0x65, 0x61, 0x77, + 0x65, 0x65, 0x64, 0x66, 0x73, 0x2e, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, + 0x72, 0x6f, 0x6c, 0x2e, 0x46, 0x61, 0x69, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x3d, 0x5a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, + 0x6f, 0x6d, 0x2f, 0x73, 0x65, 0x61, 0x77, 0x65, 0x65, 0x64, 0x66, 0x73, 0x2f, 0x73, 0x65, 0x61, + 0x77, 0x65, 0x65, 0x64, 0x2d, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, + 0x72, 0x70, 0x63, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x3b, 0x63, 0x6f, 0x6e, 0x74, + 0x72, 0x6f, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -4311,7 +4476,7 @@ func file_control_proto_rawDescGZIP() []byte { } var file_control_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_control_proto_msgTypes = make([]protoimpl.MessageInfo, 38) +var file_control_proto_msgTypes = make([]protoimpl.MessageInfo, 39) var file_control_proto_goTypes = []interface{}{ (PrimaryKind)(0), // 0: seaweedfs.block.control.PrimaryKind (*HeartbeatReport)(nil), // 1: seaweedfs.block.control.HeartbeatReport @@ -4342,50 +4507,51 @@ var file_control_proto_goTypes = []interface{}{ (*VolumeTimelineResponse)(nil), // 26: seaweedfs.block.control.VolumeTimelineResponse (*CreateVolumeRequest)(nil), // 27: seaweedfs.block.control.CreateVolumeRequest (*CreateVolumeResponse)(nil), // 28: seaweedfs.block.control.CreateVolumeResponse - (*DeleteVolumeRequest)(nil), // 29: seaweedfs.block.control.DeleteVolumeRequest - (*DeleteVolumeResponse)(nil), // 30: seaweedfs.block.control.DeleteVolumeResponse - (*MarkVolumeDeletingRequest)(nil), // 31: seaweedfs.block.control.MarkVolumeDeletingRequest - (*MarkVolumeDeletingResponse)(nil), // 32: seaweedfs.block.control.MarkVolumeDeletingResponse - (*FailbackRequest)(nil), // 33: seaweedfs.block.control.FailbackRequest - (*FailbackResponse)(nil), // 34: seaweedfs.block.control.FailbackResponse - (*ProbeRoundSubscription)(nil), // 35: seaweedfs.block.control.ProbeRoundSubscription - (*ProbeRound)(nil), // 36: seaweedfs.block.control.ProbeRound - (*ProbeAnswer)(nil), // 37: seaweedfs.block.control.ProbeAnswer - (*ProbeAck)(nil), // 38: seaweedfs.block.control.ProbeAck - (*timestamppb.Timestamp)(nil), // 39: google.protobuf.Timestamp + (*GetLifecycleVolumeRequest)(nil), // 29: seaweedfs.block.control.GetLifecycleVolumeRequest + (*DeleteVolumeRequest)(nil), // 30: seaweedfs.block.control.DeleteVolumeRequest + (*DeleteVolumeResponse)(nil), // 31: seaweedfs.block.control.DeleteVolumeResponse + (*MarkVolumeDeletingRequest)(nil), // 32: seaweedfs.block.control.MarkVolumeDeletingRequest + (*MarkVolumeDeletingResponse)(nil), // 33: seaweedfs.block.control.MarkVolumeDeletingResponse + (*FailbackRequest)(nil), // 34: seaweedfs.block.control.FailbackRequest + (*FailbackResponse)(nil), // 35: seaweedfs.block.control.FailbackResponse + (*ProbeRoundSubscription)(nil), // 36: seaweedfs.block.control.ProbeRoundSubscription + (*ProbeRound)(nil), // 37: seaweedfs.block.control.ProbeRound + (*ProbeAnswer)(nil), // 38: seaweedfs.block.control.ProbeAnswer + (*ProbeAck)(nil), // 39: seaweedfs.block.control.ProbeAck + (*timestamppb.Timestamp)(nil), // 40: google.protobuf.Timestamp } var file_control_proto_depIdxs = []int32{ - 39, // 0: seaweedfs.block.control.HeartbeatReport.sent_at:type_name -> google.protobuf.Timestamp + 40, // 0: seaweedfs.block.control.HeartbeatReport.sent_at:type_name -> google.protobuf.Timestamp 4, // 1: seaweedfs.block.control.HeartbeatReport.slots:type_name -> seaweedfs.block.control.HeartbeatSlot 2, // 2: seaweedfs.block.control.HeartbeatReport.store_attestation:type_name -> seaweedfs.block.control.StoreAttestation 3, // 3: seaweedfs.block.control.StoreAttestation.stores:type_name -> seaweedfs.block.control.AttestedStore 5, // 4: seaweedfs.block.control.HeartbeatSlot.frontends:type_name -> seaweedfs.block.control.FrontendTarget - 39, // 5: seaweedfs.block.control.HeartbeatAck.accepted_at:type_name -> google.protobuf.Timestamp - 39, // 6: seaweedfs.block.control.ClusterEventAck.accepted_at:type_name -> google.protobuf.Timestamp + 40, // 5: seaweedfs.block.control.HeartbeatAck.accepted_at:type_name -> google.protobuf.Timestamp + 40, // 6: seaweedfs.block.control.ClusterEventAck.accepted_at:type_name -> google.protobuf.Timestamp 9, // 7: seaweedfs.block.control.AssignmentFact.peers:type_name -> seaweedfs.block.control.ReplicaDescriptor 0, // 8: seaweedfs.block.control.AssignmentFact.primary_kind:type_name -> seaweedfs.block.control.PrimaryKind 5, // 9: seaweedfs.block.control.StatusResponse.frontends:type_name -> seaweedfs.block.control.FrontendTarget 13, // 10: seaweedfs.block.control.StatusResponse.unhealthy_replicas:type_name -> seaweedfs.block.control.ReplicaUnhealthy - 39, // 11: seaweedfs.block.control.ClusterStatusResponse.captured_at:type_name -> google.protobuf.Timestamp + 40, // 11: seaweedfs.block.control.ClusterStatusResponse.captured_at:type_name -> google.protobuf.Timestamp 21, // 12: seaweedfs.block.control.ClusterStatusResponse.nodes:type_name -> seaweedfs.block.control.NodeEvidence 22, // 13: seaweedfs.block.control.ClusterStatusResponse.volumes:type_name -> seaweedfs.block.control.VolumeEvidence 19, // 14: seaweedfs.block.control.ClusterStatusResponse.conditions:type_name -> seaweedfs.block.control.ObservationCondition 24, // 15: seaweedfs.block.control.ClusterStatusResponse.events:type_name -> seaweedfs.block.control.ClusterEvent - 39, // 16: seaweedfs.block.control.NodeEvidence.last_heartbeat_at:type_name -> google.protobuf.Timestamp + 40, // 16: seaweedfs.block.control.NodeEvidence.last_heartbeat_at:type_name -> google.protobuf.Timestamp 19, // 17: seaweedfs.block.control.NodeEvidence.conditions:type_name -> seaweedfs.block.control.ObservationCondition 23, // 18: seaweedfs.block.control.VolumeEvidence.replicas:type_name -> seaweedfs.block.control.ReplicaEvidence 19, // 19: seaweedfs.block.control.VolumeEvidence.conditions:type_name -> seaweedfs.block.control.ObservationCondition 19, // 20: seaweedfs.block.control.ReplicaEvidence.conditions:type_name -> seaweedfs.block.control.ObservationCondition - 39, // 21: seaweedfs.block.control.ClusterEvent.event_time:type_name -> google.protobuf.Timestamp - 39, // 22: seaweedfs.block.control.ListVolumesResponse.captured_at:type_name -> google.protobuf.Timestamp + 40, // 21: seaweedfs.block.control.ClusterEvent.event_time:type_name -> google.protobuf.Timestamp + 40, // 22: seaweedfs.block.control.ListVolumesResponse.captured_at:type_name -> google.protobuf.Timestamp 22, // 23: seaweedfs.block.control.ListVolumesResponse.volumes:type_name -> seaweedfs.block.control.VolumeEvidence - 39, // 24: seaweedfs.block.control.VolumeTimelineResponse.captured_at:type_name -> google.protobuf.Timestamp + 40, // 24: seaweedfs.block.control.VolumeTimelineResponse.captured_at:type_name -> google.protobuf.Timestamp 24, // 25: seaweedfs.block.control.VolumeTimelineResponse.events:type_name -> seaweedfs.block.control.ClusterEvent 1, // 26: seaweedfs.block.control.ObservationService.ReportHeartbeat:input_type -> seaweedfs.block.control.HeartbeatReport - 37, // 27: seaweedfs.block.control.ObservationService.AnswerProbe:input_type -> seaweedfs.block.control.ProbeAnswer + 38, // 27: seaweedfs.block.control.ObservationService.AnswerProbe:input_type -> seaweedfs.block.control.ProbeAnswer 24, // 28: seaweedfs.block.control.ObservationService.ReportClusterEvent:input_type -> seaweedfs.block.control.ClusterEvent 8, // 29: seaweedfs.block.control.AssignmentService.SubscribeAssignments:input_type -> seaweedfs.block.control.SubscribeRequest - 35, // 30: seaweedfs.block.control.AssignmentService.SubscribeProbeRounds:input_type -> seaweedfs.block.control.ProbeRoundSubscription + 36, // 30: seaweedfs.block.control.AssignmentService.SubscribeProbeRounds:input_type -> seaweedfs.block.control.ProbeRoundSubscription 11, // 31: seaweedfs.block.control.EvidenceService.QueryVolumeStatus:input_type -> seaweedfs.block.control.StatusRequest 14, // 32: seaweedfs.block.control.ClusterEvidenceService.GetClusterStatus:input_type -> seaweedfs.block.control.GetClusterStatusRequest 15, // 33: seaweedfs.block.control.ClusterEvidenceService.ListVolumes:input_type -> seaweedfs.block.control.ListVolumesRequest @@ -4393,30 +4559,36 @@ var file_control_proto_depIdxs = []int32{ 17, // 35: seaweedfs.block.control.ClusterEvidenceService.GetVolumeTimeline:input_type -> seaweedfs.block.control.GetVolumeTimelineRequest 18, // 36: seaweedfs.block.control.ClusterEvidenceService.WatchClusterEvents:input_type -> seaweedfs.block.control.WatchClusterEventsRequest 27, // 37: seaweedfs.block.control.LifecycleService.CreateVolume:input_type -> seaweedfs.block.control.CreateVolumeRequest - 29, // 38: seaweedfs.block.control.LifecycleService.DeleteVolume:input_type -> seaweedfs.block.control.DeleteVolumeRequest - 31, // 39: seaweedfs.block.control.LifecycleService.MarkVolumeDeleting:input_type -> seaweedfs.block.control.MarkVolumeDeletingRequest - 31, // 40: seaweedfs.block.control.LifecycleService.AbortVolumeDeleting:input_type -> seaweedfs.block.control.MarkVolumeDeletingRequest - 31, // 41: seaweedfs.block.control.LifecycleService.CommitVolumeDeleting:input_type -> seaweedfs.block.control.MarkVolumeDeletingRequest - 33, // 42: seaweedfs.block.control.FailbackService.ExecuteFailback:input_type -> seaweedfs.block.control.FailbackRequest - 6, // 43: seaweedfs.block.control.ObservationService.ReportHeartbeat:output_type -> seaweedfs.block.control.HeartbeatAck - 38, // 44: seaweedfs.block.control.ObservationService.AnswerProbe:output_type -> seaweedfs.block.control.ProbeAck - 7, // 45: seaweedfs.block.control.ObservationService.ReportClusterEvent:output_type -> seaweedfs.block.control.ClusterEventAck - 10, // 46: seaweedfs.block.control.AssignmentService.SubscribeAssignments:output_type -> seaweedfs.block.control.AssignmentFact - 36, // 47: seaweedfs.block.control.AssignmentService.SubscribeProbeRounds:output_type -> seaweedfs.block.control.ProbeRound - 12, // 48: seaweedfs.block.control.EvidenceService.QueryVolumeStatus:output_type -> seaweedfs.block.control.StatusResponse - 20, // 49: seaweedfs.block.control.ClusterEvidenceService.GetClusterStatus:output_type -> seaweedfs.block.control.ClusterStatusResponse - 25, // 50: seaweedfs.block.control.ClusterEvidenceService.ListVolumes:output_type -> seaweedfs.block.control.ListVolumesResponse - 22, // 51: seaweedfs.block.control.ClusterEvidenceService.GetVolumeStatus:output_type -> seaweedfs.block.control.VolumeEvidence - 26, // 52: seaweedfs.block.control.ClusterEvidenceService.GetVolumeTimeline:output_type -> seaweedfs.block.control.VolumeTimelineResponse - 24, // 53: seaweedfs.block.control.ClusterEvidenceService.WatchClusterEvents:output_type -> seaweedfs.block.control.ClusterEvent - 28, // 54: seaweedfs.block.control.LifecycleService.CreateVolume:output_type -> seaweedfs.block.control.CreateVolumeResponse - 30, // 55: seaweedfs.block.control.LifecycleService.DeleteVolume:output_type -> seaweedfs.block.control.DeleteVolumeResponse - 32, // 56: seaweedfs.block.control.LifecycleService.MarkVolumeDeleting:output_type -> seaweedfs.block.control.MarkVolumeDeletingResponse - 32, // 57: seaweedfs.block.control.LifecycleService.AbortVolumeDeleting:output_type -> seaweedfs.block.control.MarkVolumeDeletingResponse - 32, // 58: seaweedfs.block.control.LifecycleService.CommitVolumeDeleting:output_type -> seaweedfs.block.control.MarkVolumeDeletingResponse - 34, // 59: seaweedfs.block.control.FailbackService.ExecuteFailback:output_type -> seaweedfs.block.control.FailbackResponse - 43, // [43:60] is the sub-list for method output_type - 26, // [26:43] is the sub-list for method input_type + 29, // 38: seaweedfs.block.control.LifecycleService.GetVolume:input_type -> seaweedfs.block.control.GetLifecycleVolumeRequest + 30, // 39: seaweedfs.block.control.LifecycleService.DeleteVolume:input_type -> seaweedfs.block.control.DeleteVolumeRequest + 32, // 40: seaweedfs.block.control.LifecycleService.MarkVolumeDeleting:input_type -> seaweedfs.block.control.MarkVolumeDeletingRequest + 32, // 41: seaweedfs.block.control.LifecycleService.AbortVolumeDeleting:input_type -> seaweedfs.block.control.MarkVolumeDeletingRequest + 32, // 42: seaweedfs.block.control.LifecycleService.CommitVolumeDeleting:input_type -> seaweedfs.block.control.MarkVolumeDeletingRequest + 32, // 43: seaweedfs.block.control.LifecycleService.ReserveVolumeDeletion:input_type -> seaweedfs.block.control.MarkVolumeDeletingRequest + 32, // 44: seaweedfs.block.control.LifecycleService.CheckVolumeNoLiveLease:input_type -> seaweedfs.block.control.MarkVolumeDeletingRequest + 34, // 45: seaweedfs.block.control.FailbackService.ExecuteFailback:input_type -> seaweedfs.block.control.FailbackRequest + 6, // 46: seaweedfs.block.control.ObservationService.ReportHeartbeat:output_type -> seaweedfs.block.control.HeartbeatAck + 39, // 47: seaweedfs.block.control.ObservationService.AnswerProbe:output_type -> seaweedfs.block.control.ProbeAck + 7, // 48: seaweedfs.block.control.ObservationService.ReportClusterEvent:output_type -> seaweedfs.block.control.ClusterEventAck + 10, // 49: seaweedfs.block.control.AssignmentService.SubscribeAssignments:output_type -> seaweedfs.block.control.AssignmentFact + 37, // 50: seaweedfs.block.control.AssignmentService.SubscribeProbeRounds:output_type -> seaweedfs.block.control.ProbeRound + 12, // 51: seaweedfs.block.control.EvidenceService.QueryVolumeStatus:output_type -> seaweedfs.block.control.StatusResponse + 20, // 52: seaweedfs.block.control.ClusterEvidenceService.GetClusterStatus:output_type -> seaweedfs.block.control.ClusterStatusResponse + 25, // 53: seaweedfs.block.control.ClusterEvidenceService.ListVolumes:output_type -> seaweedfs.block.control.ListVolumesResponse + 22, // 54: seaweedfs.block.control.ClusterEvidenceService.GetVolumeStatus:output_type -> seaweedfs.block.control.VolumeEvidence + 26, // 55: seaweedfs.block.control.ClusterEvidenceService.GetVolumeTimeline:output_type -> seaweedfs.block.control.VolumeTimelineResponse + 24, // 56: seaweedfs.block.control.ClusterEvidenceService.WatchClusterEvents:output_type -> seaweedfs.block.control.ClusterEvent + 28, // 57: seaweedfs.block.control.LifecycleService.CreateVolume:output_type -> seaweedfs.block.control.CreateVolumeResponse + 28, // 58: seaweedfs.block.control.LifecycleService.GetVolume:output_type -> seaweedfs.block.control.CreateVolumeResponse + 31, // 59: seaweedfs.block.control.LifecycleService.DeleteVolume:output_type -> seaweedfs.block.control.DeleteVolumeResponse + 33, // 60: seaweedfs.block.control.LifecycleService.MarkVolumeDeleting:output_type -> seaweedfs.block.control.MarkVolumeDeletingResponse + 33, // 61: seaweedfs.block.control.LifecycleService.AbortVolumeDeleting:output_type -> seaweedfs.block.control.MarkVolumeDeletingResponse + 33, // 62: seaweedfs.block.control.LifecycleService.CommitVolumeDeleting:output_type -> seaweedfs.block.control.MarkVolumeDeletingResponse + 33, // 63: seaweedfs.block.control.LifecycleService.ReserveVolumeDeletion:output_type -> seaweedfs.block.control.MarkVolumeDeletingResponse + 33, // 64: seaweedfs.block.control.LifecycleService.CheckVolumeNoLiveLease:output_type -> seaweedfs.block.control.MarkVolumeDeletingResponse + 35, // 65: seaweedfs.block.control.FailbackService.ExecuteFailback:output_type -> seaweedfs.block.control.FailbackResponse + 46, // [46:66] is the sub-list for method output_type + 26, // [26:46] is the sub-list for method input_type 26, // [26:26] is the sub-list for extension type_name 26, // [26:26] is the sub-list for extension extendee 0, // [0:26] is the sub-list for field type_name @@ -4765,7 +4937,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[28].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*DeleteVolumeRequest); i { + switch v := v.(*GetLifecycleVolumeRequest); i { case 0: return &v.state case 1: @@ -4777,7 +4949,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*DeleteVolumeResponse); i { + switch v := v.(*DeleteVolumeRequest); i { case 0: return &v.state case 1: @@ -4789,7 +4961,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MarkVolumeDeletingRequest); i { + switch v := v.(*DeleteVolumeResponse); i { case 0: return &v.state case 1: @@ -4801,7 +4973,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MarkVolumeDeletingResponse); i { + switch v := v.(*MarkVolumeDeletingRequest); i { case 0: return &v.state case 1: @@ -4813,7 +4985,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*FailbackRequest); i { + switch v := v.(*MarkVolumeDeletingResponse); i { case 0: return &v.state case 1: @@ -4825,7 +4997,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[33].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*FailbackResponse); i { + switch v := v.(*FailbackRequest); i { case 0: return &v.state case 1: @@ -4837,7 +5009,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[34].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ProbeRoundSubscription); i { + switch v := v.(*FailbackResponse); i { case 0: return &v.state case 1: @@ -4849,7 +5021,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[35].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ProbeRound); i { + switch v := v.(*ProbeRoundSubscription); i { case 0: return &v.state case 1: @@ -4861,7 +5033,7 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[36].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ProbeAnswer); i { + switch v := v.(*ProbeRound); i { case 0: return &v.state case 1: @@ -4873,6 +5045,18 @@ func file_control_proto_init() { } } file_control_proto_msgTypes[37].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ProbeAnswer); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_control_proto_msgTypes[38].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ProbeAck); i { case 0: return &v.state @@ -4891,7 +5075,7 @@ func file_control_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_control_proto_rawDesc, NumEnums: 1, - NumMessages: 38, + NumMessages: 39, NumExtensions: 0, NumServices: 6, }, diff --git a/seaweed-block/core/rpc/control/control_grpc.pb.go b/seaweed-block/core/rpc/control/control_grpc.pb.go index e20c54ff10..b6bf6b9803 100644 --- a/seaweed-block/core/rpc/control/control_grpc.pb.go +++ b/seaweed-block/core/rpc/control/control_grpc.pb.go @@ -782,11 +782,14 @@ var ClusterEvidenceService_ServiceDesc = grpc.ServiceDesc{ } const ( - LifecycleService_CreateVolume_FullMethodName = "/seaweedfs.block.control.LifecycleService/CreateVolume" - LifecycleService_DeleteVolume_FullMethodName = "/seaweedfs.block.control.LifecycleService/DeleteVolume" - LifecycleService_MarkVolumeDeleting_FullMethodName = "/seaweedfs.block.control.LifecycleService/MarkVolumeDeleting" - LifecycleService_AbortVolumeDeleting_FullMethodName = "/seaweedfs.block.control.LifecycleService/AbortVolumeDeleting" - LifecycleService_CommitVolumeDeleting_FullMethodName = "/seaweedfs.block.control.LifecycleService/CommitVolumeDeleting" + LifecycleService_CreateVolume_FullMethodName = "/seaweedfs.block.control.LifecycleService/CreateVolume" + LifecycleService_GetVolume_FullMethodName = "/seaweedfs.block.control.LifecycleService/GetVolume" + LifecycleService_DeleteVolume_FullMethodName = "/seaweedfs.block.control.LifecycleService/DeleteVolume" + LifecycleService_MarkVolumeDeleting_FullMethodName = "/seaweedfs.block.control.LifecycleService/MarkVolumeDeleting" + LifecycleService_AbortVolumeDeleting_FullMethodName = "/seaweedfs.block.control.LifecycleService/AbortVolumeDeleting" + LifecycleService_CommitVolumeDeleting_FullMethodName = "/seaweedfs.block.control.LifecycleService/CommitVolumeDeleting" + LifecycleService_ReserveVolumeDeletion_FullMethodName = "/seaweedfs.block.control.LifecycleService/ReserveVolumeDeletion" + LifecycleService_CheckVolumeNoLiveLease_FullMethodName = "/seaweedfs.block.control.LifecycleService/CheckVolumeNoLiveLease" ) // LifecycleServiceClient is the client API for LifecycleService service. @@ -794,6 +797,8 @@ const ( // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type LifecycleServiceClient interface { CreateVolume(ctx context.Context, in *CreateVolumeRequest, opts ...grpc.CallOption) (*CreateVolumeResponse, error) + // Resolve the durable volume identity without creating or changing it. + GetVolume(ctx context.Context, in *GetLifecycleVolumeRequest, opts ...grpc.CallOption) (*CreateVolumeResponse, error) DeleteVolume(ctx context.Context, in *DeleteVolumeRequest, opts ...grpc.CallOption) (*DeleteVolumeResponse, error) // MarkVolumeDeleting admits a chunk volume delete: under the same locks // as every assignment, placement and binding write it refuses @@ -807,6 +812,15 @@ type LifecycleServiceClient interface { MarkVolumeDeleting(ctx context.Context, in *MarkVolumeDeletingRequest, opts ...grpc.CallOption) (*MarkVolumeDeletingResponse, error) AbortVolumeDeleting(ctx context.Context, in *MarkVolumeDeletingRequest, opts ...grpc.CallOption) (*MarkVolumeDeletingResponse, error) CommitVolumeDeleting(ctx context.Context, in *MarkVolumeDeletingRequest, opts ...grpc.CallOption) (*MarkVolumeDeletingResponse, error) + // ReserveVolumeDeletion is the layout volume delete's reservation: it + // commits the delete reservation under the token and stops every later + // grant for the volume, refused while an authority line is live. A + // committed reservation is never given back. + ReserveVolumeDeletion(ctx context.Context, in *MarkVolumeDeletingRequest, opts ...grpc.CallOption) (*MarkVolumeDeletingResponse, error) + // CheckVolumeNoLiveLease is the layout volume delete's check between its + // HEAD read and its update: OK only with the committed reservation and + // no live lease on any line of the volume (granted lines included). + CheckVolumeNoLiveLease(ctx context.Context, in *MarkVolumeDeletingRequest, opts ...grpc.CallOption) (*MarkVolumeDeletingResponse, error) } type lifecycleServiceClient struct { @@ -826,6 +840,15 @@ func (c *lifecycleServiceClient) CreateVolume(ctx context.Context, in *CreateVol return out, nil } +func (c *lifecycleServiceClient) GetVolume(ctx context.Context, in *GetLifecycleVolumeRequest, opts ...grpc.CallOption) (*CreateVolumeResponse, error) { + out := new(CreateVolumeResponse) + err := c.cc.Invoke(ctx, LifecycleService_GetVolume_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *lifecycleServiceClient) DeleteVolume(ctx context.Context, in *DeleteVolumeRequest, opts ...grpc.CallOption) (*DeleteVolumeResponse, error) { out := new(DeleteVolumeResponse) err := c.cc.Invoke(ctx, LifecycleService_DeleteVolume_FullMethodName, in, out, opts...) @@ -862,11 +885,31 @@ func (c *lifecycleServiceClient) CommitVolumeDeleting(ctx context.Context, in *M return out, nil } +func (c *lifecycleServiceClient) ReserveVolumeDeletion(ctx context.Context, in *MarkVolumeDeletingRequest, opts ...grpc.CallOption) (*MarkVolumeDeletingResponse, error) { + out := new(MarkVolumeDeletingResponse) + err := c.cc.Invoke(ctx, LifecycleService_ReserveVolumeDeletion_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *lifecycleServiceClient) CheckVolumeNoLiveLease(ctx context.Context, in *MarkVolumeDeletingRequest, opts ...grpc.CallOption) (*MarkVolumeDeletingResponse, error) { + out := new(MarkVolumeDeletingResponse) + err := c.cc.Invoke(ctx, LifecycleService_CheckVolumeNoLiveLease_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // LifecycleServiceServer is the server API for LifecycleService service. // All implementations must embed UnimplementedLifecycleServiceServer // for forward compatibility type LifecycleServiceServer interface { CreateVolume(context.Context, *CreateVolumeRequest) (*CreateVolumeResponse, error) + // Resolve the durable volume identity without creating or changing it. + GetVolume(context.Context, *GetLifecycleVolumeRequest) (*CreateVolumeResponse, error) DeleteVolume(context.Context, *DeleteVolumeRequest) (*DeleteVolumeResponse, error) // MarkVolumeDeleting admits a chunk volume delete: under the same locks // as every assignment, placement and binding write it refuses @@ -880,6 +923,15 @@ type LifecycleServiceServer interface { MarkVolumeDeleting(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error) AbortVolumeDeleting(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error) CommitVolumeDeleting(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error) + // ReserveVolumeDeletion is the layout volume delete's reservation: it + // commits the delete reservation under the token and stops every later + // grant for the volume, refused while an authority line is live. A + // committed reservation is never given back. + ReserveVolumeDeletion(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error) + // CheckVolumeNoLiveLease is the layout volume delete's check between its + // HEAD read and its update: OK only with the committed reservation and + // no live lease on any line of the volume (granted lines included). + CheckVolumeNoLiveLease(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error) mustEmbedUnimplementedLifecycleServiceServer() } @@ -890,6 +942,9 @@ type UnimplementedLifecycleServiceServer struct { func (UnimplementedLifecycleServiceServer) CreateVolume(context.Context, *CreateVolumeRequest) (*CreateVolumeResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateVolume not implemented") } +func (UnimplementedLifecycleServiceServer) GetVolume(context.Context, *GetLifecycleVolumeRequest) (*CreateVolumeResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetVolume not implemented") +} func (UnimplementedLifecycleServiceServer) DeleteVolume(context.Context, *DeleteVolumeRequest) (*DeleteVolumeResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method DeleteVolume not implemented") } @@ -902,6 +957,12 @@ func (UnimplementedLifecycleServiceServer) AbortVolumeDeleting(context.Context, func (UnimplementedLifecycleServiceServer) CommitVolumeDeleting(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CommitVolumeDeleting not implemented") } +func (UnimplementedLifecycleServiceServer) ReserveVolumeDeletion(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ReserveVolumeDeletion not implemented") +} +func (UnimplementedLifecycleServiceServer) CheckVolumeNoLiveLease(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CheckVolumeNoLiveLease not implemented") +} func (UnimplementedLifecycleServiceServer) mustEmbedUnimplementedLifecycleServiceServer() {} // UnsafeLifecycleServiceServer may be embedded to opt out of forward compatibility for this service. @@ -933,6 +994,24 @@ func _LifecycleService_CreateVolume_Handler(srv interface{}, ctx context.Context return interceptor(ctx, in, info, handler) } +func _LifecycleService_GetVolume_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetLifecycleVolumeRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LifecycleServiceServer).GetVolume(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: LifecycleService_GetVolume_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LifecycleServiceServer).GetVolume(ctx, req.(*GetLifecycleVolumeRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _LifecycleService_DeleteVolume_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteVolumeRequest) if err := dec(in); err != nil { @@ -1005,6 +1084,42 @@ func _LifecycleService_CommitVolumeDeleting_Handler(srv interface{}, ctx context return interceptor(ctx, in, info, handler) } +func _LifecycleService_ReserveVolumeDeletion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MarkVolumeDeletingRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LifecycleServiceServer).ReserveVolumeDeletion(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: LifecycleService_ReserveVolumeDeletion_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LifecycleServiceServer).ReserveVolumeDeletion(ctx, req.(*MarkVolumeDeletingRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _LifecycleService_CheckVolumeNoLiveLease_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MarkVolumeDeletingRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LifecycleServiceServer).CheckVolumeNoLiveLease(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: LifecycleService_CheckVolumeNoLiveLease_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LifecycleServiceServer).CheckVolumeNoLiveLease(ctx, req.(*MarkVolumeDeletingRequest)) + } + return interceptor(ctx, in, info, handler) +} + // LifecycleService_ServiceDesc is the grpc.ServiceDesc for LifecycleService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -1016,6 +1131,10 @@ var LifecycleService_ServiceDesc = grpc.ServiceDesc{ MethodName: "CreateVolume", Handler: _LifecycleService_CreateVolume_Handler, }, + { + MethodName: "GetVolume", + Handler: _LifecycleService_GetVolume_Handler, + }, { MethodName: "DeleteVolume", Handler: _LifecycleService_DeleteVolume_Handler, @@ -1032,6 +1151,14 @@ var LifecycleService_ServiceDesc = grpc.ServiceDesc{ MethodName: "CommitVolumeDeleting", Handler: _LifecycleService_CommitVolumeDeleting_Handler, }, + { + MethodName: "ReserveVolumeDeletion", + Handler: _LifecycleService_ReserveVolumeDeletion_Handler, + }, + { + MethodName: "CheckVolumeNoLiveLease", + Handler: _LifecycleService_CheckVolumeNoLiveLease_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "control.proto", diff --git a/seaweed-block/core/rpc/lifecycleclient/identity.go b/seaweed-block/core/rpc/lifecycleclient/identity.go new file mode 100644 index 0000000000..488fa02207 --- /dev/null +++ b/seaweed-block/core/rpc/lifecycleclient/identity.go @@ -0,0 +1,31 @@ +// Package lifecycleclient resolves volume names through the master. +package lifecycleclient + +import ( + "context" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" +) + +type VolumeResolver interface { + GetVolume(context.Context, *control.GetLifecycleVolumeRequest, ...grpc.CallOption) (*control.CreateVolumeResponse, error) +} + +// ResolveVolume never creates an id or falls back to a name-only filer path. +func ResolveVolume(ctx context.Context, rpc VolumeResolver, name string) (layout.VolumeID, error) { + r, err := rpc.GetVolume(ctx, &control.GetLifecycleVolumeRequest{VolumeId: name}) + if err != nil { + return layout.VolumeID{}, err + } + if r.GetVolumeId() != name { + return layout.VolumeID{}, fmt.Errorf("master resolved volume %q as %q", name, r.GetVolumeId()) + } + id, err := layout.ParseVolumeID(r.GetLayoutId()) + if err != nil { + return layout.VolumeID{}, fmt.Errorf("volume %q has no valid master layout identity; recreate: %w", name, err) + } + return id, nil +} diff --git a/seaweed-block/core/rpc/lifecycleclient/identity_test.go b/seaweed-block/core/rpc/lifecycleclient/identity_test.go new file mode 100644 index 0000000000..0522a44dee --- /dev/null +++ b/seaweed-block/core/rpc/lifecycleclient/identity_test.go @@ -0,0 +1,48 @@ +package lifecycleclient + +import ( + "context" + "testing" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type resolverProbe struct { + reply *control.CreateVolumeResponse + err error + calls int +} + +func (p *resolverProbe) GetVolume(_ context.Context, q *control.GetLifecycleVolumeRequest, _ ...grpc.CallOption) (*control.CreateVolumeResponse, error) { + p.calls++ + if q.GetVolumeId() != "v" { + panic("wrong name") + } + return p.reply, p.err +} + +func TestResolveVolumeNeverInventsAnIdentity(t *testing.T) { + for _, tc := range []struct { + name, volume, id string + err error + good bool + }{ + {"valid", "v", "1234567890abcdef1234567890abcdef", nil, true}, + {"empty", "v", "", nil, false}, + {"malformed", "v", "bad", nil, false}, + {"wrong-name", "other", "1234567890abcdef1234567890abcdef", nil, false}, + {"missing", "", "", status.Error(codes.NotFound, "missing"), false}, + {"transport", "", "", status.Error(codes.Unavailable, "unavailable"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + p := &resolverProbe{reply: &control.CreateVolumeResponse{VolumeId: tc.volume, LayoutId: tc.id}, err: tc.err} + id, err := ResolveVolume(context.Background(), p, "v") + if p.calls != 1 || (err == nil) != tc.good || (!tc.good && !id.IsZero()) { + t.Fatalf("calls=%d id=%s err=%v", p.calls, id, err) + } + }) + } +} diff --git a/seaweed-block/core/rpc/proto/control.proto b/seaweed-block/core/rpc/proto/control.proto index 856ebbbd8e..a876b246cb 100644 --- a/seaweed-block/core/rpc/proto/control.proto +++ b/seaweed-block/core/rpc/proto/control.proto @@ -95,6 +95,8 @@ service ClusterEvidenceService { // epoch, endpoint_version, readiness, or primary facts. service LifecycleService { rpc CreateVolume(CreateVolumeRequest) returns (CreateVolumeResponse); + // Resolve the durable volume identity without creating or changing it. + rpc GetVolume(GetLifecycleVolumeRequest) returns (CreateVolumeResponse); rpc DeleteVolume(DeleteVolumeRequest) returns (DeleteVolumeResponse); // MarkVolumeDeleting admits a chunk volume delete: under the same locks // as every assignment, placement and binding write it refuses @@ -108,6 +110,15 @@ service LifecycleService { rpc MarkVolumeDeleting(MarkVolumeDeletingRequest) returns (MarkVolumeDeletingResponse); rpc AbortVolumeDeleting(MarkVolumeDeletingRequest) returns (MarkVolumeDeletingResponse); rpc CommitVolumeDeleting(MarkVolumeDeletingRequest) returns (MarkVolumeDeletingResponse); + // ReserveVolumeDeletion is the layout volume delete's reservation: it + // commits the delete reservation under the token and stops every later + // grant for the volume, refused while an authority line is live. A + // committed reservation is never given back. + rpc ReserveVolumeDeletion(MarkVolumeDeletingRequest) returns (MarkVolumeDeletingResponse); + // CheckVolumeNoLiveLease is the layout volume delete's check between its + // HEAD read and its update: OK only with the committed reservation and + // no live lease on any line of the volume (granted lines included). + rpc CheckVolumeNoLiveLease(MarkVolumeDeletingRequest) returns (MarkVolumeDeletingResponse); } // FailbackService — disabled-by-default authority failback endpoint. @@ -490,6 +501,11 @@ message CreateVolumeRequest { string pvc_uid = 7; string protocol = 8; // "iscsi" default | "nvme" string frontend_transport = 9; // NVMe: "tcp" default | "rdma" + uint32 block_size = 10; // omitted: 4096, persisted on first create + uint64 chunk_bytes = 11; // omitted: 4 MiB, persisted on first create + string source_volume = 12; // restore only: source lifecycle name + string source_snapshot = 13; // restore only: named source snapshot + string create_request_id = 14; // restore retry identity, bound to name/source/snapshot } message CreateVolumeResponse { @@ -502,6 +518,14 @@ message CreateVolumeResponse { string pvc_uid = 7; string protocol = 8; // "iscsi" default | "nvme" string frontend_transport = 9; // NVMe: "tcp" default | "rdma" + string layout_id = 10; // master-minted, immutable 32 lower-case hex digits + uint32 block_size = 11; + uint64 chunk_bytes = 12; + bool store_ready = 13; // false: created, store not ready; retry CreateVolume +} + +message GetLifecycleVolumeRequest { + string volume_id = 1; // lifecycle name } message DeleteVolumeRequest { diff --git a/seaweed-block/core/storage/chunk_abort_upload_bytes_test.go b/seaweed-block/core/storage/chunk_abort_upload_bytes_test.go index e18109267b..ed13bb9e6c 100644 --- a/seaweed-block/core/storage/chunk_abort_upload_bytes_test.go +++ b/seaweed-block/core/storage/chunk_abort_upload_bytes_test.go @@ -72,5 +72,5 @@ func TestChunkStageV3_MidUploadAbortReducesRetryBytes(t *testing.T) { t.Fatalf("retry frontier=%d want%d", result.Head.RemoteLSN, frontier) } assertImage(t, "retry image", f.imageOf(t, result.Head), want) - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } diff --git a/seaweed-block/core/storage/chunk_birth.go b/seaweed-block/core/storage/chunk_birth.go deleted file mode 100644 index 89e3991e3f..0000000000 --- a/seaweed-block/core/storage/chunk_birth.go +++ /dev/null @@ -1,15 +0,0 @@ -package storage - -// The caller holds captureMu exclusive, with no layer state lock held. -// An owned-map max is conservative: recovery can drop an unacked suffix -// while retaining its maximum. Bound it by the same-barrier cut frontier; -// the captured image has no later writes. Preserve lower inherited births. -func (l *chunkLayerImpl) captureBirths(candidates map[uint64]bool, frontier uint64) map[uint64]uint64 { - out := make(map[uint64]uint64, len(candidates)) - l.s.mu.RLock() - defer l.s.mu.RUnlock() - for idx := range candidates { - out[idx] = min(l.s.v3.mapEntries[idx].LSN, frontier) - } - return out -} diff --git a/seaweed-block/core/storage/chunk_birth_manifest_test.go b/seaweed-block/core/storage/chunk_birth_manifest_test.go deleted file mode 100644 index 062f36e959..0000000000 --- a/seaweed-block/core/storage/chunk_birth_manifest_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package storage_test - -import ( - "bytes" - "context" - "fmt" - "path" - "sort" - "strings" - "sync" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" - "google.golang.org/protobuf/proto" -) - -// Only the metadata/blob transports are in memory; capture, recovery, -// PrepareManifest, segment encoding, CAS and resolved reads are production. -type birthFiler struct { - mu sync.Mutex - entries map[string]*filerpb.Entry -} - -func (f *birthFiler) LookupEntry(_ context.Context, d, n string) (*filerpb.Entry, error) { - f.mu.Lock() - defer f.mu.Unlock() - e := f.entries[path.Join(d, n)] - if e == nil { - return nil, chunkstore.ErrNotFound - } - return proto.Clone(e).(*filerpb.Entry), nil -} -func (f *birthFiler) CreateEntry(_ context.Context, d string, e *filerpb.Entry, excl bool) error { - f.mu.Lock() - defer f.mu.Unlock() - k := path.Join(d, e.Name) - if excl && f.entries[k] != nil { - return chunkstore.ErrExists - } - f.entries[k] = proto.Clone(e).(*filerpb.Entry) - return nil -} -func (f *birthFiler) UpdateEntry(_ context.Context, d string, e *filerpb.Entry, expected map[string][]byte) error { - f.mu.Lock() - defer f.mu.Unlock() - k := path.Join(d, e.Name) - old := f.entries[k] - if old == nil { - return chunkstore.ErrNotFound - } - for k, v := range expected { - if !bytes.Equal(old.Extended[k], v) { - return chunkstore.ErrPrecondition - } - } - f.entries[k] = proto.Clone(e).(*filerpb.Entry) - return nil -} -func (f *birthFiler) DeleteEntry(_ context.Context, d, n string, expected map[string][]byte) error { - f.mu.Lock() - defer f.mu.Unlock() - k := path.Join(d, n) - for key, v := range expected { - if f.entries[k] == nil || !bytes.Equal(f.entries[k].Extended[key], v) { - return chunkstore.ErrPrecondition - } - } - delete(f.entries, k) - return nil -} -func (f *birthFiler) ListEntries(_ context.Context, d, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { - f.mu.Lock() - defer f.mu.Unlock() - var out []*filerpb.Entry - for k, e := range f.entries { - if path.Dir(k) == d && strings.HasPrefix(e.Name, prefix) && e.Name > after { - out = append(out, proto.Clone(e).(*filerpb.Entry)) - } - } - sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) - if limit > 0 && len(out) > int(limit) { - out = out[:limit] - } - return out, nil -} - -type birthBlobs struct { - mu sync.Mutex - data map[string][]byte -} - -func (b *birthBlobs) Put(_ context.Context, d []byte) (string, error) { - b.mu.Lock() - defer b.mu.Unlock() - id := fmt.Sprint(len(b.data) + 1) - b.data[id] = bytes.Clone(d) - return id, nil -} -func (b *birthBlobs) Get(_ context.Context, id string) ([]byte, error) { - b.mu.Lock() - defer b.mu.Unlock() - d, ok := b.data[id] - if !ok { - return nil, chunkstore.ErrNotFound - } - return bytes.Clone(d), nil -} - -func TestChunkBirthDroppedSuffixPublishesWithRealManifest(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - f := &birthFiler{entries: map[string]*filerpb.Entry{}} - b := &birthBlobs{data: map[string][]byte{}} - remote, err := chunkstore.NewChunkRemote(f, b, "/birth/v1") - if err != nil { - t.Fatal(err) - } - s := storage.DroppedSuffixBirthStoreForTest(t, remote) - layer, err := storage.AttachChunkLayer(s, remote, storage.ChunkLayerConfig{ChunkBlocks: 4, Epoch: 2, Holder: "host-a"}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = layer.Close() }) - cut, err := layer.Cut(ctx) - if err != nil { - t.Fatalf("reused-LSN cut must publish without another write: %v", err) - } - h, err := remote.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - if cut.Head.RemoteLSN != 2 || h.RemoteLSN != 2 || h.Chunks[0].BirthLSN != 2 || h.Segments[0].MaxBirthLSN != 2 { - t.Fatalf("cut-image frontier/birth: %+v", h) - } - data, err := remote.Get(ctx, h.Chunks[0].Key) - if err != nil { - t.Fatal(err) - } - want := make([]byte, 4*4096) - copy(want[4096:], bytes.Repeat([]byte{0xB2}, 4096)) - if !bytes.Equal(data, want) { - t.Fatal("published cut differs from recovered B2 image") - } - // The real builder's future-birth guard must still reject corrupt proposals. - invalid := h - invalid.Chunks = map[uint64]storage.ChunkRef{0: h.Chunks[0]} - ref := invalid.Chunks[0] - ref.BirthLSN = 3 - invalid.Chunks[0] = ref - if _, _, err := remote.PrepareManifest(ctx, h, invalid, 4*4096); err == nil { - t.Fatal("future birth was accepted") - } -} diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index ca7291c56c..63354dc528 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -593,7 +593,7 @@ func (l *chunkLayerImpl) copyCOWEntry(w *cutCOWWindow, idx uint64) (capturedChun // Each worker owns one immutable image from local read through remote Put. // Once copied, its entry is done: guest writes need not wait for remote I/O. // The window remains installed for candidates not yet read by a worker. -func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, recent, versions map[uint64]uint64, head chunkHead) ([]capturedChunk, []string, error) { +func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, recent, versions map[uint64]uint64, head chunkHead) ([]capturedChunk, error) { parent := ctx abortStop := context.AfterFunc(parent, func() { w.abort(parent.Err()) }) defer abortStop() @@ -621,7 +621,7 @@ func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, rec } } order := hotChunkKeys(indices, recent) - out, intents, err := l.streamCutPayloads(ctx, order, head, false, func(ctx context.Context, idx uint64) (capturedChunk, error) { + out, err := l.streamCutPayloads(ctx, order, head, false, func(ctx context.Context, idx uint64) (capturedChunk, error) { c, ok, err := l.copyCOWEntry(w, idx) if err != nil { return capturedChunk{}, err @@ -649,9 +649,9 @@ func (l *chunkLayerImpl) copyCOWWindow(ctx context.Context, w *cutCOWWindow, rec w.mu.Unlock() err = errors.Join(err, w.join()) if err != nil { - return nil, intents, err + return nil, err } - return out, intents, nil + return out, nil } // Creation is single-owner, but no allocation/lifetime lock spans filesystem I/O. diff --git a/seaweed-block/core/storage/chunk_cut_crash_test.go b/seaweed-block/core/storage/chunk_cut_crash_test.go index fb346d9451..4322469358 100644 --- a/seaweed-block/core/storage/chunk_cut_crash_test.go +++ b/seaweed-block/core/storage/chunk_cut_crash_test.go @@ -82,11 +82,19 @@ func (r *crashRemote) Delete(ctx context.Context, key string) error { return r.fakeChunkRemote.Delete(ctx, key) } -func (r *crashRemote) PutIntent(ctx context.Context, in chunkIntent) (string, error) { +func (r *crashRemote) Begin(ctx context.Context) (string, error) { if r.isDead() { return "", errProcessDead } - return r.fakeChunkRemote.PutIntent(ctx, in) + return r.fakeChunkRemote.Begin(ctx) +} + +// Abort from a dead process never reaches the remote. +func (r *crashRemote) Abort() { + if r.isDead() { + return + } + r.fakeChunkRemote.Abort() } func (r *crashRemote) Get(ctx context.Context, key string) ([]byte, error) { @@ -103,20 +111,6 @@ func (r *crashRemote) GetHead(ctx context.Context) (chunkHead, error) { return r.fakeChunkRemote.GetHead(ctx) } -func (r *crashRemote) ListIntents(ctx context.Context) ([]chunkIntent, error) { - if r.isDead() { - return nil, errProcessDead - } - return r.fakeChunkRemote.ListIntents(ctx) -} - -func (r *crashRemote) DeleteIntent(ctx context.Context, id string) error { - if r.isDead() { - return errProcessDead - } - return r.fakeChunkRemote.DeleteIntent(ctx, id) -} - // cutCrashImage is the volume's content as a byte image. func cutCrashImage(t *testing.T, s *WALStore) []byte { t.Helper() @@ -240,9 +234,7 @@ func TestChunkCutCrashAtEachStage(t *testing.T) { if !bytes.Equal(f.imageOf(t, final), want) { t.Fatalf("the cut after the restart (gen %d) does not publish the volume as it is", final.Gen) } - if intents, err := f.ListIntents(ctx); err == nil { - t.Logf("stage %q: HEAD gen %d -> crash -> %d -> %d after the next cut; %d intent(s) left", st.name, old.Gen, head.Gen, final.Gen, len(intents)) - } + t.Logf("stage %q: HEAD gen %d -> crash -> %d -> %d after the next cut; open session %q", st.name, old.Gen, head.Gen, final.Gen, f.openSession()) }) } } diff --git a/seaweed-block/core/storage/chunk_birth_test.go b/seaweed-block/core/storage/chunk_cut_image_test.go similarity index 56% rename from seaweed-block/core/storage/chunk_birth_test.go rename to seaweed-block/core/storage/chunk_cut_image_test.go index 48885d8465..2e181ac838 100644 --- a/seaweed-block/core/storage/chunk_birth_test.go +++ b/seaweed-block/core/storage/chunk_cut_image_test.go @@ -8,36 +8,7 @@ import ( "time" ) -func TestChunkBirthBASEUsesInheritedFrontierIncludingZero(t *testing.T) { - for _, frontier := range []uint64{0, 7} { - t.Run(string(rune('0'+frontier)), func(t *testing.T) { - s, _, l := mappedBASELayerV3(t) - h, err := s.BeginBaseInstall(frontier, idA) - if err != nil { - t.Fatal(err) - } - if err := h.WriteBase(5, blk(0x55)); err != nil { - t.Fatal(err) - } - if err := h.MarkBaseComplete(); err != nil { - t.Fatal(err) - } - newest, err := s.Write(0, blk(0x41)) - if err != nil { - t.Fatal(err) - } - cut, err := l.Cut(ctTimeout(t)) - if err != nil { - t.Fatal(err) - } - if cut.Head.Chunks[1].BirthLSN != frontier || cut.Head.Chunks[0].BirthLSN != newest { - t.Fatalf("BASE birth drifted with unrelated WAL writes: %+v, inherited %d", cut.Head, frontier) - } - }) - } -} - -func TestChunkBirthCOWDoesNotObservePostBarrierWrite(t *testing.T) { +func TestChunkCutCOWDoesNotObservePostBarrierWrite(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() cfg := ctConfig(1) @@ -48,7 +19,7 @@ func TestChunkBirthCOWDoesNotObservePostBarrierWrite(t *testing.T) { if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil { t.Fatal(err) } - before, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)) + _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)) if err != nil { t.Fatal(err) } @@ -75,7 +46,7 @@ func TestChunkBirthCOWDoesNotObservePostBarrierWrite(t *testing.T) { }) go func() { defer close(joined); _, err := l.Cut(ctx); done <- err }() cowWaitSignal(t, entered, "copy after the birth barrier") - after, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x43)) + _, err = s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x43)) if err != nil { t.Fatal(err) } @@ -85,17 +56,17 @@ func TestChunkBirthCOWDoesNotObservePostBarrierWrite(t *testing.T) { } cowWaitSignal(t, joined, "birth COW join") first := f.installedHeads()[0] - if first.Chunks[1].BirthLSN != before || !bytes.Equal(f.imageOf(t, first)[ctChunkBlocks*ctBlockSize:(ctChunkBlocks+1)*ctBlockSize], makeBlock(ctBlockSize, 0x42)) { - t.Fatal("post-barrier write changed the saved image or its birth") + if !bytes.Equal(f.imageOf(t, first)[ctChunkBlocks*ctBlockSize:(ctChunkBlocks+1)*ctBlockSize], makeBlock(ctBlockSize, 0x42)) { + t.Fatal("post-barrier write changed the saved image") } l.testCOWRead = nil second, err := l.Cut(ctTimeout(t)) - if err != nil || second.Head.Chunks[1].BirthLSN != after { - t.Fatalf("next version lost post-barrier birth: %+v %v", second, err) + if err != nil || !bytes.Equal(f.imageOf(t, second.Head)[ctChunkBlocks*ctBlockSize:(ctChunkBlocks+1)*ctBlockSize], makeBlock(ctBlockSize, 0x43)) { + t.Fatalf("the next version lost the post-barrier write: %+v %v", second, err) } } -func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { +func TestChunkCutKeepsColdChunksAndDeletesZeroChunks(t *testing.T) { for _, bound := range []int{0, 1} { t.Run(string(rune('0'+bound)), func(t *testing.T) { s, _ := newChunkTestStore(t) @@ -104,8 +75,7 @@ func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { cfg.FreshFromHead = true cfg.BarrierBound = bound l := mustAttach(t, s, f, cfg) - x, err := s.Write(0, makeBlock(ctBlockSize, 0x41)) - if err != nil { + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil { t.Fatal(err) } if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42)); err != nil { @@ -119,10 +89,10 @@ func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { if err != nil { t.Fatal(err) } - if first.Head.Chunks[0].BirthLSN != x || first.Head.Chunks[1].BirthLSN != y || first.Head.Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y { - t.Fatalf("births did not preserve distinct local write frontiers: %+v, want %d/%d", first.Head, x, y) + if first.Head.Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y { + t.Fatalf("first cut: %+v, want position %d", first.Head, y) } - z, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x44)) + _, err = s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x44)) if err != nil { t.Fatal(err) } @@ -130,8 +100,8 @@ func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { if err != nil { t.Fatal(err) } - if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1].BirthLSN != z { - t.Fatal("rewrite changed a cold chunk birth or failed to advance the changed version") + if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1] == first.Head.Chunks[1] { + t.Fatal("rewrite changed a cold chunk or did not publish the changed one") } for _, lba := range []uint32{ctChunkBlocks, ctChunkBlocks + 1} { if _, err := s.Write(lba, makeBlock(ctBlockSize, 0)); err != nil { @@ -143,7 +113,7 @@ func TestChunkBirthTracksNewestLocalWriteAtCut(t *testing.T) { t.Fatal(err) } if _, exists := third.Head.Chunks[1]; exists || third.Head.Chunks[0] != first.Head.Chunks[0] { - t.Fatal("zero-chunk deletion retained a reference or changed the cold birth") + t.Fatal("zero-chunk deletion retained a reference or changed the cold chunk") } }) } diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index c166290edd..dae777d5f7 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -39,21 +39,19 @@ func hotChunkKeys(indices map[uint64]bool, recent map[uint64]uint64) []uint64 { // Preallocate metadata keys once per round. Each worker owns one immutable // image through PUT/retry, then reads its next candidate independently of slow -// workers. One durable intent covers all candidate keys before the first PUT; -// unused keys are harmless and retain no payload memory. +// workers. The holder's session is begun before the first PUT; unused keys +// are harmless and retain no payload memory. // // staging says the batch is a staging round (before the barrier): each chunk // it finishes is counted in Stats.StagedChunks as it finishes. -func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, head chunkHead, staging bool, read func(context.Context, uint64) (capturedChunk, error)) ([]capturedChunk, []string, error) { +func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, head chunkHead, staging bool, read func(context.Context, uint64) (capturedChunk, error)) ([]capturedChunk, error) { out := make([]capturedChunk, len(batch)) keys := make([]string, len(batch)) for i, idx := range batch { keys[i] = l.newKey(idx) } - var intents []string var once sync.Once - var intent string - var intentErr error + var beginErr error put := l.beginPutRound(len(batch)) err := l.uploadBatch(ctx, len(batch), func(ctx context.Context, i int) error { c, err := read(ctx, batch[i]) @@ -62,17 +60,11 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, } ref, had := head.Chunks[c.idx] if !c.zero && !(had && ref.SHA256 == c.sum && !l.owning(c.idx)) { - c.key, c.size = keys[i], len(c.data) - once.Do(func() { - intent, intentErr = l.remote.PutIntent(ctx, chunkIntent{Gen: head.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) - if intentErr == nil { - intents = append(intents, intent) - } - }) - if intentErr != nil { - return fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, intentErr) + c.key, c.size = l.keyFor(c.idx, c.sum, keys[i]), len(c.data) + once.Do(func() { _, beginErr = l.remote.Begin(ctx) }) + if beginErr != nil { + return fmt.Errorf("storage: capture session: %w: %w", errChunkRemoteUnavailable, beginErr) } - c.intent = intent if err := l.putCapturedWith(ctx, c.key, c.data, func(ctx context.Context) error { return put(ctx, i, c.key, c.data) }); err != nil { return fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } @@ -83,13 +75,13 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, return nil }) if err != nil { - return nil, intents, err + return nil, err } - return out, intents, nil + return out, nil } -func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, versions map[uint64]uint64, head chunkHead, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) { - out, intents, err := l.streamCutPayloads(ctx, batch, head, true, func(ctx context.Context, idx uint64) (capturedChunk, error) { +func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, versions map[uint64]uint64, head chunkHead, st *chunkCutStats) (map[uint64]stagedChunk, error) { + out, err := l.streamCutPayloads(ctx, batch, head, true, func(ctx context.Context, idx uint64) (capturedChunk, error) { data, err := l.readChunk(idx) if err != nil { return capturedChunk{}, err @@ -100,7 +92,7 @@ func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, return capturedChunk{idx: idx, version: versions[idx], data: data, sum: sha256.Sum256(data), zero: isAllZero(data)}, nil }) if err != nil { - return nil, intents, err + return nil, err } chunks := make(map[uint64]stagedChunk, len(out)) for _, c := range out { @@ -110,7 +102,7 @@ func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64, st.UploadedBytes += int64(c.size) } } - return chunks, intents, nil + return chunks, nil } // Only immutable metadata survives an attempt. The intent remains a GC root diff --git a/seaweed-block/core/storage/chunk_cut_progress_test.go b/seaweed-block/core/storage/chunk_cut_progress_test.go index 97a0b0784b..7bd684465e 100644 --- a/seaweed-block/core/storage/chunk_cut_progress_test.go +++ b/seaweed-block/core/storage/chunk_cut_progress_test.go @@ -68,7 +68,7 @@ func TestChunkStageV3_AbortedPointReusesUploads(t *testing.T) { if bytes.Equal(f.imageOf(t, r.Head), f.imageOf(t, before)) { t.Fatal("retry did not publish the submitted changes") } - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } // The changed image is four times the spill cap; only one hot chunk keeps @@ -119,7 +119,7 @@ func TestChunkStageV3_FourTimesCapConvergesUnderSteadyWrites(t *testing.T) { t.Fatal("large dirty image bypassed pre-copy") } assertEveryHeadIsPrefixImage(t, f, w) - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } // Each of two deadlines interrupts the third upload, after two immutable chunks @@ -214,5 +214,5 @@ func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) { if previous != 4 { t.Fatalf("reusable chunks=%d", previous) } - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } diff --git a/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go b/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go index 5f1d1a5dc6..f90f7f6547 100644 --- a/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go +++ b/seaweed-block/core/storage/chunk_cut_revoke_reuse_test.go @@ -89,5 +89,5 @@ func TestCutRevokedMidUploadKeepsItsUploads(t *testing.T) { r.bytes, dirty-2, (dirty-2)*ctChunkBytes, dirty*ctChunkBytes) } assertImage(t, "published image", f.imageOf(t, result.Head), w.imageAt(s.NextLSN()-1)) - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index 9151a70438..ac19aa1526 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -96,63 +96,54 @@ type fakeChunkRemote struct { beforeCAS func(f *fakeChunkRemote) // runs once, under mu, before the next CAS is decided onGetHead func(f *fakeChunkRemote) // runs under mu inside every GetHead while set (a read that blocks across a change) afterCAS func(f *fakeChunkRemote) // runs once, under mu, after the next CAS is decided - intents map[string]chunkIntent deferred []deferredCAS - failPutIntent error // PutIntent fails without writing - failDeleteIntent int // the next N DeleteIntent calls fail without deleting - putIntents []chunkIntent // every intent written, in order + // session is the open cut session ("" = none); sessions counts the + // Begins that opened one, aborts the Aborts that ended one. + session string + sessions, aborts int + failBegin error // Begin fails without opening a session } func newFakeChunkRemote() *fakeChunkRemote { - return &fakeChunkRemote{objs: map[string][]byte{}, putBytes: map[string][]byte{}, everStored: map[string]bool{}, intents: map[string]chunkIntent{}} + return &fakeChunkRemote{objs: map[string][]byte{}, putBytes: map[string][]byte{}, everStored: map[string]bool{}} } -func (f *fakeChunkRemote) PutIntent(ctx context.Context, in chunkIntent) (string, error) { - for _, k := range in.Keys { - if err := validChunkKey(k); err != nil { - return "", err - } - } - id, err := newChunkIntentID(in.Gen) - if err != nil { - return "", err - } - in.ID, in.CreatedNs, in.Keys = id, time.Now().UnixNano(), append([]string(nil), in.Keys...) +// Begin opens the cut's session ("begin:"), or replays the open +// one ("begin:replay"). +func (f *fakeChunkRemote) Begin(ctx context.Context) (string, error) { f.mu.Lock() defer f.mu.Unlock() - if f.failPutIntent != nil { - f.ops = append(f.ops, "putintent:fail") - return "", f.failPutIntent + if f.failBegin != nil { + f.ops = append(f.ops, "begin:fail") + return "", f.failBegin } - f.ops = append(f.ops, "putintent:"+id) - f.intents[id] = in - f.putIntents = append(f.putIntents, in) - return id, nil + if f.session != "" { + f.ops = append(f.ops, "begin:replay") + return f.session, nil + } + f.sessions++ + f.session = fmt.Sprintf("s%d", f.sessions) + f.ops = append(f.ops, "begin:"+f.session) + return f.session, nil } -func (f *fakeChunkRemote) DeleteIntent(ctx context.Context, id string) error { +// Abort ends the open session without a commit ("abort:"). +func (f *fakeChunkRemote) Abort() { f.mu.Lock() defer f.mu.Unlock() - if f.failDeleteIntent > 0 { - f.failDeleteIntent-- - f.ops = append(f.ops, "deleteintent:fail:"+id) - return errors.New("fake remote: injected DeleteIntent failure") + if f.session != "" { + f.ops = append(f.ops, "abort:"+f.session) + f.aborts++ + f.session = "" } - f.ops = append(f.ops, "deleteintent:"+id) - delete(f.intents, id) - return nil } -func (f *fakeChunkRemote) ListIntents(ctx context.Context) ([]chunkIntent, error) { +// openSession is the open session ("" = none). +func (f *fakeChunkRemote) openSession() string { f.mu.Lock() defer f.mu.Unlock() - out := make([]chunkIntent, 0, len(f.intents)) - for _, in := range f.intents { - in.Keys = append([]string(nil), in.Keys...) - out = append(out, in) - } - return out, nil + return f.session } func (f *fakeChunkRemote) Put(ctx context.Context, key string, data []byte) error { @@ -305,6 +296,7 @@ func (f *fakeChunkRemote) CASHead(ctx context.Context, expected chunkHeadVersion } } f.installLocked(next) + f.session = "" // the commit ends the cut's session if mode == casAppliedLost { outcome = "cas:lost" return 0, errFakeCASResponseLost @@ -386,7 +378,7 @@ func (f *fakeChunkRemote) seedHead(t *testing.T, image []byte, remoteLSN, epoch key := fmt.Sprintf("seed/%d", idx) f.objs[key] = append([]byte(nil), c...) f.everStored[key] = true - head.Chunks[uint64(idx)] = chunkRef{Key: key, SHA256: sha256.Sum256(c), Encoding: "full", BirthLSN: remoteLSN} + head.Chunks[uint64(idx)] = chunkRef{Key: key, SHA256: sha256.Sum256(c), Encoding: "full"} } f.installLocked(head) } diff --git a/seaweed-block/core/storage/chunk_fixed_spans_test.go b/seaweed-block/core/storage/chunk_fixed_spans_test.go index 1576aae80c..aca7563289 100644 --- a/seaweed-block/core/storage/chunk_fixed_spans_test.go +++ b/seaweed-block/core/storage/chunk_fixed_spans_test.go @@ -12,19 +12,11 @@ type fixedSpanRemote struct { delay time.Duration } -func (r *fixedSpanRemote) PrepareManifest(_ context.Context, _ ChunkHead, next ChunkHead, _ uint64) (ChunkHead, []string, error) { - time.Sleep(r.delay) - return next, nil, nil -} func (r *fixedSpanRemote) CASHead(ctx context.Context, v ChunkHeadVersion, h ChunkHead) (uint64, error) { time.Sleep(r.delay) return r.fakeChunkRemote.CASHead(ctx, v, h) } -func (r *fixedSpanRemote) DeleteIntent(ctx context.Context, id string) error { - time.Sleep(r.delay) - return r.fakeChunkRemote.DeleteIntent(ctx, id) -} func TestChunkCutFixedSpansAttributeManifestAndCleanup(t *testing.T) { s, f, l, w := precopyLayer(t, 1024, 0) delay := 10 * time.Millisecond @@ -34,7 +26,7 @@ func TestChunkCutFixedSpansAttributeManifestAndCleanup(t *testing.T) { if err != nil { t.Fatal(err) } - for _, name := range []string{"ManifestNs", "IntentCleanupNs"} { + for _, name := range []string{"CASWriteNs"} { v := reflect.ValueOf(r.Stats).FieldByName(name) if !v.IsValid() || time.Duration(v.Int()) < delay { t.Fatalf("missing fixed span %s: %+v", name, r.Stats) @@ -44,7 +36,7 @@ func TestChunkCutFixedSpansAttributeManifestAndCleanup(t *testing.T) { t.Fatal("no fixed sample") } parts := reflect.ValueOf(l.precopySamples[len(l.precopySamples)-1].parts) - for _, name := range []string{"Manifest", "IntentCleanup"} { + for _, name := range []string{"HeadCAS"} { v := parts.FieldByName(name) if !v.IsValid() || time.Duration(v.Int()) < delay { t.Fatalf("missing selected fixed part %s", name) diff --git a/seaweed-block/core/storage/chunk_frontier.go b/seaweed-block/core/storage/chunk_frontier.go index e002cd84c9..e456ac4d7b 100644 --- a/seaweed-block/core/storage/chunk_frontier.go +++ b/seaweed-block/core/storage/chunk_frontier.go @@ -45,6 +45,38 @@ func (s *WALStore) seedChunkFrontierV3(lsn uint64) error { return err } +// CanSeedChunkFrontier reports whether SeedChunkFrontier(lsn) may proceed +// on this store as it is now: the one precondition the seed itself checks, +// so a caller can refuse a position before it writes anything elsewhere. +func (s *WALStore) CanSeedChunkFrontier(lsn uint64) error { + s.mu.Lock() + defer s.mu.Unlock() + return s.seedRefusalLocked(lsn) +} + +// seedRefusalLocked is the seed precondition (the caller holds s.mu): an +// open, unattached store without a sticky fault, no local writes beyond its +// checkpoint, no install, an lsn at or above the checkpoint with room for a +// next LSN, and the owned map for the checkpoint coverage. +func (s *WALStore) seedRefusalLocked(lsn uint64) error { + v := s.v3 + if s.closed || s.chunk.Load() != nil { + return errors.New("storage: seed frontier requires an open, unattached store") + } + if err := s.stickyIOFault(); err != nil { + return err + } + d := v.pub.current() + if lsn == ^uint64(0) || lsn < d.CheckpointLSN || v.appended.Load() > d.CheckpointLSN || + s.walHead > s.checkpointLSN || s.nextLSN > lsn+1 || d.BaseState != BaseNone { + return errors.New("storage: seed frontier cannot replace local writes, an install or wrap LSN") + } + if v.ownedMap == nil { + return fmt.Errorf("%w: a v3 seed needs the owned map for its checkpoint coverage", errV3NotYet) + } + return nil +} + // seedTimes are the stage boundaries of one v3 seed (zero: not reached). type seedTimes struct{ start, locked, validated, synced, published time.Time } @@ -57,24 +89,11 @@ func (s *WALStore) seedChunkFrontierV3Locked(lsn uint64, t *seedTimes) (err erro defer s.lifecycleMu.RUnlock() t.locked = time.Now() s.mu.Lock() - if s.closed || s.chunk.Load() != nil { - s.mu.Unlock() - return errors.New("storage: seed frontier requires an open, unattached store") - } - if err := s.stickyIOFault(); err != nil { + if err := s.seedRefusalLocked(lsn); err != nil { s.mu.Unlock() return err } d := v.pub.current() - if lsn == ^uint64(0) || lsn < d.CheckpointLSN || v.appended.Load() > d.CheckpointLSN || - s.walHead > s.checkpointLSN || s.nextLSN > lsn+1 || d.BaseState != BaseNone { - s.mu.Unlock() - return errors.New("storage: seed frontier cannot replace local writes, an install or wrap LSN") - } - if v.ownedMap == nil { - s.mu.Unlock() - return fmt.Errorf("%w: a v3 seed needs the owned map for its checkpoint coverage", errV3NotYet) - } if d.CheckpointLSN == lsn && d.W >= lsn && s.nextLSN == lsn+1 { s.mu.Unlock() return nil diff --git a/seaweed-block/core/storage/chunk_head_belt_test.go b/seaweed-block/core/storage/chunk_head_belt_test.go index 2d4d455e7d..979bbe05eb 100644 --- a/seaweed-block/core/storage/chunk_head_belt_test.go +++ b/seaweed-block/core/storage/chunk_head_belt_test.go @@ -5,26 +5,11 @@ import ( "context" "errors" "testing" - "time" ) // The fake's direct root replacement models a delayed request accepted at a // second serialization point; it deliberately bypasses the first filer's CAS. -func TestHeadBeltTakeoverRefusesLateOldCAS(t *testing.T) { - f := newFakeChunkRemote() - f.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} - f.afterCAS = func(f *fakeChunkRemote) { - f.head = chunkHead{Gen: 2, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} - } - ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) - defer cancel() - _, err := ClaimChunkHead(ctx, f, ChunkLayerConfig{Epoch: 2, Holder: "new"}) - if !errors.Is(err, ErrChunkLayerFenced) { - t.Fatalf("late old CAS allowed takeover to serve: %v", err) - } -} - -func TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier(t *testing.T) { +func TestHeadBeltOldCASUnconfirmedKeepsSessionAndFrontier(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() layer := mustAttach(t, s, f, ctConfig(1)) @@ -36,6 +21,7 @@ func TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier(t *testing.T) { t.Fatal(err) } f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errors.New("confirmation unavailable near lease horizon") } + mark := len(f.stats().ops) _, err := layer.Cut(ctTimeout(t)) if err == nil { t.Fatal("unconfirmed CAS returned success") @@ -43,8 +29,10 @@ func TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier(t *testing.T) { if layer.RemoteLSN() != 0 { t.Fatal("unconfirmed CAS advanced remoteLSN", layer.RemoteLSN()) } - if len(liveIntents(t, f)) == 0 { - t.Fatal("unconfirmed CAS removed its intent") + // The CAS landed (its commit ended the session at the remote) but the + // layer could not confirm it: the layer must not Abort. + if n := countOps(opsSince(f, mark), "abort:"); n != 0 { + t.Fatal("unconfirmed CAS aborted its session") } if got, err := s.Read(0); err != nil || !bytes.Equal(got, want) { t.Fatalf("local acknowledged bytes changed: %v", err) @@ -52,8 +40,8 @@ func TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier(t *testing.T) { if err := layer.Close(); err != nil { t.Fatal(err) } - if len(liveIntents(t, f)) == 0 { - t.Fatal("Close removed unconfirmed publication roots") + if n := countOps(opsSince(f, mark), "abort:"); n != 0 { + t.Fatal("Close aborted an unconfirmed commit's session") } } @@ -79,8 +67,9 @@ func TestHeadBeltLowerEpochConflictFencesWithoutCleanup(t *testing.T) { if layer.RemoteLSN() != frontier { t.Fatal("refused cut advanced remote frontier") } - if len(liveIntents(t, f)) == 0 { - t.Fatal("fenced cut removed its intent") + // fenced: what it staged is dropped, and with it its own session + if f.openSession() != "" { + t.Fatal("fenced cut kept its session") } calls := f.stats().cas if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, ErrChunkLayerFenced) || f.stats().cas != calls { @@ -89,8 +78,8 @@ func TestHeadBeltLowerEpochConflictFencesWithoutCleanup(t *testing.T) { if err := layer.Close(); err != nil { t.Fatal(err) } - if len(liveIntents(t, f)) == 0 { - t.Fatal("Close removed fenced publication roots") + if f.openSession() != "" { + t.Fatal("a session is open after the fenced layer closed") } } @@ -107,8 +96,8 @@ func TestHeadBeltEmptyBaseForeignPublicationFences(t *testing.T) { if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, ErrChunkLayerFenced) || !layer.Fenced() { t.Fatalf("empty-base foreign publication not fenced: %v", err) } - if layer.RemoteLSN() != 0 || len(liveIntents(t, f)) == 0 { - t.Fatal("fenced first cut settled or deleted intents") + if layer.RemoteLSN() != 0 || f.openSession() != "" { + t.Fatal("fenced first cut settled, or kept its session") } calls := f.stats().cas if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, ErrChunkLayerFenced) || f.stats().cas != calls { @@ -117,89 +106,8 @@ func TestHeadBeltEmptyBaseForeignPublicationFences(t *testing.T) { if err := layer.Close(); err != nil { t.Fatal(err) } - if len(liveIntents(t, f)) == 0 { - t.Fatal("Close removed first-cut intents") - } -} - -func TestHeadBeltSinglePointHasNoCoolingDelay(t *testing.T) { - f := newFakeChunkRemote() - f.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - if _, err := ClaimChunkHead(ctx, f, ChunkLayerConfig{Epoch: 2, Holder: "new"}); err != nil { - t.Fatal("single-point takeover delayed", err) - } - if f.stats().getHeads != 2 { - t.Fatal("single-point claim skipped readback") - } -} - -type deadlineBeltRemote struct { - *fakeChunkRemote - casDeadline, readDeadline bool -} - -func (r *deadlineBeltRemote) CASHead(ctx context.Context, v ChunkHeadVersion, h ChunkHead) (uint64, error) { - d, ok := ctx.Deadline() - r.casDeadline = ok && time.Until(d) <= 2*time.Second - return r.fakeChunkRemote.CASHead(ctx, v, h) -} -func (r *deadlineBeltRemote) GetHeadRoot(ctx context.Context) (ChunkHead, error) { - d, ok := ctx.Deadline() - r.readDeadline = ok && time.Until(d) <= 2*time.Second - return r.fakeChunkRemote.GetHead(ctx) -} -func TestHeadBeltOperationsHaveOwnDeadline(t *testing.T) { - r := &deadlineBeltRemote{fakeChunkRemote: newFakeChunkRemote()} - r.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} - if _, err := ClaimChunkHead(context.Background(), r, ChunkLayerConfig{Epoch: 2, Holder: "new"}); err != nil { - t.Fatal(err) - } - if !r.casDeadline || !r.readDeadline { - t.Fatalf("claim deadlines: CAS=%t read=%t", r.casDeadline, r.readDeadline) - } - r.casDeadline, r.readDeadline = false, false - head := r.stats().head - if _, err := casAndConfirmChunkHead(context.Background(), r, ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, head); err != nil { - t.Fatal(err) - } - if !r.casDeadline || !r.readDeadline { - t.Fatalf("cut deadlines: CAS=%t read=%t", r.casDeadline, r.readDeadline) - } -} - -func TestHeadBeltTakeoverWaitsBeforeConfirmation(t *testing.T) { - f := newFakeChunkRemote() - f.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} - var committedAt, confirmedAt time.Time - f.afterCAS = func(f *fakeChunkRemote) { committedAt = time.Now() } - f.onGetHead = func(f *fakeChunkRemote) { - if !committedAt.IsZero() { - confirmedAt = time.Now() - } - } - window := chunkHeadOperationTimeout + chunkHeadSettleTime - ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) - defer cancel() - head, err := ClaimChunkHead(ctx, f, ChunkLayerConfig{Epoch: 2, Holder: "new", HeadCoolingWindow: window}) - if err != nil { - t.Fatal(err) - } - if committedAt.IsZero() || confirmedAt.IsZero() || confirmedAt.Sub(committedAt) < window || f.stats().getHeads != 2 { - t.Fatal("confirmation read preceded cooling", confirmedAt.Sub(committedAt)) - } - if head.Gen != 2 || head.Epoch != 2 || head.Holder != "new" { - t.Fatal("confirmed the wrong owner", head) - } -} - -func TestHeadBeltCoolingWindowCoversCASAndSettle(t *testing.T) { - for _, window := range []time.Duration{-1, time.Millisecond, chunkHeadOperationTimeout, chunkHeadOperationTimeout + chunkHeadSettleTime - 1} { - f := newFakeChunkRemote() - if _, err := ClaimChunkHead(context.Background(), f, ChunkLayerConfig{Epoch: 2, Holder: "new", HeadCoolingWindow: window}); err == nil || f.stats().getHeads != 0 { - t.Fatalf("unsafe cooling window %s admitted or touched remote: %v", window, err) - } + if f.openSession() != "" { + t.Fatal("a session is open after the fenced layer closed") } } @@ -235,22 +143,3 @@ func TestHeadBeltConfirmationUsesOnlyRoot(t *testing.T) { t.Fatal("confirmed wrong image") } } - -func TestHeadBeltRetryOfUnconfirmedClaimStillCools(t *testing.T) { - f := newFakeChunkRemote() - f.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() - if _, err := ClaimChunkHead(ctx, f, ChunkLayerConfig{Epoch: 2, Holder: "new", HeadCoolingWindow: chunkHeadOperationTimeout + chunkHeadSettleTime}); !errors.Is(err, context.DeadlineExceeded) || f.stats().cas != 1 { - t.Fatalf("claim did not stop inside cooling after CAS: %v, calls=%d", err, f.stats().cas) - } - retryCtx, retryCancel := context.WithTimeout(context.Background(), 8*time.Second) - defer retryCancel() - start := time.Now() - if _, err := ClaimChunkHead(retryCtx, f, ChunkLayerConfig{Epoch: 2, Holder: "new", HeadCoolingWindow: chunkHeadOperationTimeout + chunkHeadSettleTime}); err != nil { - t.Fatal(err) - } - if time.Since(start) < chunkHeadOperationTimeout+chunkHeadSettleTime || f.stats().cas != 2 { - t.Fatal("retry bypassed cooling or failed to fence the previous incarnation") - } -} diff --git a/seaweed-block/core/storage/chunk_intent_test.go b/seaweed-block/core/storage/chunk_intent_test.go deleted file mode 100644 index b6e6658d72..0000000000 --- a/seaweed-block/core/storage/chunk_intent_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package storage - -import ( - "context" - "strings" - "testing" -) - -// checkIntentContract is the intent contract every chunkRemote meets (W5): -// ids are "-" and unique per call, intents list back with what -// was written, and DeleteIntent removes only the named intent. -func checkIntentContract(t *testing.T, r chunkRemote) { - t.Helper() - ctx := context.Background() - if got, err := r.ListIntents(ctx); err != nil || len(got) != 0 { - t.Fatalf("intents before any PutIntent: %v %v", got, err) - } - a, err := r.PutIntent(ctx, chunkIntent{Gen: 7, Epoch: 2, Holder: "host-a", Keys: []string{"k1", "k2"}}) - if err != nil { - t.Fatal(err) - } - b, err := r.PutIntent(ctx, chunkIntent{Gen: 7, Epoch: 2, Holder: "host-a", Keys: []string{"k3"}}) - if err != nil { - t.Fatal(err) - } - if a == b || !strings.HasPrefix(a, "7-") || !strings.HasPrefix(b, "7-") || len(a) <= len("7-") { - t.Fatalf("intent ids %q and %q: want distinct \"7-\"", a, b) - } - got, err := r.ListIntents(ctx) - if err != nil || len(got) != 2 { - t.Fatalf("ListIntents: %v %v, want 2", got, err) - } - byID := map[string]chunkIntent{} - for _, in := range got { - byID[in.ID] = in - } - if in := byID[a]; in.Gen != 7 || in.Epoch != 2 || in.Holder != "host-a" || strings.Join(in.Keys, ",") != "k1,k2" || in.CreatedNs == 0 { - t.Fatalf("intent %q listed as %+v", a, in) - } - if err := r.DeleteIntent(ctx, a); err != nil { - t.Fatal(err) - } - if err := r.DeleteIntent(ctx, a); err != nil { - t.Fatalf("deleting a missing intent: %v, want nil", err) - } - got, _ = r.ListIntents(ctx) - if len(got) != 1 || got[0].ID != b { - t.Fatalf("after deleting %q: %+v, want only %q", a, got, b) - } -} - -func TestMemChunkRemote_IntentContract(t *testing.T) { checkIntentContract(t, NewMemChunkRemote()) } - -func TestFakeChunkRemote_IntentContract(t *testing.T) { checkIntentContract(t, newFakeChunkRemote()) } diff --git a/seaweed-block/core/storage/chunk_key_domain_test.go b/seaweed-block/core/storage/chunk_key_domain_test.go index 76dea08bca..6ea3d8c23c 100644 --- a/seaweed-block/core/storage/chunk_key_domain_test.go +++ b/seaweed-block/core/storage/chunk_key_domain_test.go @@ -5,9 +5,9 @@ import ( "testing" ) -// The chunk key domain is non-empty valid UTF-8, enforced at Put and at -// PutIntent by every remote, so a key protected by an intent always lists -// back byte-identical to the key stored (review of #110). +// The chunk key domain is non-empty valid UTF-8, enforced at Put by every +// remote, so a stored key is byte-identical to the key named (review of +// #110). func checkKeyDomain(t *testing.T, r chunkRemote) { t.Helper() ctx := context.Background() @@ -15,27 +15,14 @@ func checkKeyDomain(t *testing.T, r chunkRemote) { if err := r.Put(ctx, bad, []byte("x")); err == nil { t.Errorf("Put(%q) accepted a key outside the domain", bad) } - if _, err := r.PutIntent(ctx, chunkIntent{Gen: 1, Epoch: 1, Holder: "h", Keys: []string{"ok", bad}}); err == nil { - t.Errorf("PutIntent with key %q accepted a key outside the domain", bad) + } + for i, k := range []string{"chunks/é/ü-1", "@v1/chunks/e1/c0/x-1", "日本/鍵"} { + data := []byte{byte(i), 'y'} + if err := r.Put(ctx, k, data); err != nil { + t.Fatalf("Put of a Unicode or qualified key %q: %v", k, err) } - } - if got, err := r.ListIntents(ctx); err != nil || len(got) != 0 { - t.Fatalf("a refused PutIntent left intents: %+v %v", got, err) - } - keys := []string{"chunks/é/ü-1", "@v1/chunks/e1/c0/x-1", "日本/鍵"} - if err := r.Put(ctx, keys[0], []byte("y")); err != nil { - t.Fatalf("Put of a Unicode key: %v", err) - } - if _, err := r.PutIntent(ctx, chunkIntent{Gen: 2, Epoch: 1, Holder: "h", Keys: keys}); err != nil { - t.Fatalf("PutIntent with Unicode and qualified keys: %v", err) - } - got, err := r.ListIntents(ctx) - if err != nil || len(got) != 1 || len(got[0].Keys) != len(keys) { - t.Fatalf("ListIntents: %+v %v", got, err) - } - for i, k := range keys { - if got[0].Keys[i] != k { - t.Fatalf("intent key %d listed as %q, stored %q", i, got[0].Keys[i], k) + if got, err := r.Get(ctx, k); err != nil || string(got) != string(data) { + t.Fatalf("key %q read back as %q (%v)", k, got, err) } } } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index ddd5015a30..006562a1cb 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -109,14 +109,8 @@ type chunkLayerImpl struct { // pendingBase is the version the unresolved CAS expected. While HEAD is // still at it, that CAS may still land, so a read alone never settles it. pendingBase chunkHeadVersion - // pendingIntents are the intents (staging rounds and the barrier) of - // the unresolved proposal in pending; deleted once it is settled. - pendingIntents []string // stats holds the cumulative cut counters (under stMu). stats chunkLayerStats - // leftoverIntents are this layer's own intents whose delete failed - // after their cut was settled; every cut retries them. - leftoverIntents []string // Immutable completed uploads survive a refused point. Guarded by stMu; // versions and HEAD generation prevent reuse across mutations/recovery. reusable map[uint64]stagedChunk @@ -258,10 +252,6 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.cancel() return nil, fmt.Errorf("storage: chunk layer attach: read HEAD: %w", err) } - if cfg.RestoreGuard != nil && (head.Gen != cfg.RestoreGuard.Gen || head.Epoch != cfg.RestoreGuard.Epoch) { - l.cancel() - return nil, fmt.Errorf("%w: HEAD changed after restore claim/seed", errChunkHeadPrecondition) - } l.head = copyHead(head) l.remoteLSN = head.RemoteLSN // A HEAD that already belongs to a newer epoch or a competing holder is @@ -650,13 +640,11 @@ func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error type capturedChunk struct { version uint64 - intent string idx uint64 data []byte sum [32]byte zero bool key string // staged: already uploaded under this key (data is nil) - birth uint64 size int missing []uint64 // local copy awaits the pinned HEAD, after the local entry is released } @@ -669,7 +657,30 @@ type stagedChunk struct { headGen uint64 } +// latchIdentityMoved latches the layer fenced on any signal that HEAD's +// identity moved away from this holder (another holder or epoch, another +// claim at this epoch, a detach that needs a new grant, the volume being +// deleted), whichever remote call observed it. Fenced is the one place +// writes are admitted (the durable backend's ready check reads it), so from +// this error on the layer acknowledges nothing it can no longer publish. +func (l *chunkLayerImpl) latchIdentityMoved(err error) error { + if err == nil || !(errors.Is(err, errChunkLayerFenced) || errors.Is(err, errChunkHeadDeleted)) { + return err + } + l.stMu.Lock() + l.fenced = true + l.stMu.Unlock() + l.abortCOW(errChunkLayerFenced) + return err +} + +// ObserveRemoteError latches the layer fenced when err (from a call on the +// volume's remote made outside the layer, such as the holder's cleaning) is +// an identity-moved signal; it returns err unchanged. +func (l *chunkLayerImpl) ObserveRemoteError(err error) error { return l.latchIdentityMoved(err) } + func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) { + defer func() { err = l.latchIdentityMoved(err) }() done, err := l.register() if err != nil { return chunkCutResult{}, err @@ -688,11 +699,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.HeadReadbackNs += time.Since(start).Nanoseconds() return head, err } - dropCapturedIntents := func(ctx context.Context, ids []string) { - start := time.Now() - l.dropIntents(ctx, ids) - st.IntentCleanupNs += time.Since(start).Nanoseconds() - } finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string) { start := time.Now() l.finishCut(head, h, changed, keys) @@ -717,16 +723,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch res.CandidateTail = l.estimateCandidateTail(tailBytes) } if errors.Is(err, errChunkLayerFenced) { - l.stMu.Lock() - var ids []string - for _, sc := range l.reusable { - if sc.intent != "" { - ids = append(ids, sc.intent) - } - } - l.reusable = nil - l.stMu.Unlock() - dropCapturedIntents(ctx, ids) + l.discardStaged() } if observe := l.precopyPause; observe != nil { observe(time.Duration(st.BarrierPauseNs)) @@ -773,26 +770,22 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if err := l.resolvePending(ctx); err != nil { return chunkCutResult{}, err } - l.retryLeftoverIntents(ctx) // Pre-copy large native dirty sets outside the barrier, bounded by the // remaining COW exposure rather than a fixed candidate count. stageStart := time.Now() var staged map[uint64]stagedChunk - var intents []string _, guestFrozen := FrozenDetachFromContext(ctx) spill := l.readCutSpill() if !guestFrozen { - staged, intents, err = l.stage(ctx, &st, spill.bytes) + staged, err = l.stage(ctx, &st, spill.bytes) } st.PayloadNs += time.Since(stageStart).Nanoseconds() if err != nil { - dropCapturedIntents(ctx, intents) return chunkCutResult{}, err } if cause := context.Cause(ctx); cause != nil { - dropCapturedIntents(ctx, intents) return chunkCutResult{}, cause } @@ -817,7 +810,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch releasePrecopy() releasePrecopy = nil } - dropCapturedIntents(ctx, intents) return chunkCutResult{}, cause } // Resume rejected tentative admission before any ordinary COW upload. @@ -842,7 +834,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if err != nil { unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() - dropCapturedIntents(ctx, intents) // a clean abort: staged keys are released return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err) } candidateStart := time.Now() @@ -889,9 +880,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.cutLSN = h baseHead := copyHead(l.head) l.stMu.Unlock() - // Candidates, mutation versions and births belong to the same barrier. + // Candidates, mutation versions and the copy-order hint belong to the same barrier. // Do not sample the owned map after COW writers are admitted again. - births := l.captureBirths(candidates, h) + recent := l.chunkRecency(candidates, h) st.CandidateNs += time.Since(candidateStart).Nanoseconds() // The authoritative candidate set is fixed with mutation admission closed. // The owner callback is nonblocking and may stop only an already drained @@ -903,8 +894,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if guestFrozen && !detach { unlockCapture() st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds() - l.abortCut(all) - dropCapturedIntents(ctx, intents) + l.requeueCut(all) return chunkCutResult{}, errors.Join(ErrFrozenTailTooLarge, context.Cause(ctx), l.admit()) } @@ -914,8 +904,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // HEAD holds the image of a later LSN than this host's log has // reached: publishing would move remote_lsn backwards. Refused // before any upload. (A HEAD of a newer holder fences below.) - l.abortCut(all) - dropCapturedIntents(ctx, intents) + l.requeueCut(all) return chunkCutResult{}, fmt.Errorf("%w: %w: cut LSN %d, HEAD remote_lsn %d", errChunkCaptureRefused, errChunkLSNBehind, h, baseHead.RemoteLSN) } @@ -936,9 +925,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch copyStart = time.Now() if copyErr == nil { var copied []capturedChunk - var ids []string - copied, ids, copyErr = l.copyCOWWindow(ctx, w, births, capturedVersions, baseHead) - intents = append(intents, ids...) + copied, copyErr = l.copyCOWWindow(ctx, w, recent, capturedVersions, baseHead) for _, c := range copied { if c.key != "" { st.UploadedChunks++ @@ -960,8 +947,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } st.UploadNs = st.CopyNs if copyErr != nil { - l.abortCut(all) - dropCapturedIntents(ctx, intents) + l.requeueCut(all) return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", copyErr) } if b := l.cfg.BarrierBound; b > 0 && st.BarrierCopyChunks > b { @@ -985,7 +971,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } var uploads []upload for _, c := range captured { - c.birth = births[c.idx] ref, had := baseHead.Chunks[c.idx] switch { case c.zero && !had, unchangedFromHead(c, ref, had): @@ -998,7 +983,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch continue } if c.key != "" { // staged: uploaded before the barrier - next.Chunks[c.idx] = chunkRef{Key: c.key, SHA256: c.sum, Encoding: "full", BirthLSN: c.birth} + next.Chunks[c.idx] = chunkRef{Key: c.key, SHA256: c.sum, Encoding: "full"} newKeys[c.idx] = c.key changed = append(changed, c.idx) if useStaged[c.idx] { @@ -1006,23 +991,16 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } continue } - uploads = append(uploads, upload{c: c, key: l.newKey(c.idx)}) + uploads = append(uploads, upload{c: c, key: l.keyFor(c.idx, c.sum, l.newKey(c.idx))}) } - // The intent names every key this cut uploads and is durable before - // the first upload: GC treats it as a root until the cut is settled. + // The holder's session is begun before the first upload: every object + // the cut writes belongs to it until the commit (CASHead) or Abort. uploadStart := time.Now() if len(uploads) > 0 { - keys := make([]string, len(uploads)) - for i, u := range uploads { - keys[i] = u.key + if _, err := l.remote.Begin(ctx); err != nil { + l.requeueCut(all) + return chunkCutResult{}, fmt.Errorf("storage: capture session: %w: %w", errChunkRemoteUnavailable, err) } - id, err := l.remote.PutIntent(ctx, chunkIntent{Gen: baseHead.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) - if err != nil { - l.abortCut(all) - dropCapturedIntents(ctx, intents) - return chunkCutResult{}, fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, err) - } - intents = append(intents, id) } st.PublishPrepareNs += time.Since(prepareStart).Nanoseconds() payloadStart := time.Now() @@ -1031,8 +1009,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch u := uploads[i] return l.putCapturedWith(ctx, u.key, u.c.data, func(ctx context.Context) error { return put(ctx, i, u.key, u.c.data) }) }); err != nil { - l.abortCut(all) - dropCapturedIntents(ctx, intents) + l.requeueCut(all) return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err)) } if len(uploads) > 0 { @@ -1040,59 +1017,41 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } prepareStart = time.Now() for _, u := range uploads { - next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth} + next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full"} newKeys[u.c.idx] = u.key changed = append(changed, u.c.idx) st.UploadedChunks++ st.UploadedBytes += int64(max(len(u.c.data), u.c.size)) } st.PublishPrepareNs += time.Since(prepareStart).Nanoseconds() - upgrade := false - if builder, ok := l.remote.(ChunkManifestBuilder); ok { - upgrade = baseHead.Segments == nil - var ids []string - var err error - manifestStart := time.Now() - next, ids, err = builder.PrepareManifest(ctx, baseHead, next, uint64(l.blockSize)*l.chunkBlocks) - st.ManifestNs += time.Since(manifestStart).Nanoseconds() - intents = append(intents, ids...) - if err != nil { - l.abortCut(all) - dropCapturedIntents(ctx, intents) - return chunkCutResult{}, err - } - } st.UploadNs += time.Since(uploadStart).Nanoseconds() - if !upgrade && !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { + if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { // A no-op cut still observes authority: a fresh host may have // claimed HEAD without uploading a single chunk since our last cut. cur, err := readCapturedHead() if err != nil { - l.abortCut(all) - dropCapturedIntents(ctx, intents) + l.requeueCut(all) return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err) } - if cur.Gen != baseHead.Gen || !sameProposal(cur, baseHead) { - l.abortCut(all) - l.stMu.Lock() - l.pendingIntents = append(l.pendingIntents, intents...) - l.stMu.Unlock() + // Fence only when HEAD's identity or image differs from ours, as + // the CAS path does. Its generation alone may move without either + // (a settlement that aborts this holder's session rewrites HEAD as + // it was): the cut then completes on the newer generation. + if !sameProposal(cur, baseHead) { + l.requeueCut(all) l.fencePublication(cur) return chunkCutResult{}, errChunkLayerFenced } - finishCapturedCut(baseHead, h, nil, nil) // nothing new: no CAS + finishCapturedCut(cur, h, nil, nil) // nothing new: no CAS persistCapturedMap(capturedVersions) - dropCapturedIntents(ctx, intents) // superseded staged uploads only - return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil + return chunkCutResult{H: h, Head: copyHead(cur), Noop: true, FullHash: all}, nil } if err := l.admit(); err != nil { // admission re-checked right before the CAS - l.abortCut(all) - dropCapturedIntents(ctx, intents) + l.requeueCut(all) return chunkCutResult{}, err } if l.supersededBy(baseHead) { - l.abortCut(all) - dropCapturedIntents(ctx, intents) + l.requeueCut(all) l.stMu.Lock() l.fenced = true l.stMu.Unlock() @@ -1113,7 +1072,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch next.Gen = gen finishCapturedCut(next, h, changed, newKeys) persistCapturedMap(capturedVersions) - dropCapturedIntents(ctx, intents) return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil } // Precondition or unknown outcome: resolve by re-reading HEAD, never by @@ -1123,9 +1081,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch p := copyHead(next) l.pending = &p l.pendingDetach, l.pendingCut, l.pendingBase = detach, chunkCutResult{H: h, FullHash: all}, expected - l.pendingIntents = intents // kept until the proposal is settled l.stMu.Unlock() - l.abortCut(all) + // The session stays open: the commit may still land, and the + // settlement replays it in the same session (resolvePending). + l.requeueCut(all) } if errors.Is(casErr, errChunkLayerFenced) { keepPending() @@ -1153,12 +1112,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.CASResult = "resolved-by-reread" finishCapturedCut(cur, h, changed, newKeys) persistCapturedMap(capturedVersions) - dropCapturedIntents(ctx, intents) return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil } - // HEAD moved past the CAS's base without it: it can never land. - l.abortCut(all) - dropCapturedIntents(ctx, intents) + // HEAD moved past the CAS's base without it: it can never land, and + // what it staged was compared against a HEAD that is gone. + l.requeueCut(all) + l.discardStaged() if l.supersededBy(cur) { l.stMu.Lock() l.fenced = true @@ -1199,14 +1158,15 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { // at the same base to the non-detached base image (this holder, this epoch), // so whichever lands first decides and the detach can never land after a // successful cancel. resolvePending would re-propose the detach instead. -func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) { +func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettlement, result chunkCutResult, err error) { l.capMu.Lock() defer l.unlockCap() + defer func() { err = l.latchIdentityMoved(err) }() if r, ok := l.storedDetach(); ok { return detachApplied, r, nil } l.stMu.Lock() - fenced, pending, isDetach, base, intents := l.fenced, l.pending, l.pendingDetach, l.pendingBase, l.pendingIntents + fenced, pending, isDetach, base := l.fenced, l.pending, l.pendingDetach, l.pendingBase baseHead := copyHead(l.head) l.stMu.Unlock() if fenced { @@ -1246,15 +1206,11 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, ch return detachFenced, chunkCutResult{}, nil } // Settled: the detach landed, or it can never land. - l.stMu.Lock() - l.reusable = nil - l.pendingIntents = nil // settled here; allow deletion of these roots below. - l.stMu.Unlock() - l.dropIntents(ctx, intents) + l.discardStaged() // a landed proposal's commit already ended its session l.stMu.Lock() defer l.stMu.Unlock() cut := l.pendingCut - l.pending, l.pendingIntents = nil, nil + l.pending = nil l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} switch { case sameProposal(cur, *pending): @@ -1303,6 +1259,11 @@ func (l *chunkLayerImpl) supersededBy(cur chunkHead) bool { return cur.Epoch > l.cfg.Epoch || (cur.Epoch == l.cfg.Epoch && cur.Holder != l.cfg.Holder && cur.Gen != 0) } +// sameProposal reports whether HEAD cur is the image next proposed, by +// durable identity and image only: epoch, holder, position, detached state +// and who detached; the segments; per chunk its key, content hash and +// encoding. A value the store does not keep (a chunk's birth) or that it +// owns (a generation) would make an applied commit look foreign. func sameProposal(cur, next chunkHead) bool { if (cur.Segments == nil) != (next.Segments == nil) || cur.ChunkBytes != next.ChunkBytes || cur.ManifestChunkCount != next.ManifestChunkCount || len(cur.Segments) != len(next.Segments) { return false @@ -1316,12 +1277,17 @@ func sameProposal(cur, next chunkHead) bool { if cur.Epoch != next.Epoch || cur.Holder != next.Holder || cur.RemoteLSN != next.RemoteLSN || len(cur.Chunks) != len(next.Chunks) { return false } + // Who detached is identity; the detach's generation is the store's, not + // part of the proposal. if chunkHeadIsDetached(cur) != chunkHeadIsDetached(next) || (cur.DetachedBy == nil) != (next.DetachedBy == nil) || - (cur.DetachedBy != nil && *cur.DetachedBy != *next.DetachedBy) { + (cur.DetachedBy != nil && (cur.DetachedBy.Holder != next.DetachedBy.Holder || cur.DetachedBy.Epoch != next.DetachedBy.Epoch)) { return false } + // A chunk is its key, content hash and encoding. Its birth is not a fact + // the store keeps (the layout records none), so it is never compared. for k, v := range next.Chunks { - if cur.Chunks[k] != v { + c, ok := cur.Chunks[k] + if !ok || c.Key != v.Key || c.SHA256 != v.SHA256 || c.Encoding != v.Encoding { return false } } @@ -1337,7 +1303,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { } }() l.stMu.Lock() - pending, base, intents := l.pending, l.pendingBase, l.pendingIntents + pending, base := l.pending, l.pendingBase l.stMu.Unlock() if pending == nil { return nil @@ -1375,14 +1341,10 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { return errChunkLayerFenced } // Settled: the proposal landed or can never land. - l.stMu.Lock() - l.reusable = nil - l.pendingIntents = nil // settled here; allow deletion of these roots below. - l.stMu.Unlock() - l.dropIntents(ctx, intents) + l.discardStaged() // a landed proposal's commit already ended its session l.stMu.Lock() defer l.stMu.Unlock() - l.pending, l.pendingIntents = nil, nil + l.pending = nil wasDetach, cut := l.pendingDetach, l.pendingCut l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} switch { @@ -1502,13 +1464,6 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats { return out } -// dropIntent deletes this layer's own intent id (none if empty) once its -// cut is settled. A failed delete is kept and retried by the next cut; it -// never fails a cut whose outcome is already settled. -func (l *chunkLayerImpl) dropIntent(ctx context.Context, id string) { - l.dropIntents(ctx, []string{id}) -} - // readChunk copies chunk idx from the store (the barrier copy, the // pre-copy staging and the reconciler use it). func (l *chunkLayerImpl) readChunk(idx uint64) ([]byte, error) { @@ -1527,54 +1482,18 @@ func (l *chunkLayerImpl) readChunk(idx uint64) ([]byte, error) { return buf, nil } -// dropIntents drops every intent of a settled cut (staging rounds and -// the barrier). -func (l *chunkLayerImpl) dropIntents(ctx context.Context, ids []string) { - // A wave roots several chunks with one intent. Build the live root set - // once, rather than rescanning every cached chunk for each delete. - l.stMu.Lock() - keep := make(map[string]bool) - for _, id := range l.pendingIntents { - keep[id] = true - } - for idx, sc := range l.reusable { - if l.closed || l.fenced || sc.ver != l.chunkVersion(idx) || sc.headGen != l.head.Gen { - delete(l.reusable, idx) - continue - } - keep[sc.intent] = true - } - l.stMu.Unlock() - seen := make(map[string]bool) - for _, id := range ids { - if id == "" || keep[id] || seen[id] { - continue - } - seen[id] = true - if err := l.remote.DeleteIntent(ctx, id); err != nil { - l.stMu.Lock() - l.leftoverIntents = append(l.leftoverIntents, id) - l.stMu.Unlock() - } - } -} - // stage uploads large native dirty sets through logical reads, before fixing H. // It stops when the spill-budget remainder is reached or a round makes no // progress. Versions/HEAD generation bind every reusable immutable result. -func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap int64) (map[uint64]stagedChunk, []string, error) { +func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap int64) (map[uint64]stagedChunk, error) { // Leave at most half the side budget exposed at the barrier. Streaming // staging uses no local payload file, even for a much larger image. bound := int(spillCap / (2 * int64(l.blockSize) * int64(l.chunkBlocks))) staged := map[uint64]stagedChunk{} - var intents []string l.stMu.Lock() for idx, sc := range l.reusable { staged[idx] = sc - if sc.intent != "" { - intents = append(intents, sc.intent) - } } l.stMu.Unlock() previous := int(^uint(0) >> 1) @@ -1627,10 +1546,9 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap head := copyHead(l.head) l.stMu.Unlock() st.StageRounds++ - roundChunks, ids, err := l.stagePayloadRound(ctx, batch, vers, head, st) - intents = append(intents, ids...) + roundChunks, err := l.stagePayloadRound(ctx, batch, vers, head, st) if err != nil { - return nil, intents, err + return nil, err } for idx, sc := range roundChunks { staged[idx] = sc @@ -1640,22 +1558,25 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap hook(round) } } - return staged, intents, nil + return staged, nil } -// retryLeftoverIntents retries the deletes dropIntent could not make. -func (l *chunkLayerImpl) retryLeftoverIntents(ctx context.Context) { +// discardStaged drops the reusable staged uploads and, with them, their +// session (Abort: non-blocking; the remote rolls it back at its next HEAD +// read). The session lives exactly as long as the staged set: a cut that +// is refused but keeps its uploads (admission, frozen tail, an upload or +// copy error) keeps the session, so its retry commits them without +// staging again. Caller does not hold stMu. +func (l *chunkLayerImpl) discardStaged() { l.stMu.Lock() - ids := l.leftoverIntents - l.leftoverIntents = nil + l.reusable = nil l.stMu.Unlock() - for _, id := range ids { - l.dropIntent(ctx, id) - } + l.remote.Abort() } -// abortCut returns a failed cut's chunks to the dirty set. -func (l *chunkLayerImpl) abortCut(all bool) { +// requeueCut returns a cut that ended without a commit to the dirty set. +// Its staged uploads stay reusable and its session stays open. +func (l *chunkLayerImpl) requeueCut(all bool) { l.stMu.Lock() defer l.stMu.Unlock() for idx := range l.inflight { @@ -1681,6 +1602,22 @@ func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, n l.dirtyVer++ } +// ChunkKeyer is implemented by a content-named remote: it names a chunk's +// key from its index and its bytes' hash, and the engine uses that key in +// place of a fresh one, so every key the engine holds resolves by name. +type ChunkKeyer interface { + ChunkKey(idx uint64, sum [32]byte) string +} + +// keyFor is the key a chunk with bytes hashing to sum is uploaded under: +// the remote's name when it is content-named, else fresh. +func (l *chunkLayerImpl) keyFor(idx uint64, sum [32]byte, fresh string) string { + if k, ok := l.remote.(ChunkKeyer); ok { + return k.ChunkKey(idx, sum) + } + return fresh +} + func (l *chunkLayerImpl) newKey(idx uint64) string { l.stMu.Lock() l.keySeq++ @@ -1889,42 +1826,15 @@ func (l *chunkLayerImpl) Close() error { h() // tests: the join returned } l.stMu.Lock() - protected := make(map[string]bool, len(l.pendingIntents)) - for _, id := range l.pendingIntents { - protected[id] = true - } - var settled []string - for _, sc := range l.reusable { - if !protected[sc.intent] { - settled = append(settled, sc.intent) - } - } - for _, id := range l.leftoverIntents { - if !protected[id] { - settled = append(settled, id) - } - } l.reusable = nil - l.leftoverIntents = nil + unresolved := l.pending != nil l.stMu.Unlock() - // Layer cancellation has joined all owners. Cleanup has a separate bounded - // context; an unknown CAS retains its roots for later epoch fencing. - cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 3*time.Second) - if cleaner, ok := l.remote.(interface { - DeleteSettledIntent(context.Context, string) error - }); ok { - seen := map[string]bool{} - for _, id := range settled { - if id == "" || seen[id] { - continue - } - seen[id] = true - _ = cleaner.DeleteSettledIntent(cleanupCtx, id) - } - } else { - l.dropIntents(cleanupCtx, settled) + // Layer cancellation has joined all owners. A cut left open ends here; + // an unresolved commit keeps its session (its re-proposal, or the next + // holder, settles it). + if !unresolved { + l.remote.Abort() } - cleanupCancel() close(l.closeDone) return nil } diff --git a/seaweed-block/core/storage/chunk_layer_intent_test.go b/seaweed-block/core/storage/chunk_layer_intent_test.go deleted file mode 100644 index 61730a7f89..0000000000 --- a/seaweed-block/core/storage/chunk_layer_intent_test.go +++ /dev/null @@ -1,326 +0,0 @@ -package storage - -// The capture path's intents (W5): a cut that uploads chunks durably writes -// an intent naming at least those keys before the first upload, and deletes -// only its own intent once the outcome is settled: after a confirmed HEAD -// CAS, or a clean abort. An uncertain CAS keeps the intent until a later -// HEAD read settles it. - -import ( - "context" - "errors" - "sort" - "strings" - "testing" -) - -// opsSince returns the remote ops recorded after mark. -func opsSince(f *fakeChunkRemote, mark int) []string { - return f.stats().ops[mark:] -} - -func indexOf(ops []string, pred func(string) bool) int { - for i, op := range ops { - if pred(op) { - return i - } - } - return -1 -} - -func liveIntents(t *testing.T, f *fakeChunkRemote) []chunkIntent { - t.Helper() - in, err := f.ListIntents(context.Background()) - if err != nil { - t.Fatal(err) - } - return in -} - -func lastPutIntent(t *testing.T, f *fakeChunkRemote) chunkIntent { - t.Helper() - f.mu.Lock() - defer f.mu.Unlock() - if len(f.putIntents) == 0 { - t.Fatal("no intent was written") - } - return f.putIntents[len(f.putIntents)-1] -} - -func uploadedKeys(ops []string) []string { - var keys []string - for _, op := range ops { - if k, ok := strings.CutPrefix(op, "put:"); ok { - keys = append(keys, k) - } - } - sort.Strings(keys) - return keys -} - -func TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS(t *testing.T) { - s, _ := newChunkTestStore(t) - f := newFakeChunkRemote() - layer := mustAttach(t, s, f, ctConfig(1)) - w := newWriteLog() - w.write(t, s, 2, 0x22) - w.write(t, s, 9, 0x29) - - mark := len(f.stats().ops) - if _, err := layer.Cut(ctTimeout(t)); err != nil { - t.Fatal(err) - } - ops := opsSince(f, mark) - in := lastPutIntent(t, f) - iIntent := indexOf(ops, func(op string) bool { return op == "putintent:"+in.ID }) - iPut := indexOf(ops, func(op string) bool { return strings.HasPrefix(op, "put:") }) - iCAS := indexOf(ops, func(op string) bool { return op == "cas:ok" }) - iDel := indexOf(ops, func(op string) bool { return op == "deleteintent:"+in.ID }) - if iIntent < 0 || iPut < 0 || iIntent > iPut { - t.Fatalf("intent not written before the first upload: ops %q", ops) - } - if iCAS < 0 || iDel < iCAS { - t.Fatalf("intent not deleted after the confirmed CAS: ops %q", ops) - } - keys := append([]string(nil), in.Keys...) - sort.Strings(keys) - for _, key := range uploadedKeys(ops) { - i := sort.SearchStrings(keys, key) - if i == len(keys) || keys[i] != key { - t.Fatalf("uploaded key %q absent from intent %q", key, keys) - } - } - if in.Gen != 0 || in.Epoch != 1 || in.Holder != "host-a" { - t.Fatalf("intent gen %d epoch %d holder %q, want the cut's base gen 0, epoch 1, host-a", in.Gen, in.Epoch, in.Holder) - } - if live := liveIntents(t, f); len(live) != 0 { - t.Fatalf("intents left after a published cut: %+v", live) - } -} - -func TestChunkIntent_CutWithoutUploadWritesNoIntent(t *testing.T) { - s, _ := newChunkTestStore(t) - f := newFakeChunkRemote() - layer := mustAttach(t, s, f, ctConfig(1)) - w := newWriteLog() - w.write(t, s, 2, 0x22) - if _, err := layer.Cut(ctTimeout(t)); err != nil { - t.Fatal(err) - } - w.write(t, s, 2, 0x00) // the chunk is zero again: the cut only drops it - mark := len(f.stats().ops) - if _, err := layer.Cut(ctTimeout(t)); err != nil { - t.Fatal(err) - } - ops := opsSince(f, mark) - if indexOf(ops, func(op string) bool { return strings.HasPrefix(op, "putintent") }) >= 0 { - t.Fatalf("a cut with no upload wrote an intent: ops %q", ops) - } - if indexOf(ops, func(op string) bool { return op == "cas:ok" }) < 0 { - t.Fatalf("the dropping cut did not publish: ops %q", ops) - } -} - -func TestChunkIntent_FailedPutIntentUploadsNothing(t *testing.T) { - s, _ := newChunkTestStore(t) - f := newFakeChunkRemote() - layer := mustAttach(t, s, f, ctConfig(1)) - w := newWriteLog() - w.write(t, s, 2, 0x22) - f.mu.Lock() - f.failPutIntent = errors.New("injected PutIntent failure") - f.mu.Unlock() - mark := len(f.stats().ops) - if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkRemoteUnavailable) { - t.Fatalf("cut with a failed intent write: %v; want a remote-unavailable refusal", err) - } - if got := uploadedKeys(opsSince(f, mark)); len(got) != 0 { - t.Fatalf("chunks uploaded without an intent: %q", got) - } - f.mu.Lock() - f.failPutIntent = nil - f.mu.Unlock() - if _, err := layer.Cut(ctTimeout(t)); err != nil { - t.Fatalf("cut after the intent store recovered: %v", err) - } - if heads := f.installedHeads(); len(heads) != 1 || len(heads[0].Chunks) != 1 { - t.Fatalf("the retried cut did not publish the write: %+v", heads) - } -} - -func TestChunkIntent_FailedUploadDeletesIntent(t *testing.T) { - s, _ := newChunkTestStore(t) - f := newFakeChunkRemote() - layer := mustAttach(t, s, f, ctConfig(1)) - w := newWriteLog() - w.write(t, s, 2, 0x22) - f.mu.Lock() - f.failPut = errors.New("injected upload failure") - f.mu.Unlock() - if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkRemoteUnavailable) { - t.Fatalf("cut with a failed upload: %v; want a remote-unavailable refusal", err) - } - in := lastPutIntent(t, f) - if live := liveIntents(t, f); len(live) != 0 { - t.Fatalf("intent %s left after a cleanly aborted cut: %+v", in.ID, live) - } -} - -// HEAD is taken over before the CAS: the CAS is refused for good and the -// layer fences. Keep its roots for epoch-aware GC rather than cleaning over -// an independently serialized owner's publication. -func TestChunkIntent_ForeignOwnerRefusalKeepsIntent(t *testing.T) { - s, _ := newChunkTestStore(t) - f := newFakeChunkRemote() - layer := mustAttach(t, s, f, ctConfig(1)) - w := newWriteLog() - w.write(t, s, 2, 0x22) - f.mu.Lock() - f.beforeCAS = func(f *fakeChunkRemote) { f.takeOverLocked("host-b") } - f.mu.Unlock() - if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerFenced) { - t.Fatalf("cut against a taken-over HEAD: %v; want fenced", err) - } - if live := liveIntents(t, f); len(live) == 0 { - t.Fatal("foreign-owner refusal removed the cut's intent") - } -} - -// The CAS outcome is unknown and HEAD still holds its base: the intent -// stays until the next cut settles the proposal, then goes. -func TestChunkIntent_UncertainCASKeepsIntentUntilSettled(t *testing.T) { - s, _ := newChunkTestStore(t) - f := newFakeChunkRemote() - layer := mustAttach(t, s, f, ctConfig(1)) - w := newWriteLog() - w.write(t, s, 2, 0x22) - f.mu.Lock() - f.casModes = []fakeCASMode{casUnknownNotApplied} - f.mu.Unlock() - if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { - t.Fatalf("cut with an unknown CAS outcome: %v", err) - } - in := lastPutIntent(t, f) - if live := liveIntents(t, f); len(live) != 1 || live[0].ID != in.ID { - t.Fatalf("intents while the CAS is unresolved: %+v; want only %s", live, in.ID) - } - mark := len(f.stats().ops) - if _, err := layer.Cut(ctTimeout(t)); err != nil { - t.Fatalf("settling cut: %v", err) - } - ops := opsSince(f, mark) - iCAS := indexOf(ops, func(op string) bool { return op == "cas:ok" }) - iDel := indexOf(ops, func(op string) bool { return op == "deleteintent:"+in.ID }) - if iCAS < 0 || iDel < iCAS { - t.Fatalf("held intent not deleted after its proposal landed: ops %q", ops) - } - if live := liveIntents(t, f); len(live) != 0 { - t.Fatalf("intents left after settlement: %+v", live) - } -} - -// The CAS applied but its response was lost: the HEAD re-read confirms it, -// and the intent goes in the same cut. -func TestChunkIntent_LostCASResponseConfirmedDeletesIntent(t *testing.T) { - s, _ := newChunkTestStore(t) - f := newFakeChunkRemote() - layer := mustAttach(t, s, f, ctConfig(1)) - w := newWriteLog() - w.write(t, s, 2, 0x22) - f.mu.Lock() - f.casModes = []fakeCASMode{casAppliedLost} - f.mu.Unlock() - if _, err := layer.Cut(ctTimeout(t)); err != nil { - t.Fatalf("cut whose CAS response was lost: %v", err) - } - if live := liveIntents(t, f); len(live) != 0 { - t.Fatalf("intent left after a confirmed (re-read) CAS: %+v", live) - } -} - -// A failed DeleteIntent does not fail a published cut; the next cut deletes -// the leftover. -func TestChunkIntent_FailedDeleteIsRetriedNextCut(t *testing.T) { - s, _ := newChunkTestStore(t) - f := newFakeChunkRemote() - layer := mustAttach(t, s, f, ctConfig(1)) - w := newWriteLog() - w.write(t, s, 2, 0x22) - f.mu.Lock() - f.failDeleteIntent = 1 - f.mu.Unlock() - if _, err := layer.Cut(ctTimeout(t)); err != nil { - t.Fatalf("published cut reported the intent delete failure: %v", err) - } - first := lastPutIntent(t, f) - if live := liveIntents(t, f); len(live) != 1 || live[0].ID != first.ID { - t.Fatalf("intents after a failed delete: %+v", live) - } - w.write(t, s, 9, 0x29) - if _, err := layer.Cut(ctTimeout(t)); err != nil { - t.Fatal(err) - } - if live := liveIntents(t, f); len(live) != 0 { - t.Fatalf("leftover intent not retried: %+v", live) - } -} - -// A cut deletes only its own intent. -func TestChunkIntent_OtherIntentsUntouched(t *testing.T) { - s, _ := newChunkTestStore(t) - f := newFakeChunkRemote() - layer := mustAttach(t, s, f, ctConfig(1)) - other, err := f.PutIntent(context.Background(), chunkIntent{Gen: 0, Epoch: 1, Holder: "snapshot-op", Keys: []string{"chunks/e1/c0/other-1"}}) - if err != nil { - t.Fatal(err) - } - w := newWriteLog() - w.write(t, s, 2, 0x22) - if _, err := layer.Cut(ctTimeout(t)); err != nil { - t.Fatal(err) - } - if live := liveIntents(t, f); len(live) != 1 || live[0].ID != other { - t.Fatalf("intents after the cut: %+v; want only %s", live, other) - } -} - -// Admission is refused at the final check right before the CAS: a clean -// abort, so the intent goes. -func TestChunkIntent_AdmissionRefusedBeforeCASKeepsReusableIntent(t *testing.T) { - s, _ := newChunkTestStore(t) - f := newFakeChunkRemote() - cfg := ctConfig(1) - cfg.CaptureAllowed = func() error { - // The gate is checked concurrently between COW claims as well. Bind - // demotion to the real upload event, not a call count/schedule. - if f.stats().puts > 0 { // uploaded under an intent, before the CAS - return errors.New("demoted") - } - return nil - } - layer := mustAttach(t, s, f, cfg) - w := newWriteLog() - w.write(t, s, 2, 0x22) - if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) { - t.Fatalf("cut refused before its CAS: %v", err) - } - if f.stats().puts == 0 { - t.Fatal("control did not reach the intent-protected upload") - } - if n := f.stats().cas; n != 0 { - t.Fatalf("refused cut issued %d CAS", n) - } - if live := liveIntents(t, f); len(live) == 0 { - t.Fatal("completed upload lost its retry root after admission refusal") - } - // Restored admission reuses the exact payload and settles its root. - layer.(*chunkLayerImpl).cfg.CaptureAllowed = nil - before := f.stats().puts - if _, err := layer.Cut(ctTimeout(t)); err != nil { - t.Fatal(err) - } - if f.stats().puts != before { - t.Fatal("unchanged refused point uploaded again") - } - assertNoIntentsLeft(t, f) -} diff --git a/seaweed-block/core/storage/chunk_layer_map_v3_test.go b/seaweed-block/core/storage/chunk_layer_map_v3_test.go index b3ad2be3c6..58148bf782 100644 --- a/seaweed-block/core/storage/chunk_layer_map_v3_test.go +++ b/seaweed-block/core/storage/chunk_layer_map_v3_test.go @@ -170,7 +170,7 @@ func TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN(t *testing.T) { f := newFakeChunkRemote() layer := attachCleanMapFixtureV3(t, s, f, chunkHead{}) if mode == "intent_failure" { - f.failPutIntent = errors.New("intent unavailable") + f.failBegin = errors.New("intent unavailable") } else { f.casModes = []fakeCASMode{casUnknownNotApplied} } diff --git a/seaweed-block/core/storage/chunk_layer_precopy_test.go b/seaweed-block/core/storage/chunk_layer_precopy_test.go index b97c88d280..9feef31e69 100644 --- a/seaweed-block/core/storage/chunk_layer_precopy_test.go +++ b/seaweed-block/core/storage/chunk_layer_precopy_test.go @@ -6,7 +6,6 @@ package storage // write reached it since staging, so the image at H stays exact. import ( - "context" "errors" "strings" "testing" @@ -37,14 +36,6 @@ func precopyLayer(t *testing.T, bound, n int) (*WALStore, *fakeChunkRemote, *chu return s, f, l, w } -func assertNoIntentsLeft(t *testing.T, f *fakeChunkRemote) { - t.Helper() - in, err := f.ListIntents(context.Background()) - if err != nil || len(in) != 0 { - t.Fatalf("intents left after the cut settled: %d (%v)", len(in), err) - } -} - // A chunk re-dirtied between staging and the barrier is copied again in // the COW window: HEAD has the newer bytes, never the stale stage. Both ways a // write can reach a staged chunk are covered: flushed to the extent (its @@ -74,7 +65,7 @@ func TestChunkPrecopy_RedirtiedStagedChunkIsRecopied(t *testing.T) { r.Stats.StagedChunksUsed, r.Stats.BarrierCopyChunks, r.Stats.BarrierOverBound) } assertEveryHeadIsPrefixImage(t, f, w) - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) }) } } @@ -102,7 +93,7 @@ func TestChunkPrecopy_WritesOutpacingStagingGoOverBound(t *testing.T) { t.Fatalf("BarrierOverBound counter %d, want 0 for COW", got) } assertEveryHeadIsPrefixImage(t, f, w) - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } // Control: no bound, no staging; within the bound, no staging either. @@ -133,7 +124,7 @@ func TestChunkPrecopy_DetachUsesTheSamePath(t *testing.T) { t.Fatalf("detach: %d staging rounds, %d copied under the barrier; want staging and at most 2 copied", r.Stats.StageRounds, r.Stats.BarrierCopyChunks) } assertEveryHeadIsPrefixImage(t, f, w) - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } // W5 holds for staged keys: every upload, staged or at the barrier, is @@ -152,34 +143,24 @@ func TestChunkPrecopy_StagedUploadsAreCoveredByIntents(t *testing.T) { t.Fatal(err) } ops := opsSince(f, mark) - f.mu.Lock() - keysOf := map[string][]string{} - for _, in := range f.putIntents { - keysOf[in.ID] = in.Keys - } - f.mu.Unlock() - covered := map[string]bool{} - iCAS := indexOf(ops, func(op string) bool { return op == "cas:ok" }) - intents := 0 + open, begins := false, 0 for i, op := range ops { - if id, ok := strings.CutPrefix(op, "putintent:"); ok { - intents++ - for _, k := range keysOf[id] { - covered[k] = true - } + switch { + case strings.HasPrefix(op, "begin:") && op != "begin:fail": + open = true + begins++ + case strings.HasPrefix(op, "abort:"), op == "cas:ok": + open = false } - if k, ok := strings.CutPrefix(op, "put:"); ok && !covered[k] { - t.Fatalf("upload %q (op %d) not named by an earlier intent: ops %q", k, i, ops) - } - if strings.HasPrefix(op, "deleteintent:") && (iCAS < 0 || i < iCAS) { - t.Fatalf("intent deleted before the confirmed CAS: ops %q", ops) + if k, ok := strings.CutPrefix(op, "put:"); ok && !open { + t.Fatalf("upload %q (op %d) outside an open session: ops %q", k, i, ops) } } - if intents < 2 { - t.Fatalf("%d intents written; want staging rounds and the barrier covered (ops %q)", intents, ops) + if begins < 2 { + t.Fatalf("%d Begins; want the staging rounds and the barrier each in the session (ops %q)", begins, ops) } assertEveryHeadIsPrefixImage(t, f, w) - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } // A write that lands right after a chunk's staging read (flushed before @@ -201,9 +182,9 @@ func TestChunkPrecopy_WriteRightAfterStagingReadIsNotLost(t *testing.T) { assertEveryHeadIsPrefixImage(t, f, w) } -// A barrier Sync that fails after staging uploaded keys is a clean abort: -// the cut's staging intents are deleted (a failed delete is kept and -// retried by the next cut), and the next cut publishes the exact image. +// A barrier Sync that fails after staging uploaded keys keeps the session +// with the staged uploads open, and the next cut publishes the exact image +// in it. func TestChunkPrecopy_BarrierSyncFailureSettlesStagedIntents(t *testing.T) { s, f, l, w := precopyLayer(t, 2, 5) orig := s.committer.syncFunc @@ -219,31 +200,14 @@ func TestChunkPrecopy_BarrierSyncFailureSettlesStagedIntents(t *testing.T) { if st := f.stats(); st.puts == before.puts { t.Fatal("schedule did not stage any upload before the barrier") } - if len(liveIntents(t, f)) == 0 { - t.Fatal("completed uploads lost their retry roots") + if f.openSession() == "" { + t.Fatal("completed uploads lost their open session") } - - // The same abort with the intent delete failing: kept, retried next cut. - w.write(t, s, 2, 0x22) - w.write(t, s, uint32(ctChunkBlocks+2), 0x23) - w.write(t, s, uint32(2*ctChunkBlocks+2), 0x24) - f.mu.Lock() - f.failDeleteIntent = 100 - f.mu.Unlock() - if _, err := l.Cut(ctTimeout(t)); err == nil { - t.Fatal("second cut with a failing barrier Sync succeeded") - } - if left := len(liveIntents(t, f)); left == 0 { - t.Fatal("schedule: the failing delete left no intent to retry") - } - f.mu.Lock() - f.failDeleteIntent = 0 - f.mu.Unlock() l.testAfterStageHook = nil s.committer.syncFunc = orig if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } assertEveryHeadIsPrefixImage(t, f, w) - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } diff --git a/seaweed-block/core/storage/chunk_layer_session_test.go b/seaweed-block/core/storage/chunk_layer_session_test.go new file mode 100644 index 0000000000..fc3655ce33 --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_session_test.go @@ -0,0 +1,290 @@ +package storage + +// The capture path's session: a cut that uploads chunks begins the holder's +// session before the first upload; the commit (a confirmed HEAD CAS) ends +// it. The session lives as long as the staged uploads: a refused cut that +// keeps them (an upload error, admission, frozen tail) keeps it, and its +// retry commits them without staging again; dropping them (fenced, a HEAD +// moved past the commit's base, Close) aborts it. An uncertain commit keeps +// the session, and the settlement replays the same commit in it. + +import ( + "errors" + "sort" + "strings" + "testing" +) + +// opsSince returns the remote ops recorded after mark. +func opsSince(f *fakeChunkRemote, mark int) []string { + return f.stats().ops[mark:] +} + +func indexOf(ops []string, pred func(string) bool) int { + for i, op := range ops { + if pred(op) { + return i + } + } + return -1 +} + +func countOps(ops []string, prefix string) int { + n := 0 + for _, op := range ops { + if strings.HasPrefix(op, prefix) { + n++ + } + } + return n +} + +func uploadedKeys(ops []string) []string { + var keys []string + for _, op := range ops { + if k, ok := strings.CutPrefix(op, "put:"); ok { + keys = append(keys, k) + } + } + sort.Strings(keys) + return keys +} + +// assertNoSessionOpen: the cut settled, nothing of it is still open. +func assertNoSessionOpen(t *testing.T, f *fakeChunkRemote) { + t.Helper() + if s := f.openSession(); s != "" { + t.Fatalf("session %q still open after the cut settled", s) + } +} + +func TestSession_BegunBeforeFirstUploadAndClosedByCommit(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + w.write(t, s, 9, 0x29) + + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + ops := opsSince(f, mark) + iBegin := indexOf(ops, func(op string) bool { return op == "begin:s1" }) + iPut := indexOf(ops, func(op string) bool { return strings.HasPrefix(op, "put:") }) + iCAS := indexOf(ops, func(op string) bool { return op == "cas:ok" }) + if iBegin < 0 || iPut < 0 || iBegin > iPut { + t.Fatalf("session not begun before the first upload: ops %q", ops) + } + if iCAS < iPut || countOps(ops, "abort:") != 0 { + t.Fatalf("the published cut did not end by its commit alone: ops %q", ops) + } + assertNoSessionOpen(t, f) +} + +func TestSession_CutWithoutUploadBeginsNone(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + w.write(t, s, 2, 0x00) // the chunk is zero again: the cut only drops it + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + ops := opsSince(f, mark) + if countOps(ops, "begin:") != 0 { + t.Fatalf("a cut with no upload began a session: ops %q", ops) + } + if indexOf(ops, func(op string) bool { return op == "cas:ok" }) < 0 { + t.Fatalf("the dropping cut did not publish: ops %q", ops) + } +} + +func TestSession_FailedBeginUploadsNothing(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.failBegin = errors.New("injected Begin failure") + f.mu.Unlock() + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkRemoteUnavailable) { + t.Fatalf("cut with a failed Begin: %v; want a remote-unavailable refusal", err) + } + if got := uploadedKeys(opsSince(f, mark)); len(got) != 0 { + t.Fatalf("chunks uploaded without a session: %q", got) + } + f.mu.Lock() + f.failBegin = nil + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatalf("cut after Begin recovered: %v", err) + } + if heads := f.installedHeads(); len(heads) != 1 || len(heads[0].Chunks) != 1 { + t.Fatalf("the retried cut did not publish the write: %+v", heads) + } +} + +func TestSession_FailedUploadKeepsItForTheRetry(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.failPut = errors.New("injected upload failure") + f.mu.Unlock() + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkRemoteUnavailable) { + t.Fatalf("cut with a failed upload: %v; want a remote-unavailable refusal", err) + } + if ops := opsSince(f, mark); countOps(ops, "abort:") != 0 || f.openSession() != "s1" { + t.Fatalf("the failed cut gave up its session: ops %q, open %q", ops, f.openSession()) + } + f.mu.Lock() + f.failPut = nil + f.mu.Unlock() + mark = len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatalf("retry: %v", err) + } + ops := opsSince(f, mark) + iCAS := indexOf(ops, func(op string) bool { return op == "cas:ok" }) + if iCAS < 0 || countOps(ops[:iCAS], "begin:s") != 0 || countOps(ops, "abort:") != 0 { + t.Fatalf("the retry did not commit in the kept session: ops %q", ops) + } + assertNoSessionOpen(t, f) +} + +// HEAD is taken over before the CAS: the CAS is refused for good and the +// layer fences. It aborts only its own session (the new owner's HEAD is +// not this remote's to end: the layout kernel refuses another holder's +// Abort, TestLayoutRemote_AbortNeverEndsAnotherHoldersSession). +func TestSession_ForeignOwnerRefusalAbortsNothingOfTheirs(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.beforeCAS = func(f *fakeChunkRemote) { f.takeOverLocked("host-b") } + f.mu.Unlock() + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerFenced) { + t.Fatalf("cut against a taken-over HEAD: %v; want fenced", err) + } + ops := opsSince(f, mark) + if n := countOps(ops, "abort:"); n > 1 || (n == 1 && countOps(ops, "abort:s1") != 1) { + t.Fatalf("the fenced cut aborted something other than its own session: ops %q", ops) + } + if got := f.stats().head.Holder; got != "host-b" { + t.Fatalf("HEAD after the refused cut: holder %q, want the new owner host-b", got) + } +} + +// The commit's outcome is unknown and HEAD still holds its base: the +// session stays open (no Abort), and the next cut settles the proposal by +// replaying the same commit in that same session (no new Begin). The stop +// settlement is the other row: it aborts, then reads +// (TestLayoutStopAbortMustConfirmItsOutcome). +func TestSession_UncertainCommitIsNotAbortedUntilSettled(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casUnknownNotApplied} + f.mu.Unlock() + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { + t.Fatalf("cut with an unknown CAS outcome: %v", err) + } + if ops := opsSince(f, mark); countOps(ops, "abort:") != 0 || f.openSession() != "s1" { + t.Fatalf("an unresolved commit's session was aborted: ops %q, open %q", ops, f.openSession()) + } + mark = len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatalf("settling cut: %v", err) + } + ops := opsSince(f, mark) + iCAS := indexOf(ops, func(op string) bool { return op == "cas:ok" }) + if iCAS < 0 || countOps(ops[:iCAS], "abort:") != 0 || countOps(ops[:iCAS], "begin:s") != 0 { + t.Fatalf("the settlement did not replay the commit in the open session: ops %q", ops) + } + assertNoSessionOpen(t, f) +} + +// The CAS applied but its response was lost: the HEAD re-read confirms it, +// and nothing of the cut is left open. +func TestSession_LostCommitReplyConfirmedLeavesNoneOpen(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatalf("cut whose CAS response was lost: %v", err) + } + assertNoSessionOpen(t, f) +} + +// Admission is refused at the final check right before the CAS: the cut +// ends without a commit (its session is aborted), its completed uploads +// stay reusable, and the next cut publishes them without uploading again. +func TestSession_AdmissionRefusedBeforeCommitKeepsReusableUploads(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.CaptureAllowed = func() error { + // The gate is checked concurrently between COW claims as well. Bind + // demotion to the real upload event, not a call count/schedule. + if f.stats().puts > 0 { // uploaded in the session, before the CAS + return errors.New("demoted") + } + return nil + } + layer := mustAttach(t, s, f, cfg) + w := newWriteLog() + w.write(t, s, 2, 0x22) + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) { + t.Fatalf("cut refused before its CAS: %v", err) + } + if f.stats().puts == 0 { + t.Fatal("control did not reach the upload") + } + if n := f.stats().cas; n != 0 { + t.Fatalf("refused cut issued %d CAS", n) + } + // The refusal keeps the reusable uploads, so it keeps their session: + // aborting it would make the retry's commit find them not prepared and + // stage everything again (no convergence under sustained writes). + if ops := f.stats().ops; countOps(ops, "abort:") != 0 || f.openSession() != "s1" { + t.Fatalf("the admission refusal gave up its session: ops %q, open %q", ops, f.openSession()) + } + // Restored admission reuses the exact payload, in the same session. + layer.(*chunkLayerImpl).cfg.CaptureAllowed = nil + before := f.stats().puts + mark := len(f.stats().ops) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if f.stats().puts != before { + t.Fatal("unchanged refused point uploaded again") + } + if ops := opsSince(f, mark); countOps(ops, "begin:s") != 0 || countOps(ops, "abort:") != 0 { + t.Fatalf("the retry did not commit in the kept session: ops %q", ops) + } + assertNoSessionOpen(t, f) +} diff --git a/seaweed-block/core/storage/chunk_layer_takeover_test.go b/seaweed-block/core/storage/chunk_layer_takeover_test.go deleted file mode 100644 index 0abe1c121e..0000000000 --- a/seaweed-block/core/storage/chunk_layer_takeover_test.go +++ /dev/null @@ -1,136 +0,0 @@ -// Takeover data verification, coverage cell P10.6; -// INV-WS-CLAIM-BEFORE-SERVE-001. The production attach path first claims -// HEAD, then attaches the chunk layer against that exact claim. - -package storage - -import ( - "bytes" - "crypto/sha256" - "errors" - "testing" -) - -func takeoverImage() []byte { - img := make([]byte, ctNumBlocks*ctBlockSize) - for lba := uint32(0); lba < 16; lba++ { // chunks 0-3 hold data; 4-7 are ZERO - copy(img[int(lba)*ctBlockSize:], makeBlock(ctBlockSize, byte(0x70+lba))) - } - return img -} - -// A fresh host attaching at a newer epoch must raise HEAD's epoch before it -// serves, without changing the published chunks, so a cut-off old holder's -// next CAS fails at once instead of after the new host's first commit. -func TestChunkAttach_TakeOverRaisesEpoch(t *testing.T) { - f := newFakeChunkRemote() - f.seedHead(t, takeoverImage(), 100, 1) - seeded := f.stats().head - - s, _ := newChunkTestStore(t) - cfg := ctConfig(2) - cfg.FreshFromHead = true - claimed, err := ClaimChunkHead(ctTimeout(t), f, cfg) - if err != nil { - t.Fatal(err) - } - cfg.RestoreGuard = &ChunkHeadVersion{Gen: claimed.Gen, Epoch: claimed.Epoch} - mustAttach(t, s, f, cfg) - - head := f.stats().head - if head.Epoch != 2 || head.Holder != cfg.Holder { - t.Fatalf("after attach HEAD is epoch %d holder %q, want the attaching epoch 2 holder %q", head.Epoch, head.Holder, cfg.Holder) - } - if head.RemoteLSN != seeded.RemoteLSN || len(head.Chunks) != len(seeded.Chunks) { - t.Fatalf("takeover changed the image: remote_lsn %d chunks %d, want %d and %d", head.RemoteLSN, len(head.Chunks), seeded.RemoteLSN, len(seeded.Chunks)) - } - for k, v := range seeded.Chunks { - if head.Chunks[k] != v { - t.Fatalf("takeover changed chunk %d: %+v, want %+v", k, head.Chunks[k], v) - } - } - for lba := uint32(0); lba < ctNumBlocks; lba++ { - got, err := s.Read(lba) - if err != nil || !bytes.Equal(got, blockOf(takeoverImage(), lba)) { - t.Fatalf("takeover read LBA %d: bytes differ from seeded image, err=%v", lba, err) - } - } - // The old holder (epoch 1) can no longer commit. - if _, err := f.CASHead(ctTimeout(t), chunkHeadVersion{Gen: seeded.Gen, Epoch: 1}, seeded); !errors.Is(err, errChunkHeadPrecondition) { - t.Fatalf("old holder's CAS after takeover: %v, want errChunkHeadPrecondition", err) - } -} - -// The old holder commits a newer generation between the new host's HEAD -// read and its takeover CAS. Attach must then either take over that newer -// generation (and serve exactly its image) or fail; it must never serve a -// mix of two generations. -func TestChunkAttach_TakeOverRacesOldHolder(t *testing.T) { - f := newFakeChunkRemote() - img := takeoverImage() - f.seedHead(t, img, 100, 1) - - // The old holder's newer generation rewrites chunk 1 (LBA 4-7). - newer := append([]byte(nil), img...) - for lba := uint32(4); lba < 8; lba++ { - copy(newer[int(lba)*ctBlockSize:], makeBlock(ctBlockSize, byte(0xE0+lba))) - } - injected := false - f.beforeCAS = func(f *fakeChunkRemote) { - injected = true - next := copyChunkHead(f.head) - key := "seed/newer/1" - c := newer[1*ctChunkBytes : 2*ctChunkBytes] - f.objs[key] = append([]byte(nil), c...) - f.everStored[key] = true - next.Chunks[1] = chunkRef{Key: key, SHA256: sha256.Sum256(c)} - next.RemoteLSN = 101 - f.installLocked(next) - } - - s, _ := newChunkTestStore(t) - cfg := ctConfig(2) - cfg.FreshFromHead = true - claimed, err := ClaimChunkHead(ctTimeout(t), f, cfg) - f.mu.Lock() - ran := injected - f.mu.Unlock() - if !ran { - // The race is injected before the takeover CAS; without that CAS the - // test has not exercised the race at all, whatever attach returned. - t.Fatalf("the old holder's competing CAS was never injected (attach err %v): attach made no takeover CAS", err) - } - if err != nil { - // Failing the attach is an allowed outcome, but only as a refusal - // to serve: nothing may have been published by the new host. - if h := f.stats().head; h.Holder == cfg.Holder { - t.Fatalf("attach failed (%v) but HEAD names the new holder: %+v", err, h) - } - if !errors.Is(err, ErrChunkHeadPrecondition) { - t.Fatalf("competing publication was not a definite claim refusal: %v", err) - } - // Retry the definite refusal through the same claim seam; the - // successful retry must serve every byte of the competing image. - claimed, err = ClaimChunkHead(ctTimeout(t), f, cfg) - if err != nil { - t.Fatal(err) - } - } - cfg.RestoreGuard = &ChunkHeadVersion{Gen: claimed.Gen, Epoch: claimed.Epoch} - mustAttach(t, s, f, cfg) - - head := f.stats().head - if head.Epoch != 2 || head.Holder != cfg.Holder || head.RemoteLSN != 101 { - t.Fatalf("attach returned without taking over: HEAD epoch %d holder %q", head.Epoch, head.Holder) - } - want := newer - for lba := uint32(0); lba < ctNumBlocks; lba++ { - got, err := s.Read(lba) - if err != nil { - t.Fatalf("read LBA %d: %v", lba, err) - } - if !bytes.Equal(got, blockOf(want, lba)) { - t.Fatalf("LBA %d differs from the HEAD the new host took over (gen %d): a mix of generations", lba, head.Gen) - } - } -} diff --git a/seaweed-block/core/storage/chunk_manifest.go b/seaweed-block/core/storage/chunk_manifest.go index c460c0fe99..bb79a1cd1a 100644 --- a/seaweed-block/core/storage/chunk_manifest.go +++ b/seaweed-block/core/storage/chunk_manifest.go @@ -1,20 +1,11 @@ package storage -import "context" - // ChunkSegment names an immutable range manifest. Owner is the namespace in // which that manifest was encoded; forks preserve it without rewriting data. type ChunkSegment struct { - Key string `json:"key"` - SHA256 [32]byte `json:"sha256"` - Owner string `json:"owner"` - Count int `json:"count"` - MaxBirthLSN uint64 `json:"max_birth_lsn"` - SegFormat int `json:"seg_format"` -} - -// ChunkManifestBuilder prepares immutable segments before the existing root -// CAS. Returned intents belong to the publishing caller and follow its settlement rules. -type ChunkManifestBuilder interface { - PrepareManifest(context.Context, ChunkHead, ChunkHead, uint64) (ChunkHead, []string, error) + Key string `json:"key"` + SHA256 [32]byte `json:"sha256"` + Owner string `json:"owner"` + Count int `json:"count"` + SegFormat int `json:"seg_format"` } diff --git a/seaweed-block/core/storage/chunk_memremote.go b/seaweed-block/core/storage/chunk_memremote.go index 5806239c21..a9543e5fa8 100644 --- a/seaweed-block/core/storage/chunk_memremote.go +++ b/seaweed-block/core/storage/chunk_memremote.go @@ -10,67 +10,54 @@ import ( "context" "crypto/sha256" "fmt" - "sort" "sync" - "time" ) type MemChunkRemote struct { - mu sync.Mutex - objs map[string][]byte - ever map[string]bool - head chunkHead - puts int - intents map[string]chunkIntent + mu sync.Mutex + objs map[string][]byte + ever map[string]bool + head chunkHead + puts int + // session is the open cut session ("" = none); sessions counts every + // Begin that opened one, aborts every Abort that ended one. + session string + sessions, aborts int } func NewMemChunkRemote() *MemChunkRemote { - return &MemChunkRemote{objs: map[string][]byte{}, ever: map[string]bool{}, intents: map[string]chunkIntent{}} + return &MemChunkRemote{objs: map[string][]byte{}, ever: map[string]bool{}} } -func (m *MemChunkRemote) PutIntent(ctx context.Context, in chunkIntent) (string, error) { +// Begin opens the cut's session, or replays the open one. +func (m *MemChunkRemote) Begin(ctx context.Context) (string, error) { if err := ctx.Err(); err != nil { return "", err } - for _, k := range in.Keys { - if err := validChunkKey(k); err != nil { - return "", err - } - } - id, err := newChunkIntentID(in.Gen) - if err != nil { - return "", err - } - in.ID, in.CreatedNs, in.Keys = id, time.Now().UnixNano(), append([]string(nil), in.Keys...) m.mu.Lock() defer m.mu.Unlock() - m.intents[id] = in - return id, nil + if m.session == "" { + m.sessions++ + m.session = fmt.Sprintf("s%d", m.sessions) + } + return m.session, nil } -func (m *MemChunkRemote) DeleteIntent(ctx context.Context, id string) error { - if err := ctx.Err(); err != nil { - return err - } +// Abort ends the open session without a commit. +func (m *MemChunkRemote) Abort() { m.mu.Lock() defer m.mu.Unlock() - delete(m.intents, id) - return nil + if m.session != "" { + m.aborts++ + m.session = "" + } } -func (m *MemChunkRemote) ListIntents(ctx context.Context) ([]chunkIntent, error) { - if err := ctx.Err(); err != nil { - return nil, err - } +// OpenSession is the open session ("" = none), for tests. +func (m *MemChunkRemote) OpenSession() string { m.mu.Lock() defer m.mu.Unlock() - out := make([]chunkIntent, 0, len(m.intents)) - for _, in := range m.intents { - in.Keys = append([]string(nil), in.Keys...) - out = append(out, in) - } - sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) - return out, nil + return m.session } func (m *MemChunkRemote) Put(ctx context.Context, key string, data []byte) error { @@ -136,6 +123,7 @@ func (m *MemChunkRemote) CASHead(ctx context.Context, expected chunkHeadVersion, installed := copyHead(next) installed.Gen = m.head.Gen + 1 m.head = installed + m.session = "" // the commit ends the cut's session return installed.Gen, nil } diff --git a/seaweed-block/core/storage/chunk_noop_cut_gen_test.go b/seaweed-block/core/storage/chunk_noop_cut_gen_test.go new file mode 100644 index 0000000000..9af0d9423a --- /dev/null +++ b/seaweed-block/core/storage/chunk_noop_cut_gen_test.go @@ -0,0 +1,41 @@ +package storage + +import "testing" + +// A no-op cut fences only when HEAD's identity or image differs from the one +// this holder published, as the CAS path does. HEAD's generation alone may +// move without either (a settlement that aborts the holder's session +// rewrites HEAD as it was): the holder stays healthy and its no-op cut +// completes on the newer generation. +func TestNoopCutDoesNotFenceOnAGenerationOnlyMove(t *testing.T) { + s, f, l, w := precopyLayer(t, 1024, 0) + w.write(t, s, 1, 0x41) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + h, err := f.GetHead(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + // The same HEAD written again: a new generation, same identity and image. + if _, err := f.CASHead(ctTimeout(t), ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, copyHead(h)); err != nil { + t.Fatal(err) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil || l.Fenced() { + t.Fatalf("a no-op cut after a generation-only move: %v (fenced %v); want it to complete", err, l.Fenced()) + } + if !r.Noop { + t.Fatalf("cut %+v; want a no-op", r) + } + // A different image (or identity) still fences, as before. + h2, _ := f.GetHead(ctTimeout(t)) + moved := copyHead(h2) + moved.Holder = "another-host" + if _, err := f.CASHead(ctTimeout(t), ChunkHeadVersion{Gen: h2.Gen, Epoch: h2.Epoch}, moved); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctTimeout(t)); err == nil || !l.Fenced() { + t.Fatalf("a no-op cut over another holder's HEAD: %v (fenced %v); want fenced", err, l.Fenced()) + } +} diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 526e52c9e7..b18407cf38 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -32,7 +32,6 @@ type PrecopyFixedParts struct { PublishPrepare time.Duration `json:"publishPrepareNs"` Manifest time.Duration `json:"manifestNs"` CommitState time.Duration `json:"commitStateNs"` - IntentCleanup time.Duration `json:"intentCleanupNs"` NonPayloadCopy time.Duration `json:"nonPayloadCopyNs"` Drain time.Duration `json:"drainNs"` @@ -45,7 +44,7 @@ type PrecopyFixedParts struct { } func precopyFixedParts(st chunkCutStats, fixed time.Duration) PrecopyFixedParts { - p := PrecopyFixedParts{SyncPhases: st.SyncPhases, Candidate: time.Duration(st.CandidateNs), WindowSetup: time.Duration(st.WindowSetupNs), PublishPrepare: time.Duration(st.PublishPrepareNs), Manifest: time.Duration(st.ManifestNs), CommitState: time.Duration(st.CommitStateNs), IntentCleanup: time.Duration(st.IntentCleanupNs), NonPayloadCopy: time.Duration(st.NonPayloadCopyNs), Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs), MapPersist: time.Duration(st.MapPersistNs)} + p := PrecopyFixedParts{SyncPhases: st.SyncPhases, Candidate: time.Duration(st.CandidateNs), WindowSetup: time.Duration(st.WindowSetupNs), PublishPrepare: time.Duration(st.PublishPrepareNs), Manifest: time.Duration(st.ManifestNs), CommitState: time.Duration(st.CommitStateNs), NonPayloadCopy: time.Duration(st.NonPayloadCopyNs), Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs), MapPersist: time.Duration(st.MapPersistNs)} p.Other = max(time.Duration(0), fixed-p.measured()) return p } @@ -495,7 +494,7 @@ func comparablePrecopyAttempt(a *PrecopyAttempt) bool { } func (p PrecopyFixedParts) measured() time.Duration { - return p.Drain + p.StoreLock + p.DataSync + p.HeadCAS + p.HeadReadback + p.MapPersist + p.Candidate + p.WindowSetup + p.PublishPrepare + p.Manifest + p.CommitState + p.IntentCleanup + p.NonPayloadCopy + return p.Drain + p.StoreLock + p.DataSync + p.HeadCAS + p.HeadReadback + p.MapPersist + p.Candidate + p.WindowSetup + p.PublishPrepare + p.Manifest + p.CommitState + p.NonPayloadCopy } // Candidate count is conservative and advisory while guest writes continue. diff --git a/seaweed-block/core/storage/chunk_precopy_detach_test.go b/seaweed-block/core/storage/chunk_precopy_detach_test.go index a309e22c97..7389efaaaf 100644 --- a/seaweed-block/core/storage/chunk_precopy_detach_test.go +++ b/seaweed-block/core/storage/chunk_precopy_detach_test.go @@ -41,13 +41,13 @@ func TestPrecopyDetachConvergesBeforeStoppingIO(t *testing.T) { if !bytes.Equal(got, want) { t.Fatal("detached HEAD differs from local image") } - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } func TestPrecopyDetachUnsettledRoundsKeepDirtyBytes(t *testing.T) { s, f, l, w := precopyLayer(t, 1024, 1) // Fail before publication, after a candidate image has been collected. - f.failPutIntent = errFakeRemoteDown + f.failBegin = errFakeRemoteDown stopped := 0 _, err := l.PrecopyDetach(ctTimeout(t), func() bool { stopped++; return true }) if !errors.Is(err, ErrPrecopyUnknown) || stopped != 0 { @@ -56,7 +56,7 @@ func TestPrecopyDetachUnsettledRoundsKeepDirtyBytes(t *testing.T) { if f.stats().head.State == ChunkHeadDetached { t.Fatal("failed rounds detached") } - f.failPutIntent = nil + f.failBegin = nil r, err := l.Cut(ctTimeout(t)) if err != nil { t.Fatal(err) @@ -248,12 +248,23 @@ func TestPrecopyDetachSustainedWrapFlushAndFreshRestore(t *testing.T) { next.Holder = "host-b" next.FreshFromHead = true next.RestoreChunkBytes = ctChunkBytes - next.PrepareRestore = func(h ChunkHead) error { return fresh.SeedChunkFrontier(h.RemoteLSN) } - h, err := ClaimChunkHead(ctTimeout(t), f, next) + // layout.Start owns the epoch transition in the B path. Publish the + // successor HEAD here so this engine test still checks sustained writes, + // detach and lazy fresh readback without calling the removed flat claim. + oldHead, err := f.GetHead(ctTimeout(t)) if err != nil { t.Fatal(err) } - next.RestoreGuard = &ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch} + if err := fresh.SeedChunkFrontier(oldHead.RemoteLSN); err != nil { + t.Fatal(err) + } + h := copyHead(oldHead) + h.Epoch, h.Holder, h.State, h.DetachedBy = next.Epoch, next.Holder, ChunkHeadActive, nil + gen, err := f.CASHead(ctTimeout(t), ChunkHeadVersion{Gen: oldHead.Gen, Epoch: oldHead.Epoch}, h) + if err != nil { + t.Fatal(err) + } + h.Gen = gen mustAttach(t, fresh, f, next) for lba := uint32(0); lba < ctNumBlocks; lba++ { got, err := fresh.Read(lba) diff --git a/seaweed-block/core/storage/chunk_public.go b/seaweed-block/core/storage/chunk_public.go index 8dcfb337a7..61f945c301 100644 --- a/seaweed-block/core/storage/chunk_public.go +++ b/seaweed-block/core/storage/chunk_public.go @@ -18,7 +18,6 @@ type ( ChunkCutResult = chunkCutResult ChunkCutStats = chunkCutStats ChunkLayerStats = chunkLayerStats - ChunkIntent = chunkIntent ChunkDetachedBy = chunkDetachedBy DetachSettlement = detachSettlement ) @@ -40,12 +39,6 @@ const ( ChunkHeadDeleted = chunkHeadDeleted ) -// NewChunkIntentID returns a fresh intent id "-" for a remote -// implementation's PutIntent; ValidChunkIntentID accepts exactly those ids. -func NewChunkIntentID(gen uint64) (string, error) { return newChunkIntentID(gen) } - -func ValidChunkIntentID(id string) bool { return validChunkIntentID(id) } - const ( ChunkBaseNone = chunkBaseNone ChunkBaseInstalling = chunkBaseInstalling @@ -71,7 +64,7 @@ var ( ) // ValidChunkKey enforces the chunk key domain (non-empty valid UTF-8); a -// remote implementation calls it in Put and, for every key, in PutIntent. +// remote implementation calls it in Put. func ValidChunkKey(key string) error { return validChunkKey(key) } // AttachChunkLayer attaches a chunk layer to an open, recovered WALStore. diff --git a/seaweed-block/core/storage/chunk_recency.go b/seaweed-block/core/storage/chunk_recency.go new file mode 100644 index 0000000000..e135373c3c --- /dev/null +++ b/seaweed-block/core/storage/chunk_recency.go @@ -0,0 +1,16 @@ +package storage + +// chunkRecency is a copy-order hint for the COW window: each candidate +// chunk's newest local write, bounded by the cut frontier. It is local, +// never persisted, never compared with HEAD or the store; correctness never +// depends on it. The caller holds captureMu exclusive, with no layer state +// lock held. +func (l *chunkLayerImpl) chunkRecency(candidates map[uint64]bool, frontier uint64) map[uint64]uint64 { + out := make(map[uint64]uint64, len(candidates)) + l.s.mu.RLock() + defer l.s.mu.RUnlock() + for idx := range candidates { + out[idx] = min(l.s.v3.mapEntries[idx].LSN, frontier) + } + return out +} diff --git a/seaweed-block/core/storage/chunk_birth_budget_test.go b/seaweed-block/core/storage/chunk_recency_budget_test.go similarity index 82% rename from seaweed-block/core/storage/chunk_birth_budget_test.go rename to seaweed-block/core/storage/chunk_recency_budget_test.go index fa832c474e..fc75b2ec12 100644 --- a/seaweed-block/core/storage/chunk_birth_budget_test.go +++ b/seaweed-block/core/storage/chunk_recency_budget_test.go @@ -7,7 +7,7 @@ import ( // Metadata-only maximum-volume/default-chunk shape; no volume-sized image or // device is allocated. This measures the added sampler, not a complete cut. -func BenchmarkCaptureBirthsMaxVolumeDefaultChunk(b *testing.B) { +func BenchmarkChunkRecencyMaxVolumeDefaultChunk(b *testing.B) { const count = 1 << 22 // ceil((16 TiB - 4 KiB) / 4 MiB) candidates := make(map[uint64]bool, count) s := &WALStore{v3: &walStoreV3State{mapEntries: make([]chunkLSNEntryV3, count), mapProof: newMapProofEpochV3()}} @@ -20,14 +20,14 @@ func BenchmarkCaptureBirthsMaxVolumeDefaultChunk(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { s.captureMu.Lock() - out := l.captureBirths(candidates, count) + out := l.chunkRecency(candidates, count) s.captureMu.Unlock() if len(out) != count || out[0] != 1 || out[count-1] != count { - b.Fatal("worst-shape birth mismatch") + b.Fatal("worst-shape recency mismatch") } } } -func TestCaptureBirthsIncludesStoreLockWait(t *testing.T) { +func TestChunkRecencyIncludesStoreLockWait(t *testing.T) { s := &WALStore{v3: &walStoreV3State{mapEntries: []chunkLSNEntryV3{{LSN: 7}}, mapProof: newMapProofEpochV3()}} l := &chunkLayerImpl{s: s} candidates := map[uint64]bool{0: true} @@ -44,7 +44,7 @@ func TestCaptureBirthsIncludesStoreLockWait(t *testing.T) { t.Error("sampler did not join") } }) - go func() { s.captureMu.Lock(); out := l.captureBirths(candidates, 7); s.captureMu.Unlock(); done <- out }() + go func() { s.captureMu.Lock(); out := l.chunkRecency(candidates, 7); s.captureMu.Unlock(); done <- out }() select { case out := <-done: done <- out diff --git a/seaweed-block/core/storage/chunk_reopen_belt_test.go b/seaweed-block/core/storage/chunk_reopen_belt_test.go deleted file mode 100644 index 23ee0e973d..0000000000 --- a/seaweed-block/core/storage/chunk_reopen_belt_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package storage - -import ( - "bytes" - "context" - "errors" - "fmt" - "testing" -) - -// A server-held CAS outlives its caller. No old-process code runs after the -// reopen: releaseDeferredCAS only evaluates the request's original guard. -func TestClaimChunkHeadSameOwnerReopenRejectsKilledProcessCAS(t *testing.T) { - for _, gen := range []uint64{0, 7} { - t.Run(fmt.Sprint(gen), func(t *testing.T) { - r := newFakeChunkRemote() - if gen != 0 { - r.head = ChunkHead{Gen: gen, Epoch: 2, Holder: "host-a", Chunks: map[uint64]ChunkRef{}} - } - old := copyHead(r.head) - old.Epoch, old.Holder = 2, "host-a" - old.RemoteLSN = 1 - r.casModes = []fakeCASMode{casDeferred} - if _, err := r.CASHead(context.Background(), ChunkHeadVersion{Gen: gen, Epoch: r.head.Epoch}, old); !errors.Is(err, errFakeCASUnknown) { - t.Fatal("old cut was not left in flight", err) - } - claimed, err := ClaimChunkHead(context.Background(), r, ctConfig(2)) - if err != nil { - t.Fatal(err) - } - if n := r.releaseDeferredCAS(); n != 0 { - t.Fatalf("killed process CAS landed after reopen: applied=%d claimedGen=%d", n, claimed.Gen) - } - if claimed.Gen != gen+1 || claimed.RemoteLSN != 0 || claimed.Epoch != 2 || claimed.Holder != "host-a" { - t.Fatalf("reopen must fence the old generation without changing the image or owner: %+v", claimed) - } - }) - } -} - -func TestClaimChunkHeadSameOwnerReopenPreservesSeal(t *testing.T) { - r := newFakeChunkRemote() - r.head = ChunkHead{Gen: 7, Epoch: 2, Holder: "host-a", RemoteLSN: 3, - State: ChunkHeadDetached, DetachedBy: &ChunkDetachedBy{Gen: 7, Epoch: 2, Holder: "host-a"}} - sealed := copyHead(r.head) - cfg := ctConfig(2) - prepared := false - cfg.PrepareRestore = func(ChunkHead) error { prepared = true; return nil } - _, err := ClaimChunkHead(context.Background(), r, cfg) - if !errors.Is(err, ErrChunkLayerDetached) || prepared || r.stats().cas != 0 || !sameHead(r.stats().head, sealed) { - t.Fatalf("reopen undid seal: err=%v prepared=%t CAS=%d HEAD=%+v", err, prepared, r.stats().cas, r.stats().head) - } - // The planned new holder can consume the sealed image at a higher epoch; - // it is a takeover, not a reopen of the sealed incarnation. - next, err := ClaimChunkHead(context.Background(), r, ChunkLayerConfig{Epoch: 3, Holder: "host-b"}) - if err != nil || next.Gen != 8 || next.RemoteLSN != 3 || next.State != ChunkHeadActive || next.DetachedBy != nil { - t.Fatalf("planned holder cannot claim preserved seal: HEAD=%+v err=%v", next, err) - } -} - -func TestHeadBeltSameOwnerReopenPreservesAcknowledgedWrites(t *testing.T) { - s, path, crash := crashableStore(t) - r := newFakeChunkRemote() - cfg := ctConfig(2) - old := mustAttach(t, s, r, cfg) - a := makeBlock(4096, 0x31) - b := makeBlock(4096, 0x42) - c := makeBlock(4096, 0x53) - if _, err := s.Write(0, a); err != nil { - t.Fatal(err) - } - if _, err := old.Cut(ctTimeout(t)); err != nil { - t.Fatal(err) - } - if _, err := s.Write(1, b); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - r.casModes = []fakeCASMode{casDeferred} - if _, err := old.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { - t.Fatal("old cut was not unresolved", err) - } - // Close removes the old local publisher but cannot cancel a request already - // retained by the server. It also must preserve that request's intent. - if err := old.Close(); err != nil { - t.Fatal(err) - } - crash() - s, _ = reopen(t, path) - claimed, err := ClaimChunkHead(ctTimeout(t), r, cfg) - if err != nil { - t.Fatal(err) - } - next := mustAttach(t, s, r, cfg) - landed := r.releaseDeferredCAS() - if _, err := s.Write(2, c); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - _, firstErr := next.Cut(ctTimeout(t)) - if firstErr != nil { - t.Logf("new process first CAS after late request: %v; fenced=%t", firstErr, next.Fenced()) - if _, err := next.Cut(ctTimeout(t)); err != nil { - t.Fatal("retry lost the new process's progress", err) - } - } - image := r.imageOf(t, r.stats().head) - for i, want := range [][]byte{a, b, c} { - got, err := s.Read(uint32(i)) - if err != nil || !bytes.Equal(got, want) || !bytes.Equal(image[i*4096:(i+1)*4096], want) { - t.Fatalf("acknowledged block %d lost locally or remotely: %v", i, err) - } - } - if landed != 0 || firstErr != nil { - t.Fatalf("reopen did not exclude old CAS: landed=%d claimedGen=%d firstErr=%v (all acknowledged bytes survived retry)", landed, claimed.Gen, firstErr) - } -} diff --git a/seaweed-block/core/storage/chunk_restore.go b/seaweed-block/core/storage/chunk_restore.go deleted file mode 100644 index fb83e12467..0000000000 --- a/seaweed-block/core/storage/chunk_restore.go +++ /dev/null @@ -1,122 +0,0 @@ -package storage - -import ( - "context" - "errors" - "fmt" -) - -// ClaimChunkHead transfers only HEAD ownership, never chunk bodies. Epoch is -// supplied by the master's projection, not allocated here. The caller must -// persist lazy-read absence before exposing the local volume for I/O. -// No WALStore, layer-state or provider-map lock is held across remote calls; -// the provider may hold its per-volume attach serialization lock. -// On a proven owner fence, the returned HEAD is the exact observed proof; -// it is not an installed claim and must never be used to serve I/O. -func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfig) (ChunkHead, error) { - if remote == nil || cfg.Epoch == 0 || cfg.Holder == "" { - return ChunkHead{}, errors.New("storage: HEAD claim needs master epoch and holder") - } - if err := validateHeadCoolingWindow(cfg.HeadCoolingWindow); err != nil { - return ChunkHead{}, err - } - allowed := func() error { - if err := ctx.Err(); err != nil { - return err - } - if cfg.CaptureAllowed != nil { - return cfg.CaptureAllowed() - } - return nil - } - if err := allowed(); err != nil { - return ChunkHead{}, err - } - head, err := remote.GetHead(ctx) - if err != nil { - return ChunkHead{}, err - } - if head.Epoch > cfg.Epoch || (head.Gen != 0 && head.Epoch == cfg.Epoch && head.Holder != cfg.Holder) { - return copyHead(head), ErrChunkLayerFenced - } - // INV-WS-SEALED-REOPEN-001: the sealing incarnation cannot reopen its - // committed handoff proof. A higher-epoch takeover remains a separate claim. - if chunkHeadIsDetached(head) && head.Epoch == cfg.Epoch && head.Holder == cfg.Holder { - return copyHead(head), ErrChunkLayerDetached - } - // Preparation uses exactly the validated image this CAS will protect. - // A failing seed cannot fence the old holder before this host is ready. - if cfg.PrepareRestore != nil { - if err := cfg.PrepareRestore(copyHead(head)); err != nil { - return ChunkHead{}, fmt.Errorf("storage: prepare HEAD restore: %w", err) - } - } - if err := allowed(); err != nil { - return ChunkHead{}, err - } - // INV-WS-HEAD-BELT-001: even the same owner must replace the generation - // before serving. A killed incarnation may have left a CAS in flight; - // readback alone cannot invalidate that request's original precondition. - // An empty HEAD also needs an exclusive create before an old first cut. - next := copyHead(head) - next.Epoch, next.Holder = cfg.Epoch, cfg.Holder - // A new holder's takeover starts serving the same image as active. The - // previous holder's final-cut proof belongs only to its detached HEAD. - next.State, next.DetachedBy = chunkHeadActive, nil - var intents []string - settled := true // no root RPC sent yet - defer func() { - if settled { - for _, id := range intents { - _ = remote.DeleteIntent(ctx, id) - } - } - }() - if builder, ok := remote.(ChunkManifestBuilder); ok && next.Segments == nil && len(next.Chunks) != 0 { - if cfg.RestoreChunkBytes == 0 { - return ChunkHead{}, errors.New("storage: legacy HEAD claim needs validated chunk geometry") - } - next, intents, err = builder.PrepareManifest(ctx, head, next, cfg.RestoreChunkBytes) - if err != nil { - return ChunkHead{}, err - } - } - if err := allowed(); err != nil { - return ChunkHead{}, err - } - settled = false // an ambiguous CAS keeps its segment intents - gen, casErr := casChunkHead(ctx, remote, ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next) - if casErr == nil { - next.Gen = gen - if err := confirmChunkTakeover(ctx, remote, next, cfg.HeadCoolingWindow); err != nil { - return ChunkHead{}, err - } - if err := allowed(); err != nil { - return ChunkHead{}, err - } - settled = true - return next, nil - } - // Never blindly replay a possibly committed takeover. A re-read must - // prove the exact proposal; otherwise the volume remains nonoperational. - current, readErr := readChunkHead(ctx, remote) - if readErr != nil { - return ChunkHead{}, fmt.Errorf("storage: HEAD claim unresolved: %w", errors.Join(casErr, readErr)) - } - if current.Gen > head.Gen && sameProposal(current, next) { - if err := confirmChunkTakeover(ctx, remote, current, cfg.HeadCoolingWindow); err != nil { - return ChunkHead{}, err - } - if err := allowed(); err != nil { - return ChunkHead{}, err - } - settled = true - return current, nil - } - // A foreign publication is a fence, not permission to clean our roots. - if current.Gen != 0 && (current.Epoch != head.Epoch || current.Holder != head.Holder) { - return copyHead(current), fmt.Errorf("storage: HEAD claim displaced: %w", ErrChunkLayerFenced) - } - settled = errors.Is(casErr, ErrChunkHeadPrecondition) || current.Gen > head.Gen - return ChunkHead{}, fmt.Errorf("storage: HEAD claim not installed: %w", casErr) -} diff --git a/seaweed-block/core/storage/chunk_restore_test.go b/seaweed-block/core/storage/chunk_restore_test.go index 3065dbd2d7..a1df711407 100644 --- a/seaweed-block/core/storage/chunk_restore_test.go +++ b/seaweed-block/core/storage/chunk_restore_test.go @@ -29,86 +29,7 @@ func (r *claimFaultRemote) GetHead(ctx context.Context) (ChunkHead, error) { return r.ChunkRemote.GetHead(ctx) } -func TestClaimChunkHeadSettlesUnknownWithoutReplay(t *testing.T) { - for _, applied := range []bool{false, true} { - for _, failRead := range []bool{false, true} { - remote := NewMemChunkRemote() - if _, err := remote.CASHead(context.Background(), ChunkHeadVersion{}, ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7, Chunks: map[uint64]ChunkRef{}}); err != nil { - t.Fatal(err) - } - fault := &claimFaultRemote{ChunkRemote: remote, applied: applied, failRead: failRead} - head, err := ClaimChunkHead(context.Background(), fault, ChunkLayerConfig{Epoch: 2, Holder: "new"}) - if (err == nil) != (applied && !failRead) { - t.Fatalf("applied=%v readFail=%v err=%v", applied, failRead, err) - } - if fault.calls != 1 { - t.Fatalf("CAS replayed %d times", fault.calls) - } - if err == nil && (head.Epoch != 2 || head.Holder != "new" || head.RemoteLSN != 7) { - t.Fatal(head) - } - } - } -} - -func TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift(t *testing.T) { - remote := NewMemChunkRemote() - _, err := remote.CASHead(context.Background(), ChunkHeadVersion{}, ChunkHead{Epoch: 3, Holder: "current", Chunks: map[uint64]ChunkRef{}}) - if err != nil { - t.Fatal(err) - } - for _, cfg := range []ChunkLayerConfig{{Epoch: 2, Holder: "old"}, {Epoch: 3, Holder: "other"}} { - if _, err := ClaimChunkHead(context.Background(), remote, cfg); !errors.Is(err, ErrChunkLayerFenced) { - t.Fatalf("stale claim accepted: %v", err) - } - } - before, _ := remote.GetHead(context.Background()) - checks := 0 - _, err = ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 4, Holder: "new", CaptureAllowed: func() error { - checks++ - if checks == 2 { - return errors.New("lineage moved") - } - return nil - }}) - after, _ := remote.GetHead(context.Background()) - if err == nil || after.Gen != before.Gen || after.Epoch != 3 { - t.Fatalf("drift published: head=%+v err=%v", after, err) - } - // Reopening the same owner preserves the image but fences its old generation. - if _, err := ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 3, Holder: "current"}); err != nil { - t.Fatal(err) - } - final, _ := remote.GetHead(context.Background()) - if final.Gen != before.Gen+1 || final.RemoteLSN != before.RemoteLSN { - t.Fatal("same-owner reopen did not replace only the generation") - } -} - -func TestClaimChunkHeadFencesNoopCut(t *testing.T) { - s, _ := newChunkTestStore(t) - remote := newFakeChunkRemote() - layer := mustAttach(t, s, remote, ctConfig(1)) - if _, err := s.Write(0, makeBlock(4096, 0xAA)); err != nil { - t.Fatal(err) - } - if _, err := layer.Capture(ctTimeout(t)); err != nil { - t.Fatal(err) - } - if _, err := ClaimChunkHead(ctTimeout(t), remote, ChunkLayerConfig{Epoch: 2, Holder: "host-b"}); err != nil { - t.Fatal(err) - } - if _, err := layer.Capture(ctTimeout(t)); !errors.Is(err, ErrChunkLayerFenced) { - t.Fatalf("stale no-op cut returned %v, want fenced", err) - } - if !layer.Fenced() { - t.Fatal("no-op cut did not propagate fence") - } -} - -// A no-op cut still consults remote authority. An outage there is retryable -// remote unavailability, not an untyped failure or an ownership fence. -func TestClaimChunkHeadNoopCutClassifiesRemoteReadFailure(t *testing.T) { +func TestChunkNoopCutClassifiesRemoteReadFailure(t *testing.T) { s, _ := newChunkTestStore(t) remote := newFakeChunkRemote() layer := mustAttach(t, s, remote, ctConfig(1)) diff --git a/seaweed-block/core/storage/chunk_review271_test.go b/seaweed-block/core/storage/chunk_review271_test.go index 9ddeafd667..57a1538643 100644 --- a/seaweed-block/core/storage/chunk_review271_test.go +++ b/seaweed-block/core/storage/chunk_review271_test.go @@ -8,36 +8,38 @@ import ( "errors" "path/filepath" "runtime" + "strings" "sync" "sync/atomic" "testing" "time" ) -func TestCutPayloadIntentCountIndependentOfCandidates(t *testing.T) { +func TestCutPayloadSessionBeginsIndependentOfCandidates(t *testing.T) { for _, n := range []int{4, 8} { _, f, l, _ := precopyLayer(t, 0, n) l.cfg.UploadConcurrency = 1 - before := len(f.putIntents) mark := len(f.stats().ops) r, err := l.Cut(ctTimeout(t)) if err != nil { t.Fatal(err) } - rooted := map[string]bool{} - for _, in := range f.putIntents[before:] { - for _, key := range in.Keys { - rooted[key] = true + ops := opsSince(f, mark) + open, begins := false, 0 + for _, op := range ops { + switch { + case strings.HasPrefix(op, "begin:") && op != "begin:fail": + open = true + begins++ + case strings.HasPrefix(op, "abort:"), op == "cas:ok": + open = false + } + if k, ok := strings.CutPrefix(op, "put:"); ok && !open { + t.Fatalf("upload %s outside an open session", k) } } - for _, key := range uploadedKeys(opsSince(f, mark)) { - if !rooted[key] { - t.Fatalf("unrooted upload %s", key) - } - } - calls := len(f.putIntents) - before - if calls > 1+r.Stats.StageRounds { - t.Fatalf("candidates=%d intent writes=%d rounds=%d", n, calls, r.Stats.StageRounds) + if begins > 1+r.Stats.StageRounds { + t.Fatalf("candidates=%d Begins=%d rounds=%d", n, begins, r.Stats.StageRounds) } } } @@ -71,27 +73,30 @@ func TestCutUploadRetriesPastThreeAttemptsAtSamePoint(t *testing.T) { } } -func TestChunkCloseDropsReusableButKeepsUnknownCASRoots(t *testing.T) { +// Close drops the reusable uploads and aborts a cut's open session, except +// while a commit is unresolved: its session stays for the settlement. +func TestChunkCloseAbortsTheOpenSessionUnlessACommitIsUnresolved(t *testing.T) { for _, pending := range []bool{false, true} { t.Run(map[bool]string{false: "known-abort", true: "unknown-CAS"}[pending], func(t *testing.T) { _, f, l, _ := precopyLayer(t, 0, 1) - id, err := f.PutIntent(context.Background(), chunkIntent{Keys: []string{"unpublished"}}) - if err != nil { + if _, err := f.Begin(context.Background()); err != nil { t.Fatal(err) } l.stMu.Lock() - l.reusable = map[uint64]stagedChunk{0: {capturedChunk: capturedChunk{intent: id}}} + l.reusable = map[uint64]stagedChunk{0: {}} if pending { l.pending = &chunkHead{Gen: 9} - l.pendingIntents = []string{id} } l.stMu.Unlock() - if err = l.Close(); err != nil { + if err := l.Close(); err != nil { t.Fatal(err) } - live := len(liveIntents(t, f)) - if (pending && live != 1) || (!pending && live != 0) { - t.Fatalf("pending=%v live=%d", pending, live) + open := f.openSession() != "" + if open != pending { + t.Fatalf("pending=%v: session open after Close=%v", pending, open) + } + if l.reusable != nil { + t.Fatal("Close kept the reusable uploads") } }) } @@ -202,7 +207,7 @@ func TestCutPayloadReadsOverlapEarlierUploadsWithinBudget(t *testing.T) { t.Cleanup(func() { cancel(); free(); cowWaitSignal(t, done, "overlap cleanup") }) go func() { defer close(done) - _, _, err := l.streamCutPayloads(ctx, []uint64{0, 1, 2}, chunkHead{}, false, func(_ context.Context, idx uint64) (capturedChunk, error) { + _, err := l.streamCutPayloads(ctx, []uint64{0, 1, 2}, chunkHead{}, false, func(_ context.Context, idx uint64) (capturedChunk, error) { if idx == 2 { close(readThird) } @@ -224,7 +229,7 @@ func TestCutPayloadReadsOverlapEarlierUploadsWithinBudget(t *testing.T) { } } -func TestCutPayloadIntentCountLargeCandidateSets(t *testing.T) { +func TestCutPayloadOneBeginForLargeCandidateSets(t *testing.T) { for _, n := range []int{256, 4096} { _, _, l, _ := precopyLayer(t, 0, 1) f := newFakeChunkRemote() @@ -233,12 +238,13 @@ func TestCutPayloadIntentCountLargeCandidateSets(t *testing.T) { for i := range batch { batch[i] = uint64(i) } - _, ids, err := l.streamCutPayloads(ctTimeout(t), batch, chunkHead{}, false, func(_ context.Context, idx uint64) (capturedChunk, error) { + _, err := l.streamCutPayloads(ctTimeout(t), batch, chunkHead{}, false, func(_ context.Context, idx uint64) (capturedChunk, error) { data := makeBlock(ctBlockSize, byte(idx%255+1)) return capturedChunk{idx: idx, data: data, sum: sha256.Sum256(data)}, nil }) - if err != nil || len(ids) != 1 || len(f.putIntents) != 1 || len(f.putIntents[0].Keys) != n { - t.Fatalf("D=%d intents=%d ids=%d err=%v", n, len(f.putIntents), len(ids), err) + ops := f.stats().ops + if err != nil || countOps(ops, "begin:") != 1 || len(uploadedKeys(ops)) != n { + t.Fatalf("D=%d Begins=%d uploads=%d err=%v", n, countOps(ops, "begin:"), len(uploadedKeys(ops)), err) } } } diff --git a/seaweed-block/core/storage/chunk_same_host_clean_test.go b/seaweed-block/core/storage/chunk_same_host_clean_test.go deleted file mode 100644 index 1dfb88a699..0000000000 --- a/seaweed-block/core/storage/chunk_same_host_clean_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package storage - -import ( - "bytes" - "errors" - "testing" -) - -// INV-WS-SAME-HOST-CLEAN-MOVE-001: the returning host consumes its sealed -// image only with a newly issued epoch; same-epoch reopening stays sealed. -func TestClaimChunkHeadSameHostCleanMovePreservesSealedImage(t *testing.T) { - s, _ := newChunkTestStore(t) - r := newFakeChunkRemote() - layer := mustAttach(t, s, r, ctConfig(1)) - want := makeBlock(4096, 0x63) - if _, err := s.Write(0, want); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if _, err := layer.Detach(ctTimeout(t)); err != nil { - t.Fatal(err) - } - sealed := copyHead(r.stats().head) - if _, err := ClaimChunkHead(ctTimeout(t), r, ctConfig(1)); !errors.Is(err, ErrChunkLayerDetached) || !sameHead(r.stats().head, sealed) { - t.Fatal("same-epoch reopen consumed the seal", err) - } - claimed, err := ClaimChunkHead(ctTimeout(t), r, ctConfig(2)) - if err != nil { - t.Fatal(err) - } - expected := copyHead(sealed) - expected.Gen++ - expected.Epoch = 2 - expected.State = ChunkHeadActive - expected.DetachedBy = nil - if !sameHead(claimed, expected) || !bytes.Equal(r.imageOf(t, claimed)[:4096], want) { - t.Fatalf("same-host claim changed sealed image/frontier: sealed=%+v claimed=%+v", sealed, claimed) - } -} diff --git a/seaweed-block/core/storage/chunk_seal_replay.go b/seaweed-block/core/storage/chunk_seal_replay.go deleted file mode 100644 index d1cb773ed2..0000000000 --- a/seaweed-block/core/storage/chunk_seal_replay.go +++ /dev/null @@ -1,27 +0,0 @@ -package storage - -import ( - "context" - "fmt" -) - -// ReadDetachedChunkHead implements INV-WS-SEAL-REPLAY-001. A re-sent seal -// succeeds only on this remote observation, never on a remembered result or -// a generation comparison with a previously observed root. It writes nothing. -func ReadDetachedChunkHead(ctx context.Context, remote ChunkRemote, epoch uint64, holder string) (ChunkHead, error) { - if remote == nil || epoch == 0 || holder == "" { - return ChunkHead{}, fmt.Errorf("%w: seal replay needs remote and assigned owner", ErrChunkCaptureRefused) - } - head, err := readChunkHead(ctx, remote) - if err != nil { - return ChunkHead{}, err - } - if head.Epoch != epoch || head.Holder != holder { - return ChunkHead{}, ErrChunkLayerFenced - } - proof := head.DetachedBy - if head.Gen == 0 || !chunkHeadIsDetached(head) || proof == nil || proof.Gen != head.Gen || proof.Epoch != epoch || proof.Holder != holder { - return ChunkHead{}, fmt.Errorf("%w: HEAD is not this owner's exact detached proof", ErrChunkCASOutcomeUnknown) - } - return copyHead(head), nil -} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index e1081f5421..13c281280d 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -28,12 +28,8 @@ package storage import ( "context" - "crypto/rand" - "encoding/hex" "errors" "fmt" - "strconv" - "strings" "time" "unicode/utf8" ) @@ -156,7 +152,6 @@ type chunkRef struct { Key string SHA256 [32]byte Encoding string - BirthLSN uint64 } // chunkHeadVersion is the CAS guard of HEAD. @@ -223,8 +218,7 @@ const ( func chunkHeadIsDetached(h chunkHead) bool { return h.State == chunkHeadDetached } // chunkRemote is the remote store. Keys are non-empty valid UTF-8 strings -// (validChunkKey); Put and PutIntent refuse any other key before writing -// anything. Keys are immutable: Put of a key that +// (validChunkKey); Put refuses any other key before writing anything. Keys are immutable: Put of a key that // exists, or once existed, fails with errChunkKeyExists and never replaces // stored bytes. CASHead installs next only when the stored HEAD matches // expected and returns the new generation; a mismatch fails with @@ -233,60 +227,27 @@ func chunkHeadIsDetached(h chunkHead) bool { return h.State == chunkHeadDetached // further CAS, never retries blindly, and reports no success or frontier // advance while it is unresolved. // -// Intents protect chunks a holder is about to publish (W5): GC treats every -// live intent as a root. A holder durably writes an intent naming the keys -// before it uploads the first of them (or, for a snapshot or fork, before it -// writes the manifest that references them), and deletes it after the HEAD -// CAS succeeds or the attempt is cleanly abandoned. -// - PutIntent stores in durably and returns its id, "-", -// unique per call; the id and CreatedNs it assigns are listed back. -// - DeleteIntent removes that one intent; a missing id is not an error. -// - ListIntents returns every live intent of the volume, or an error; it -// never skips an intent it cannot read. +// A cut runs in the holder's session (the layout kernel's Begin, Commit and +// Abort; Put of a content-named object is its Ensure): +// - Begin opens the session before the cut's first upload and returns it; +// a Begin while the session is open is its replay. Every object the cut +// writes belongs to the session until CASHead commits it. +// - Abort is the notice that a cut ended without a commit. It never +// blocks: the remote rolls the session back at its next HEAD read. type chunkRemote interface { Put(ctx context.Context, key string, data []byte) error Get(ctx context.Context, key string) ([]byte, error) GetHead(ctx context.Context) (chunkHead, error) CASHead(ctx context.Context, expected chunkHeadVersion, next chunkHead) (uint64, error) Delete(ctx context.Context, key string) error - PutIntent(ctx context.Context, in chunkIntent) (string, error) - DeleteIntent(ctx context.Context, id string) error - ListIntents(ctx context.Context) ([]chunkIntent, error) -} - -// chunkIntent is one live intent: the keys a holder at HEAD generation Gen -// and epoch Epoch is about to publish. -type chunkIntent struct { - Segments map[uint64]ChunkSegment - ChunkBytes uint64 - ID string // "-"; assigned by PutIntent - Gen uint64 - Epoch uint64 - Holder string - Keys []string - CreatedNs int64 // assigned by PutIntent - // DeadlineNs (unix ns) is a copy intent's publication deadline, kept as - // metadata: a GC sweep settles a dead copy attempt by claiming its - // publishing entry with a tombstone, never by the deadline alone (W5). - // 0 for capture intents. - DeadlineNs int64 -} - -// newChunkIntentID returns "-<16 lowercase hex digits>" from a random -// nonce. -func newChunkIntentID(gen uint64) (string, error) { - var b [8]byte - if _, err := rand.Read(b[:]); err != nil { - return "", fmt.Errorf("storage: intent nonce: %w", err) - } - return strconv.FormatUint(gen, 10) + "-" + hex.EncodeToString(b[:]), nil + Begin(ctx context.Context) (string, error) + Abort() } // validChunkKey is the chunk key domain: a non-empty, valid UTF-8 string. -// Every remote refuses any other key at Put and at PutIntent, before it -// persists anything, so a key protected by an intent always lists back -// byte-identical to the key stored (an encoding that replaced invalid -// bytes would otherwise protect a different key than the one stored). +// Every remote refuses any other key at Put, before it persists anything (an +// encoding that replaced invalid bytes would store another key than the +// one named). func validChunkKey(key string) error { if key == "" || !utf8.ValidString(key) { return fmt.Errorf("%w: %q", errChunkKeyInvalid, key) @@ -294,20 +255,6 @@ func validChunkKey(key string) error { return nil } -// validChunkIntentID accepts exactly the ids newChunkIntentID produces. -func validChunkIntentID(id string) bool { - gen, nonce, ok := strings.Cut(id, "-") - if !ok || len(nonce) != 16 || strings.ToLower(nonce) != nonce { - return false - } - v, err := strconv.ParseUint(gen, 10, 64) - if err != nil || strconv.FormatUint(v, 10) != gen { - return false - } - _, err = hex.DecodeString(nonce) - return err == nil -} - // chunkLayerConfig configures one attachment. type chunkLayerConfig struct { // OnPublishSettled, when set, is called once per confirmed publication @@ -348,16 +295,6 @@ type chunkLayerConfig struct { // with it and FreshFromHead: a fresh marker left by an earlier start, an // older binary or another opener is never trusted. CreatedThisStart bool - // RestoreGuard binds fresh attachment to the HEAD the provider claimed - // and durably seeded. A changed read refuses before hooks/readiness; the - // next recovery must repeat claim and seed. Nil is for direct layer users. - RestoreGuard *chunkHeadVersion - // PrepareRestore runs after ClaimChunkHead validates its observed HEAD - // and before any ownership CAS (also for an idempotent claim). The owner - // durably seeds the local frontier and rebases cached ship cursors here, - // while its frontend is gated. An error leaves remote ownership unchanged. - // No store/layer/remote lock is held across the callback. - PrepareRestore func(head chunkHead) error // RestoreChunkBytes is the local, validated geometry for upgrading a flat // legacy image during an ownership claim; it is never inferred from data. RestoreChunkBytes uint64 @@ -438,7 +375,6 @@ type chunkCutStats struct { PublishPrepareNs int64 ManifestNs int64 CommitStateNs int64 - IntentCleanupNs int64 NonPayloadCopyNs int64 PayloadNs int64 // disjoint streaming/copy/upload wall intervals diff --git a/seaweed-block/core/storage/chunk_seed_check_test.go b/seaweed-block/core/storage/chunk_seed_check_test.go new file mode 100644 index 0000000000..c2b801da82 --- /dev/null +++ b/seaweed-block/core/storage/chunk_seed_check_test.go @@ -0,0 +1,34 @@ +package storage + +import ( + "testing" +) + +// CanSeedChunkFrontier is the seed's own precondition: for every case the +// check and the seed agree (a refusal by one is a refusal by the other). +func TestCanSeedChunkFrontierAgreesWithTheSeed(t *testing.T) { + for _, c := range []struct { + name string + lsn uint64 + write bool // a local write beyond the checkpoint first + ok bool + }{ + {"a position with room for a next LSN", 7, false, true}, + {"no room for a next LSN", ^uint64(0), false, false}, + {"local writes beyond the checkpoint", 7, true, false}, + } { + t.Run(c.name, func(t *testing.T) { + s, _ := newChunkTestStore(t) + if c.write { + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil { + t.Fatal(err) + } + } + check := s.CanSeedChunkFrontier(c.lsn) + seed := s.SeedChunkFrontier(c.lsn) + if (check == nil) != c.ok || (seed == nil) != c.ok { + t.Fatalf("lsn %d: check %v, seed %v; want ok=%t for both", c.lsn, check, seed, c.ok) + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_birth_migration_test.go b/seaweed-block/core/storage/chunk_seed_image_test.go similarity index 71% rename from seaweed-block/core/storage/chunk_birth_migration_test.go rename to seaweed-block/core/storage/chunk_seed_image_test.go index 380532f0db..61b522b17f 100644 --- a/seaweed-block/core/storage/chunk_birth_migration_test.go +++ b/seaweed-block/core/storage/chunk_seed_image_test.go @@ -5,7 +5,7 @@ import ( "testing" ) -func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) { +func TestChunkSeededFrontierPreservesInheritedImage(t *testing.T) { s, _ := newChunkTestStore(t) if err := s.SeedChunkFrontier(7); err != nil { t.Fatal(err) @@ -17,7 +17,7 @@ func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) { cfg := ctConfig(2) cfg.FreshFromHead = true l := mustAttach(t, s, f, cfg) - newest, err := s.Write(0, makeBlock(ctBlockSize, 0x41)) + _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)) if err != nil { t.Fatal(err) } @@ -25,9 +25,6 @@ func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) { if err != nil { t.Fatal(err) } - if cut.Head.Chunks[1].BirthLSN != 7 || cut.Head.Chunks[0].BirthLSN != newest { - t.Fatalf("seeded image birth lost: %+v", cut.Head) - } want := bytes.Clone(image) copy(want, makeBlock(ctBlockSize, 0x41)) if !bytes.Equal(f.imageOf(t, cut.Head), want) { diff --git a/seaweed-block/core/storage/chunk_session_contract_test.go b/seaweed-block/core/storage/chunk_session_contract_test.go new file mode 100644 index 0000000000..1cce4fc7ee --- /dev/null +++ b/seaweed-block/core/storage/chunk_session_contract_test.go @@ -0,0 +1,67 @@ +package storage + +import ( + "context" + "testing" +) + +// sessionRemote is a test remote that reports its open session. +type sessionRemote interface { + chunkRemote + open() string +} + +type memSession struct{ *MemChunkRemote } + +func (m memSession) open() string { return m.OpenSession() } + +type fakeSession struct{ *fakeChunkRemote } + +func (f fakeSession) open() string { return f.openSession() } + +// checkSessionContract is the session contract every chunkRemote meets: +// Begin opens a session (a Begin while it is open replays it), Abort ends +// it and is idempotent, and a commit (a successful CASHead) ends it. +func checkSessionContract(t *testing.T, r sessionRemote) { + t.Helper() + ctx := context.Background() + if s := r.open(); s != "" { + t.Fatalf("a session is open before any Begin: %q", s) + } + a, err := r.Begin(ctx) + if err != nil || a == "" { + t.Fatalf("Begin: %q %v", a, err) + } + if again, err := r.Begin(ctx); err != nil || again != a { + t.Fatalf("Begin while %q is open: %q %v; want its replay", a, again, err) + } + r.Abort() + if s := r.open(); s != "" { + t.Fatalf("after Abort: session %q still open", s) + } + r.Abort() // nothing open: a no-op + b, err := r.Begin(ctx) + if err != nil || b == "" || b == a { + t.Fatalf("Begin after an Abort: %q %v; want a new session", b, err) + } + head, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + next := copyHead(head) + next.Epoch, next.Holder = 1, "host-a" + if _, err := r.CASHead(ctx, chunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next); err != nil { + t.Fatal(err) + } + if s := r.open(); s != "" { + t.Fatalf("after the commit: session %q still open", s) + } +} + +func TestMemChunkRemote_SessionContract(t *testing.T) { + checkSessionContract(t, memSession{NewMemChunkRemote()}) +} + +func TestFakeChunkRemote_SessionContract(t *testing.T) { + checkSessionContract(t, fakeSession{newFakeChunkRemote()}) +} diff --git a/seaweed-block/core/storage/chunk_stage_accounting_test.go b/seaweed-block/core/storage/chunk_stage_accounting_test.go index dc8a284789..3cb39b1254 100644 --- a/seaweed-block/core/storage/chunk_stage_accounting_test.go +++ b/seaweed-block/core/storage/chunk_stage_accounting_test.go @@ -85,7 +85,7 @@ func TestChunkStage_StagedChunksCountsAnInterruptedRound(t *testing.T) { w.write(t, s, uint32(c*ctChunkBlocks+2), 0) } f.mu.Lock() - f.failPutIntent = errors.New("intent refused") + f.failBegin = errors.New("intent refused") f.mu.Unlock() before := l.Stats().StagedChunks l.stMu.Lock() diff --git a/seaweed-block/core/storage/chunk_upload_parallel_test.go b/seaweed-block/core/storage/chunk_upload_parallel_test.go index 3536384d51..89aab81dce 100644 --- a/seaweed-block/core/storage/chunk_upload_parallel_test.go +++ b/seaweed-block/core/storage/chunk_upload_parallel_test.go @@ -36,8 +36,8 @@ func TestChunkUploads_DefaultOverlapsBeforeCAS(t *testing.T) { } } f.mu.Lock() - if len(f.intents) == 0 || f.casCalls != baselineCAS { - t.Error("overlapping uploads require a durable intent and no root CAS") + if f.session == "" || f.casCalls != baselineCAS { + t.Error("overlapping uploads require an open session and no root CAS") } f.mu.Unlock() _ = w @@ -94,7 +94,11 @@ func TestChunkUploads_ConfiguredBoundAndCancellation(t *testing.T) { if f.stats().cas != 0 { t.Fatal("cancelled upload published root") } - assertNoIntentsLeft(t, f) // joined abort; no publication can refer to its keys + // joined: no publication refers to its keys; its completed + // uploads stay reusable, so the session stays for the retry + if f.openSession() == "" { + t.Fatal("a cancelled cut dropped the session its reusable uploads belong to") + } }) } } @@ -175,8 +179,8 @@ func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) { t.Fatalf("returned with owned upload still active: %v", err) case <-time.After(20 * time.Millisecond): } - if len(liveIntents(t, f)) == 0 { - t.Fatal("intent removed before join") + if f.openSession() == "" { + t.Fatal("session aborted before join") } closed := make(chan struct{}) t.Cleanup(func() { release(); cowWaitSignal(t, closed, "upload close cleanup") }) @@ -198,8 +202,8 @@ func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) { if f.stats().cas != 0 { t.Fatal("failed batch published") } - assertNoIntentsLeft(t, f) cowWaitSignal(t, closed, "upload close") + assertNoSessionOpen(t, f) // Close ended the failed cut's session files, err := filepath.Glob(s.path + ".cut-cow-*") if err != nil || len(files) != 0 { t.Fatalf("payload files after join: %v %v", files, err) diff --git a/seaweed-block/core/storage/layout_fresh_mutators_test.go b/seaweed-block/core/storage/layout_fresh_mutators_test.go new file mode 100644 index 0000000000..1d2c81a199 --- /dev/null +++ b/seaweed-block/core/storage/layout_fresh_mutators_test.go @@ -0,0 +1,156 @@ +package storage + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "sort" + "strings" + "testing" +) + +// walStoreMethods classes every exported WALStore method by what a fresh +// local root allows: guest writes are refused while fresh; base and +// replication mutators, control and reads are not (a restore's base goes +// through them, so a fresh root never deadlocks its own restore). A new +// method fails until it is classed here. +var walStoreMethods = map[string]string{ + "Write": "guest (delegates to WriteContext)", "WriteContext": "guest: refused while fresh", + "WriteBatch": "guest (delegates to WriteBatchContext)", "WriteBatchContext": "guest: refused while fresh", + + "ApplyEntry": "replication", "WriteExtentDirect": "base (v3: install handle)", "AdvanceFrontier": "base/replication", + "BeginBaseInstall": "base", "CommitChunkAttachV3": "base", "SeedChunkFrontier": "base", "SyncInstallLog": "base", + "AdvanceWALTail": "replication", "FormatV3": "base", "Recover": "recovery", + + "SetLayoutIdentity": "control", "SetWMode": "control", "SetMultiBlockRecords": "control", "SetRecoveryRetentionLSNs": "control", + "SetRecycleFloorSource": "control", "AllowBaseRetirementV3": "control", "DeferBaseRetirementV3": "control", + "DisableAutoFlushForRecoveryTest": "test control", "ResetFlusherForMeasurement": "test control", "Sync": "control", "Close": "control", + + "AllBlocks": "read", "AppliedLSNs": "read", "CanSeedChunkFrontier": "read (the seed precondition, no write)", "BlockSize": "read", "StoreID": "read (the superblock UUID)", "ChunkBlocks": "read (immutable local map shape)", "Boundaries": "read", "CheckpointLSN": "read", + "CheckpointLSNForPOC": "read", "CheckpointPersistence": "read", "ChunkMapStatsV3": "read", "DataSyncPolicy": "read", + "DurabilityLatency": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", + "InstalledBaseLSN": "read", "LayoutIdentity": "read", "NextLSN": "read", "NumBlocks": "read", + "OwnerChunkAttachDurableV3": "read", "Read": "read", "ReadContext": "read", "RecoveryMode": "read", + "RecoveryRetentionLSNs": "read", "RecoveryWarnings": "read", "ScanLBAs": "read", "WALCapacityBytes": "read", + "WALSyncCount": "read", "WriteInstrumentation": "read", +} + +func TestWALStoreMutators_FreshGuardEnumeration(t *testing.T) { + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + found := map[string]*ast.FuncDecl{} + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + src, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + file, err := parser.ParseFile(token.NewFileSet(), f, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Recv == nil || !fn.Name.IsExported() { + continue + } + if st, ok := fn.Recv.List[0].Type.(*ast.StarExpr); ok { + if id, ok := st.X.(*ast.Ident); ok && id.Name == "WALStore" { + found[fn.Name.Name] = fn + } + } + } + } + var unclassed, gone []string + for n := range found { + if _, ok := walStoreMethods[n]; !ok { + unclassed = append(unclassed, n) + } + } + for n := range walStoreMethods { + if found[n] == nil { + gone = append(gone, n) + } + } + sort.Strings(unclassed) + sort.Strings(gone) + if len(unclassed)+len(gone) != 0 { + t.Fatalf("WALStore methods changed: class each (guest writes must check layoutFresh).\nnew: %v\ngone: %v", unclassed, gone) + } + for n, class := range walStoreMethods { + if class != "guest: refused while fresh" { + continue + } + guarded := false + ast.Inspect(found[n].Body, func(x ast.Node) bool { + if sel, ok := x.(*ast.SelectorExpr); ok && sel.Sel.Name == "layoutFresh" { + guarded = true + } + return true + }) + if !guarded { + t.Errorf("%s is a guest write and does not check layoutFresh", n) + } + } +} + +// A fresh root restores through the base path (never refused), refuses a +// guest write until fresh is cleared, then takes it; a crash after the base +// and before the clear reopens with the same claim id, still fresh, and +// the clear runs again (idempotent). +func TestLayoutFresh_RestoreThenFlipThenFirstGuestWrite(t *testing.T) { + p := filepath.Join(t.TempDir(), "s") + s, err := CreateWALStoreWithOptions(p, 64, 4096, WALStoreOptions{ChunkBlocks: 8}) + if err != nil { + t.Fatal(err) + } + if err := s.SetLayoutIdentity("k-r", true); err != nil { + t.Fatal(err) + } + h, err := s.BeginBaseInstall(7, [16]byte{1}) + if err != nil { + t.Fatalf("base install on a fresh root: %v", err) + } + base := blk(0x55) + if err := h.WriteBase(5, base); err != nil { + t.Fatalf("base write on a fresh root: %v", err) + } + if err := h.MarkBaseComplete(); err != nil { + t.Fatal(err) + } + if _, err := s.Write(6, blk(0x66)); err == nil { + t.Fatal("a guest write before the clear was accepted") + } + // Crash after the base, before the clear. + if err := s.Close(); err != nil { + t.Fatal(err) + } + s, err = OpenWALStore(p) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if id, fresh, ok := s.LayoutIdentity(); !ok || id != "k-r" || !fresh { + t.Fatalf("after the crash: %q fresh %t ok %t; want the same claim id, still fresh", id, fresh, ok) + } + for i := 0; i < 2; i++ { + if err := s.SetLayoutIdentity("k-r", false); err != nil { + t.Fatalf("clear #%d: %v", i+1, err) + } + } + if _, err := s.Write(6, blk(0x66)); err != nil { + t.Fatalf("first guest write after the clear: %v", err) + } + if got, err := s.Read(5); err != nil || got[0] != 0x55 { + t.Fatalf("base block after restore: %x %v", got[:1], err) + } +} diff --git a/seaweed-block/core/storage/layout_identity_v3_test.go b/seaweed-block/core/storage/layout_identity_v3_test.go new file mode 100644 index 0000000000..9f306fa474 --- /dev/null +++ b/seaweed-block/core/storage/layout_identity_v3_test.go @@ -0,0 +1,146 @@ +package storage + +import ( + "errors" + "path/filepath" + "strings" + "testing" +) + +// The layout identity is one atomic descriptor field set: written before a +// claim, durable across a close and a reopen, flipped to not-fresh, and +// bounded; a store that never set it reports none. +func TestLayoutIdentityIsDurableInTheDescriptor(t *testing.T) { + p := filepath.Join(t.TempDir(), "s") + s, err := CreateWALStoreWithOptions(p, 64, 4096, WALStoreOptions{ChunkBlocks: 8}) + if err != nil { + t.Fatal(err) + } + if _, _, ok := s.LayoutIdentity(); ok { + t.Fatal("a new store reports a layout identity") + } + if err := s.SetLayoutIdentity("k-1234", true); err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + s, err = OpenWALStore(p) + if err != nil { + t.Fatal(err) + } + if id, fresh, ok := s.LayoutIdentity(); !ok || id != "k-1234" || !fresh { + t.Fatalf("after reopen: %q fresh %t ok %t", id, fresh, ok) + } + if err := s.SetLayoutIdentity("k-1234", false); err != nil { + t.Fatal(err) + } + for _, bad := range []string{"", strings.Repeat("k", MaxLayoutClaimIDBytes+1), "a\xff"} { + if err := s.SetLayoutIdentity(bad, false); err == nil { + t.Errorf("claim id %q accepted", bad) + } + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + s, err = OpenWALStore(p) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if id, fresh, ok := s.LayoutIdentity(); !ok || id != "k-1234" || fresh { + t.Fatalf("after the fresh flip and reopen: %q fresh %t ok %t", id, fresh, ok) + } +} + +// The identity bytes decode strictly: unknown flags, a length out of +// bounds, bytes after the claim id, or bytes without the identity are +// refused; the round trip is exact. +func TestLayoutIdentityDecodeIsStrict(t *testing.T) { + d := descriptorV3{LayoutSet: true, LayoutFresh: true, LayoutClaimID: "k"} + b := d.encode() + var got descriptorV3 + if err := decodeLayoutIdentityV3(&got, b[88:122]); err != nil || !got.LayoutSet || !got.LayoutFresh || got.LayoutClaimID != "k" { + t.Fatalf("round trip: %+v %v", got, err) + } + for name, mut := range map[string]func(x []byte){ + "unknown flag": func(x []byte) { x[0] |= 0x80 }, + "zero length": func(x []byte) { x[1] = 0 }, + "too long": func(x []byte) { x[1] = MaxLayoutClaimIDBytes + 1 }, + "after the claim id": func(x []byte) { x[2+1] = 'z' }, + "without identity": func(x []byte) { x[0] = 0 }, + } { + x := append([]byte(nil), b[88:122]...) + mut(x) + if err := decodeLayoutIdentityV3(&descriptorV3{}, x); err == nil { + t.Errorf("%s accepted", name) + } + } +} + +// The identity is written once: another claim id on a root that has one, +// and fresh coming back after it was cleared, are refused and change +// nothing. +func TestLayoutIdentityIsImmutable(t *testing.T) { + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "s"), 64, 4096, WALStoreOptions{ChunkBlocks: 8}) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if err := s.SetLayoutIdentity("k-1", true); err != nil { + t.Fatal(err) + } + if err := s.SetLayoutIdentity("k-2", true); err == nil { + t.Fatal("a second claim id replaced the root's") + } + if err := s.SetLayoutIdentity("k-1", false); err != nil { + t.Fatal(err) + } + if err := s.SetLayoutIdentity("k-1", true); err == nil { + t.Fatal("a root that held writes became fresh again") + } + if id, fresh, ok := s.LayoutIdentity(); !ok || id != "k-1" || fresh { + t.Fatalf("after the refused changes: %q fresh %t", id, fresh) + } +} + +// Fresh is a property of the root: while it is set no guest write (single +// or batch) is acknowledged; once cleared (durably, before the write) the +// root takes writes, and a reopen keeps it cleared. +func TestLayoutFreshRefusesGuestWrites(t *testing.T) { + p := filepath.Join(t.TempDir(), "s") + s, err := CreateWALStoreWithOptions(p, 64, 4096, WALStoreOptions{ChunkBlocks: 8}) + if err != nil { + t.Fatal(err) + } + if err := s.SetLayoutIdentity("k-1", true); err != nil { + t.Fatal(err) + } + blk := make([]byte, 4096) + if _, err := s.Write(0, blk); !errors.Is(err, ErrLayoutFresh) { + t.Fatalf("write to a fresh root: %v; want ErrLayoutFresh", err) + } + if _, err := s.WriteBatch(0, [][]byte{blk}); !errors.Is(err, ErrLayoutFresh) { + t.Fatalf("batch write to a fresh root: %v; want ErrLayoutFresh", err) + } + if err := s.SetLayoutIdentity("k-1", false); err != nil { + t.Fatal(err) + } + if _, err := s.Write(0, blk); err != nil { + t.Fatalf("write after fresh cleared: %v", err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + s, err = OpenWALStore(p) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, blk); err != nil { + t.Fatalf("write after reopen: %v", err) + } +} diff --git a/seaweed-block/core/storage/legacy_replacement_v3_test.go b/seaweed-block/core/storage/legacy_replacement_v3_test.go index d42746d6cd..b3e7565818 100644 --- a/seaweed-block/core/storage/legacy_replacement_v3_test.go +++ b/seaweed-block/core/storage/legacy_replacement_v3_test.go @@ -1617,5 +1617,5 @@ func TestNativeReplacementRecoverInvalidatesStagedImage(t *testing.T) { if !bytes.Equal(f.imageOf(t, cut.Head)[:ctBlockSize], want) { t.Fatal("cut reused bytes staged before native Recover") } - assertNoIntentsLeft(t, f) + assertNoSessionOpen(t, f) } diff --git a/seaweed-block/core/storage/superblock_v3.go b/seaweed-block/core/storage/superblock_v3.go index b7d3e7ffc3..da6cab7cc2 100644 --- a/seaweed-block/core/storage/superblock_v3.go +++ b/seaweed-block/core/storage/superblock_v3.go @@ -102,13 +102,28 @@ type descriptorV3 struct { BaseInstallID [16]byte WMode WMode MigrationPhase MigrationPhase + + // The layout identity of this local root: the claim id its marker + // carries (written before any claim) and whether the root is fresh + // (until its restore base is durable). Bytes 88-122 of the slot. + LayoutSet bool + LayoutFresh bool + LayoutClaimID string } +// MaxLayoutClaimIDBytes bounds the claim id the descriptor holds. +const MaxLayoutClaimIDBytes = 32 + +const ( + layoutFlagSet = 1 << 0 + layoutFlagFresh = 1 << 1 +) + var crc32cTable = crc32.MakeTable(crc32.Castagnoli) // reservedRangesV3 are the [start, end) byte ranges that must be zero. var reservedRangesV3 = [][2]int{ - {9, 12}, {88, 128}, {164, 168}, {240, 256}, {273, 280}, {306, slotCRCOffsetV3}, + {9, 12}, {122, 128}, {164, 168}, {240, 256}, {273, 280}, {306, slotCRCOffsetV3}, } // encode serializes d into one sealed slot. It does not validate; callers @@ -131,6 +146,14 @@ func (d *descriptorV3) encode() []byte { le.PutUint64(b[64:], d.CreatedAt) le.PutUint64(b[72:], d.SlotGen) le.PutUint64(b[80:], d.CheckpointLSN) + if d.LayoutSet { + b[88] = layoutFlagSet + if d.LayoutFresh { + b[88] |= layoutFlagFresh + } + b[89] = uint8(len(d.LayoutClaimID)) + copy(b[90:90+MaxLayoutClaimIDBytes], d.LayoutClaimID) + } copy(b[128:144], d.Nonce[:]) le.PutUint64(b[144:], d.RetainedTail) le.PutUint64(b[152:], d.RetainedHead) @@ -198,6 +221,9 @@ func decodeSlotV3(b []byte, accept slotImplAcceptor) (descriptorV3, error) { d.CreatedAt = le.Uint64(b[64:]) d.SlotGen = le.Uint64(b[72:]) d.CheckpointLSN = le.Uint64(b[80:]) + if err := decodeLayoutIdentityV3(&d, b[88:122]); err != nil { + return descriptorV3{}, err + } copy(d.Nonce[:], b[128:144]) d.RetainedTail = le.Uint64(b[144:]) d.RetainedHead = le.Uint64(b[152:]) @@ -220,6 +246,29 @@ func decodeSlotV3(b []byte, accept slotImplAcceptor) (descriptorV3, error) { return d, nil } +// decodeLayoutIdentityV3 reads the layout identity bytes (88-122): a flags +// byte, a length, the claim id, zero after it; unset means all zero. +func decodeLayoutIdentityV3(d *descriptorV3, b []byte) error { + flags, n := b[0], int(b[1]) + if flags&^(layoutFlagSet|layoutFlagFresh) != 0 { + return invalidV3("layout identity flags %#x", flags) + } + if flags&layoutFlagSet == 0 { + if i := firstNonZero(b); i >= 0 { + return invalidV3("layout identity byte %d set without the identity", 88+i) + } + return nil + } + if n == 0 || n > MaxLayoutClaimIDBytes { + return invalidV3("layout claim id of %d bytes", n) + } + if i := firstNonZero(b[2+n:]); i >= 0 { + return invalidV3("layout identity byte %d after the claim id", 90+n+i) + } + d.LayoutSet, d.LayoutFresh, d.LayoutClaimID = true, flags&layoutFlagFresh != 0, string(b[2:2+n]) + return nil +} + func firstNonZero(b []byte) int { for i, c := range b { if c != 0 { diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index afccc9023f..ca937ba73f 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -470,6 +470,9 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { } func (s *WALStore) WriteContext(ctx context.Context, lba uint32, data []byte) (uint64, error) { + if v := s.v3; v != nil && v.layoutFresh.Load() { + return 0, ErrLayoutFresh + } deadline := s.writeAdmissionDeadline(ctx) if err := s.acquireWriteLock(ctx, deadline, s.captureMu.TryRLock, s.captureMu.RLock); err != nil { return 0, err @@ -566,6 +569,9 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error } func (s *WALStore) WriteBatchContext(ctx context.Context, startLBA uint32, blocks [][]byte) ([]uint64, error) { + if v := s.v3; v != nil && v.layoutFresh.Load() { + return nil, ErrLayoutFresh + } deadline := s.writeAdmissionDeadline(ctx) if err := s.acquireWriteLock(ctx, deadline, s.captureMu.TryRLock, s.captureMu.RLock); err != nil { return nil, err @@ -882,6 +888,16 @@ func (s *WALStore) NumBlocks() uint32 { // BlockSize returns the IO unit size in bytes. func (s *WALStore) BlockSize() int { return int(s.sb.BlockSize) } +// ChunkBlocks is the immutable chunk-map shape stored with this local root. +func (s *WALStore) ChunkBlocks() uint64 { + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + if s.v3 == nil || s.v3.ownedMap == nil { + return 0 + } + return s.v3.ownedMap.chunkBlocks +} + // SetRecoveryRetentionLSNs configures the WAL retention window past // checkpointLSN. After this is set, the recovery scan accepts // fromLSN > checkpointLSN - retentionLSNs. Zero (the default) diff --git a/seaweed-block/core/storage/walstore_readonly_v3.go b/seaweed-block/core/storage/walstore_readonly_v3.go index ef5f4fe268..13b1bcd512 100644 --- a/seaweed-block/core/storage/walstore_readonly_v3.go +++ b/seaweed-block/core/storage/walstore_readonly_v3.go @@ -152,11 +152,6 @@ func validateReadOnlyMapV3(path string, d descriptorV3, fallback *descriptorV3) } func (v *walStoreReaderV3) loadPresence(path string) error { - if _, err := os.Stat(path + ".chunkfresh"); err == nil { - return ErrReadOnlyNotResident - } else if !errors.Is(err, os.ErrNotExist) { - return err - } data, err := os.ReadFile(path + ".chunkpresence") if errors.Is(err, os.ErrNotExist) { return nil diff --git a/seaweed-block/core/storage/walstore_readonly_v3_test.go b/seaweed-block/core/storage/walstore_readonly_v3_test.go index d56b391ff8..6945e0da14 100644 --- a/seaweed-block/core/storage/walstore_readonly_v3_test.go +++ b/seaweed-block/core/storage/walstore_readonly_v3_test.go @@ -78,7 +78,7 @@ func crashReadOnlyStoreV3(t *testing.T, s *WALStore) { s.mu.Unlock() } func TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies(t *testing.T) { - for _, fault := range []string{"installing", "acknowledged_wal", "missing_map", "fallback_page", "presence", "fresh"} { + for _, fault := range []string{"installing", "acknowledged_wal", "missing_map", "fallback_page", "presence"} { t.Run(fault, func(t *testing.T) { s, path := newMappedCheckpointStoreV3(t) if fault == "fallback_page" { @@ -135,10 +135,6 @@ func TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies(t *testing.T) if e := os.WriteFile(path+".chunkpresence", []byte("absent nope\n"), 0600); e != nil { t.Fatal(e) } - case "fresh": - if e := os.WriteFile(path+".chunkfresh", []byte("fresh\n"), 0600); e != nil { - t.Fatal(e) - } } before, e := os.ReadFile(path) if e != nil { diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 6599c40467..d542185f9d 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -11,6 +11,7 @@ import ( "sync" "sync/atomic" "time" + "unicode/utf8" ) // Impl-3 internals of the real WALStore (format bump v3, DESIGN r15 @@ -25,7 +26,10 @@ import ( // migration tool or restore into a newly created volume. BASE mutations use // install handles; raw extent writes and frontier jumps remain refused. type walStoreV3State struct { - pub *descriptorPublisherV3 + // layoutFresh mirrors the descriptor's layout identity: set while the + // local root is fresh, when no guest write may be acknowledged. + layoutFresh atomic.Bool + pub *descriptorPublisherV3 w *walWriterV3 ownedMap *chunkLSNMapV3 mapEntries []chunkLSNEntryV3 // guarded by WALStore.mu; UNKNOWN is never cleared here @@ -409,6 +413,7 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO } s, err := openInitializedV3(path, f, &sb, metadata, func(s *WALStore) error { v := &walStoreV3State{} + v.layoutFresh.Store(d.LayoutSet && d.LayoutFresh) v.pub = newDescriptorPublisherV3(d, id, other, descriptorIOV3{ writeSlot: func(off int64, buf []byte) error { if h := s.v3.testBeforeSlotWrite; h != nil { @@ -906,6 +911,55 @@ func (s *WALStore) refreshW() error { return err } +// ErrLayoutFresh: a guest write to a local root still marked fresh (no +// acknowledged write and no durable base yet). The start clears fresh +// before it serves: after the base on a restore, right after the claim +// when there is nothing to restore. +var ErrLayoutFresh = errors.New("storage: the local root is still fresh; a guest write is refused until it is not") + +// SetLayoutIdentity records this local root's layout identity: the claim +// id its marker carries and whether it is still fresh. It is one atomic +// descriptor publication, durable when it returns; a start calls it before +// any claim, and again with fresh = false once the root may hold an +// acknowledged write. The claim id never changes once set, and fresh +// never comes back. +func (s *WALStore) SetLayoutIdentity(claimID string, fresh bool) error { + v := s.v3 + if v == nil { + return errV3NotYet + } + if claimID == "" || len(claimID) > MaxLayoutClaimIDBytes || !utf8.ValidString(claimID) { + return fmt.Errorf("storage: layout claim id %q: 1-%d bytes of UTF-8", claimID, MaxLayoutClaimIDBytes) + } + v.syncMu.Lock() + defer v.syncMu.Unlock() + _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { + if n.LayoutSet && n.LayoutClaimID != claimID { + return fmt.Errorf("storage: the local root carries claim id %q; it never changes (to %q)", n.LayoutClaimID, claimID) + } + if n.LayoutSet && !n.LayoutFresh && fresh { + return errors.New("storage: the local root is no longer fresh; it never becomes fresh again") + } + n.LayoutSet, n.LayoutFresh, n.LayoutClaimID = true, fresh, claimID + return nil + }) + if err == nil { + v.layoutFresh.Store(fresh) + } + return err +} + +// LayoutIdentity returns this local root's layout identity (ok false when +// none was ever recorded). +func (s *WALStore) LayoutIdentity() (claimID string, fresh bool, ok bool) { + v := s.v3 + if v == nil { + return "", false, false + } + d := v.pub.current() + return d.LayoutClaimID, d.LayoutFresh, d.LayoutSet +} + // SetWMode changes the W mode (DESIGN 6.4). It runs a Sync first, so every // write admitted before it is acknowledged under the old mode, then // publishes the new mode with W = the actual acknowledged W while holding diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d6b38299c2..5850a7c6ba 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -111,6 +111,25 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto - Example: a volume holds 100 non-zero chunks when snapshot `init` is taken; then 20 of them are rewritten and snapshot `snap1` is taken. `snap1` and HEAD each list 100 keys, 80 of them the same as in `init`. The store holds 120 chunk objects, not 200. Deleting `init` frees exactly its 20 old keys, and only once GC finds them unreferenced (§6); the 80 shared objects are neither moved nor copied. - The cost of complete maps falls on the cut: a scattered write pattern dirties many 4 MiB chunks and many segments (§14, cut cost). +### Content-named catalog callers during the cutover + +The host control binds a `BCatalog` to the master's `(name, layout_id)` as a `VolumeRef`. A request for a different name is refused; a missing HEAD or failed lookup is an error, never an empty catalog or an invitation to read an older incarnation. + +```mermaid +flowchart LR + Master[Durable master name and layout id] --> Ref[VolumeRef] + Ref --> Attach[Attach: BCatalog.CreateVolume] + Ref --> Evidence[Master: one HEAD metadata response] + Ref --> List[List: read HEAD snapshots] + Ref --> Delete[Delete: conditional snapshot removal] + Ref --> Usage[Usage: HEAD and current root] + Data[Named snapshot data path] --> Commit[Commit snapshot name in HEAD] +``` + +Blockmaster resolves that identity from its published lifecycle record and reads the filer's conventional `?metadata=true` endpoint once. The shared inline-HEAD decoder binds the entry generation and volume attributes to canonical content, including the claim-bearing detached image. The existing clean-move check still requires the expected epoch/holder and the recorded ACK of that generation. Failed or missing metadata refuses the move; there is no old-directory or old-codec fallback. Entry mtime comes from that same response and is diagnostic evidence, never authority. Do not edit, restore or remove HEAD outside the kernel; its single-entry generation is the proof version. + +Listings carry each snapshot's root and dependents. Usage reports snapshot/dependent counts and own/foreign current chunks; it does not synthesize byte accounting. Retention policy is read separately through the catalog. Snapshot entries carry their creation time, class, expiry and bounded labels, sampled once for a named capture and supplied as `CommitRequest.Meta`. A replay keeps the facts already in HEAD. Attach creates the identified VOLUME and unclaimed HEAD idempotently and never creates the legacy name-only directory. Snapshot creation belongs to the data path's HEAD commit, rather than a post-cut catalog write. The runtime cutover remains incomplete while scheduled snapshots, geometry checks and cleaning still reference the old catalog; those references must be removed before that catalog is deleted or this branch ships. + ## 4. Dirty tracking - **Native v3:** the owned per-chunk LSN map and retained WAL/in-memory mutations determine dirt relative to HEAD (`captureCandidates`). UNKNOWN is conservative. Map coverage is durable with the checkpoint before reuse, and a cut certifies only unchanged captured versions after successful publication. @@ -190,7 +209,7 @@ stateDiagram-v2 - **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; until its first HEAD the parent stays rooted by GC's grace after any delete, and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. Model: `docs/spec/RestoreIndependence.tla`. - **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; no snapshot is kept because of a fork or restore; deletion uses the same conditional mark as `DeleteSnapshot`. - **Snapshot delete in any order with forks** (no claims): a fork publishes only before its read time + operation deadline, and GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector` refuses otherwise); an unknown publish keeps the fork intent, which roots the keys until the target is resolved. Model: `ForkDelete` (`G >= D + E + P`). -- **GC** (`gc.go` `Collector.run`, operator-driven through `sw-block ops chunk gc`, preview by default; see also `core/frontend/chunkstore/GC.md`): +- **GC** (legacy store, `gc.go` `Collector.run`; no longer wired: its operator command is removed, and on the content-named layout cleaning is the holder's `BCatalog.Clean` in its maintenance pass; this description goes with the legacy store): - roots: every HEAD, every named snapshot (including one whose delete is still in progress), every snapshot attempt that is not aborted, live intents, and segment objects; an unreadable segment aborts the mark. A deleted snapshot's attempt stays a root for one grace period after its delete time, then stops counting (`Collector.snapshotAttemptHeads` in `gc_copy.go`); - a capture intent expires only if it is older than the TTL, blockmaster has issued a higher epoch, and the remote HEAD has moved to a higher epoch; copy intents are settled only by a permanent tombstone at their publication target; - the whole mark must finish within the grace period minus the operation deadline, and the collector requires grace greater than the deadline; @@ -198,7 +217,7 @@ stateDiagram-v2 - deletion tombstones the binding (`swb.gc.deleted=1`), deletes the needle, then marks it `done`; bindings are never removed, so a key is never rebound. - **Freeing an old snapshot's data** takes three separate steps: 1. **Delete the snapshot** (`sw-block ops chunk snapshot-delete`, `POST /chunk/snapshot/delete`, `Catalog.DeleteSnapshot`), or let retention delete it. This marks the attempt `deleting` with its delete time and removes the name record; no chunk or segment is touched, and a retry is safe (`deleting` and `absent` are both success). - 2. **Run GC with `--apply`.** The deleted attempt stops being a root one grace period after its delete time. A chunk referenced by nothing else then becomes a candidate (if it is itself older than the grace period), and it is deleted only after a second mark at least one grace period later still finds it unreferenced. With the default grace of one hour, a chunk is reclaimed two hours or more after the snapshot delete, and only by GC passes that run after those points. Chunks still referenced by HEAD, another snapshot or a fork are never candidates. + 2. **Clean** (the holder's maintenance pass, `--chunk-maintenance-gc`; formerly GC with `--apply`). The deleted attempt stops being a root one grace period after its delete time. A chunk referenced by nothing else then becomes a candidate (if it is itself older than the grace period), and it is deleted only after a second mark at least one grace period later still finds it unreferenced. With the default grace of one hour, a chunk is reclaimed two hours or more after the snapshot delete, and only by GC passes that run after those points. Chunks still referenced by HEAD, another snapshot or a fork are never candidates. 3. **Volume vacuum in SeaweedFS.** GC deletes the needle; SeaweedFS returns the disk space when it vacuums that volume. Until then the bytes stay on the volume servers. - **Why a reachability mark and not reference counts.** Chunks and segments are shared by snapshots and forks of any number of volumes. A reference count kept in filer entries and changed by several hosts can be lost or applied twice by a crash or an unknown outcome; a lost increment would delete live data. The mark recomputes reachability from the roots on every pass, and the two-mark grace covers writers that are about to publish keys they already uploaded. The cost is delay: space comes back hours after a delete, not at once. - **Volume delete** (`volume_delete.go` `DeleteVolume`): (a) a blockmaster deletion reservation; (b) one HEAD write to `deleting` (refused while HEAD is held); (c) refuse and revert if any snapshot name record exists; (c') commit `deleting �' purging` bound to the same incarnation; (e) HEAD becomes `deleted` with no chunks and `VOLUME` is marked deleted. A deleted id is never attached or created again. @@ -333,6 +352,7 @@ sequenceDiagram M->>M: wait for expiry, restart deadline and skew bound, then mint epoch e+1 end M->>M: the issue write also starts B's lease (horizon issue+1.5·TTL, deadline issue+TTL) + Note over M,B: target B may be source A; the same clean proof or forced barrier applies M->>B: assignment at epoch e+1 and a lease opt B dies before renewing or claiming (HEAD still at epoch e) M->>M: wait for B's lease expiry, deadline and skew bound @@ -366,12 +386,16 @@ stateDiagram-v2 Granted --> Expired: horizon or deadline passes Expired --> Granted: unchanged holder from its registered host, no move/revocation, MAX expiry + skew passed; durable re-grant Expired --> Moved: FORCED move after expiry + skew bound, then HEAD read (an older-epoch HEAD is accepted) + Granted --> DeleteReserved: lifecycle deletion committed, then exclusion published under publisher mu -> leaseMu + Expired --> DeleteReserved: same permanent reservation + DeleteReserved --> DeleteReserved: every grant/renewal/extension refuses; restart rebuilds exclusion before serving + DeleteReserved --> NoLiveLease: durable horizon and granted/restart deadline plus skew have both passed } ``` **Return after lease expiry.** A new process of the unchanged holder and epoch may obtain one durable re-grant after the existing forced-move barrier: both the persisted horizon and granted/restart deadline plus full skew have passed. Re-grant and forced issue serialize under the publisher lock; the winner prevents the competing operation. Revocation, a pending move or uncertain persistence refuses a usable grant. Existing fenced guards remain terminal. The returning process claims a new HEAD generation before I/O, keeps its local acknowledged WAL, and publishes it on the first cut. An empty local root restores only HEAD; a same-epoch sealed HEAD remains detached. -**Same-host planned return.** A sealed volume can be moved cleanly back to its source host after the exact detached-generation ACK was recorded. The move issues a higher epoch even when the host and endpoints are unchanged. The returning process claims the sealed HEAD before serving; a same-epoch reopen remains detached. Forced moves to the source host remain refused. Re-preparing the binding preserves the old retired-epoch tag, so replaying that retirement cannot retire the new binding. +**Same-host planned return.** A sealed volume can be moved cleanly back to its source host after the exact detached-generation ACK was recorded. The move issues a higher epoch even when the host and endpoints are unchanged. The returning process claims the sealed HEAD before serving; a same-epoch reopen remains detached. A forced recovery can also target the same host after the normal expired-lease, restart and skew barriers; it issues a higher epoch and records the abandoned suffix. Bindings identify a volume/server, not its epoch: the old process is fenced by its expired lease and a shared host-volume lock excludes a simultaneous successor. Re-preparing the binding preserves the old retired-epoch tag, so replaying that retirement cannot retire the new binding. **Moving back to a host with a surviving local file.** A fresh volume claims HEAD before serving. A non-fresh attach reads HEAD first; if another holder published it, the attach fails closed with `ErrChunkStaleLocalRoot` (`core/frontend/durable/provider_chunk.go`): the volume is not served, and one log line and the status evidence name the local root to remove or quarantine, after which the next attach starts fresh from HEAD (#167). diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 2b344f72b1..6cab6100a2 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -123,6 +123,7 @@ flowchart LR | any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | | Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` | | Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | +| any authority line | DeleteReserved (permanent) | the existing lifecycle reservation is committed durably; then `mu -> leaseMu` publishes the exclusion. Publication, move issue, first grant, expired re-grant, renewal and background horizon extension check it under their writer lock. Restart reloads every committed exclusion before serving. Deleting HEAD requires the persisted lease horizon and restart deadline plus skew to have ended, including unclaimed grants; the check returns a refusal rather than waiting | `core/authority/workspace_delete_reservation.go` `ReserveWorkspaceDeletion`, `NoLiveWorkspaceLease`; `core/host/master/volume_delete_authority.go`; `host.go` `New` | `INV-SNAPK-DELETE-GATE-001` | **Workspace lease and move, in blockmaster.** @@ -183,13 +184,13 @@ a pre-issued publication. | none | Granted | `RenewWorkspaceLease` from the current primary (server id, replica id) at the current epoch; a missing/foreign server is refused by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`); no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL (an epoch issued by a move already has its lease) | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Granted | Granted | current primary server/replica/epoch required by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing server refused); renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LEASE-HORIZON-MONO-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001` | -| Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), a nonzero HEAD generation, positive granted validity after half the configured/persisted skew on the publisher clock; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` | +| Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), an authoritative detached HEAD matching the ACK epoch/holder/position, positive granted validity after half the configured/persisted skew on the publisher clock; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation; the target may be the same host, with a newly issued epoch and every binding/collision/isolation check retained | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `validateWorkspaceMoveRequest`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-SAME-HOST-CLEAN-MOVE-001` | -| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (the source itself only for a clean, non-force move), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | +| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (including the source host; clean proof or forced-move lease barrier still required), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | | Expired | Granted | Same current primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait (`INV-WS-MASTER-WAIT-001`: 30 s of answered contact past the master's barrier time; no bound while the master gives no reply) or lease fence exits 75 after bounded cleanup; a typed master MOVED or DELETED refusal exits 78 at once (an issued moved source may be refused on subscription before any own assignment); a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` | -| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | +| Expired | Moved (forced) | target may be the source host; explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-SAME-HOST-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | | none, Granted, Revoking or Expired | Deleting | the chunk volume delete is admitted with `WorkspaceHolderState` = never started or deleting (`TERM-LIVE-HOLDER-001`): HEAD, read by blockmaster before its locks, is below the line's epoch, or already past the fence (deleting, purging, deleted: the rerun of a delete that stopped midway); no move pending. From then on renewals, grants, re-grants, revocations and moves of the volume are refused; the delete's HEAD compare-and-swap to deleting is its linearization point: a claim applied before it makes the delete refuse `volume_in_use` and give the reservation back, a claim after it fails. The lifecycle `DeleteVolume` reads no HEAD and keeps the ACK rule | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence`; `core/frontend/chunkstore/volume_delete.go` (HEAD to deleting) | `INV-WS-DELETE-NO-LIVE-HOLDER-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` | | Moved | epoch issued | the moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` | @@ -287,14 +288,14 @@ stateDiagram-v2 | StopPending | Valid | only the latest detach attempt, provably not applied, with serving resumed; an applied, fenced or unknown outcome, or an older attempt's resume, leaves StopPending | `core/frontend/durable/provider_chunk.go` `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `ClearStopPending` | `INV-WS-STOP-PENDING-001` | | Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | | (start) | Attaching, Refused | the volume's host lock `/run/sw-block/locks/.lock` is taken before the store opens; held by another live process, or its directory or file cannot be created or opened, refuses (`storage.ErrWALStoreLocked`, `ErrVolumeLockDirUnavailable`) | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` (from `ensureHandle`) | `INV-WS-ONE-PROCESS-PER-HOST-001` | -| Attaching | Refused | an existing local root whose HEAD another holder has published, or whose durable LSN is below HEAD's `remote_lsn` (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | +| Attaching | Refused | a local root from another claim or behind HEAD's position (`layout.ErrStaleLocalRoot`): final typed refusal with a cure, no serving or retry | `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `provider_chunk.go` `recoverChunk`, `chunkAuthorityWait` | `INV-WS-STALE-LOCAL-ROOT-001` | | (startup) | Refused | `--chunk-filer` is not the only filer of its group: a master lists another filer or several, or no master lists it within 60 s (`ErrNotSingleFiler`) | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `INV-WS-SINGLE-FILER-001` | -| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; fresh roots seed from HEAD before the CAS; existing roots retain local WAL; active incarnations replace the generation (or exclusive-create HEAD); a sealed same-owner incarnation remains detached; I/O opens only after the configured cooling window (zero at one serialization point) and an exact generation/epoch/holder readback | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001`, `INV-WS-REOPEN-FENCE-001` | -| Claiming | Detached (non-serving) | same epoch/holder HEAD is already detached: refuse with ErrChunkLayerDetached before restore preparation or CAS; a higher-epoch takeover still consumes the sealed image | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-SEALED-REOPEN-001` | -| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | -| Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | +| Claiming | Holder | Start validates the local root against the HEAD it conditionally updates; a fresh root seeds before claim, an ordinary reopen keeps its acknowledged local WAL and HEAD identity; guest I/O waits for assignment and claim | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/chunkstore/layout/claim.go` `RunClaim`; `core/frontend/durable/provider_layout.go` `startLayoutRoot` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-SNAPK-HEAD-WRITE-001` | +| Claiming | Detached (non-serving) | a same-epoch detached HEAD refuses Start without changing its sealed image; a higher-epoch claimant retains that image | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/chunkstore/layout/claim.go` `Claim` | `INV-WS-SEALED-REOPEN-001` | +| Claiming | Holder, or not installed | an unknown transition outcome is resolved by its claim/session identity and the current HEAD; no unverified local success | `core/frontend/chunkstore/layout/claim.go` `RunClaim`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead` | `INV-WS-CAS-UNKNOWN-001` | +| Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-SNAPK-HEAD-WRITE-001`, `INV-WS-HEAD-MONOTONE-001` | | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | -| Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and unresolved cut intents remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | +| Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and an unresolved cut session remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead` | `INV-SNAPK-HEAD-WRITE-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | | Holder | (background hydrate) | an independent restore's walker fills every HEAD-named absent chunk through the same shared fill flights (never a second fetch, never over a local write); it yields while any flight has guest waiters, takes one host fill permit per flight (no cut payload, class `BackgroundFill` from the caller) and the permit is released only when that flight's I/O is over, also when the walker returns early on cancel, revocation or close | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked` | `INV-RESTORE-HYDRATE-001`, `INV-CUT-READMISS-001` | @@ -325,7 +326,7 @@ stateDiagram-v2 FinalFreeze --> OpenWindow: admission stays closed through detached settlement Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier; release all held admission OpenWindow --> Copy: release barrier - Copy --> Upload: local entry released, intent durable first + Copy --> Upload: local entry released, session begun first Upload --> Copy: next unsent candidate Upload --> Closed: all workers settled Copy --> Aborted: error, budget revocation, cancellation, observed fence, recovery or close @@ -347,9 +348,9 @@ stateDiagram-v2 |---|---|---|---| | Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-WS-LEASE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | -| Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` | +| Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; the holder session begins before its first upload | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` | | Plain detach | plain=true acquires exclusive idle frontend admission (closed handles allowed), then StopIO and caller-bounded seal. Busy requests mutate nothing; publication and settlement retain authority/HEAD checks. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | -| Plain seal replay | a fresh filer HEAD must be detached with exact epoch/holder and matching detachedBy generation/epoch/holder; idle admission remains closed, authority is checked across the read, and no CAS occurs. Missing process state, including deferred authority startup, is allowed; cache alone never answers success. | `provider_seal_replay.go` `replayPlainSeal`; `chunk_seal_replay.go` `ReadDetachedChunkHead` | `INV-WS-SEAL-REPLAY-001` | +| Plain seal replay | a fresh B HEAD must be detached with the local claim id, exact epoch and holder; idle admission remains closed, authority is checked across the read, and no CAS occurs. A same-epoch detached restart may read the proof without an attached runtime; cache alone never answers success. | `provider_seal_replay.go` `replayPlainSeal`, `readLayoutSeal` | `INV-WS-SEAL-REPLAY-001` | | Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | @@ -358,13 +359,13 @@ stateDiagram-v2 | Pre-copy host drain | (Not reachable in this release; see the note below.) a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001`, `INV-CUT-READ-LOGICAL-001`, `INV-CUT-GUEST-BOUNDED-WAIT-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | -| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after one durable intent per cut or staging round names all candidate keys; an immutable slot retries through transient failures until cancellation or its object deadline | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | -| Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | -| No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | -| Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | -| CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | -| Settled | drop the intents; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | -| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | +| Upload | upload only chunks whose SHA-256 differs from HEAD, under content-addressed pool names, after Begin opens or replays the holder session covering the staged objects; an immutable slot retries through transient failures until cancellation or its object deadline | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/layout_remote.go` `Put` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | +| Manifest | prepare the complete root from changed and reused segments; new objects belong to the open session and are verified before commit | `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead`; `core/frontend/chunkstore/layout/objects.go` `PrepareRoot`; `core/frontend/chunkstore/layout/commit.go` `RunCommit` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | +| No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-SNAPK-HEAD-WRITE-001` | +| Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-SNAPK-HEAD-WRITE-001` | +| CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead` | `INV-SNAPK-HEAD-WRITE-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | +| Settled | a landed commit ends its session; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains its session and reusable uploads until retry, supersession or Close; an unresolved commit keeps its session | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | +| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its open session for settlement | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | Not reachable in this release: the frozen detach and the pre-copy detach. `/chunk/detach` refuses a valid `frozen` request with `frozen_detach_unsupported` before any provider call (`INV-CUT-FROZEN-DETACH-REFUSED-001`), and blockvolume refuses to start with `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`). So the transitions Admit → FrozenForecast, FrozenForecast → Refused, FrozenForecast → Quiesce, Quiesce → Refused (guest-frozen recheck), Quiesce → FinalFreeze and FinalFreeze → OpenWindow, and the rows Pre-copy admission, Pre-copy detach, Guest-frozen detach (apart from its HTTP400 validation) and Pre-copy host drain, are not reached by a released process. Their code is kept and still tested below the HTTP handler; the text above is unchanged. @@ -375,64 +376,17 @@ and reusable only while their chunk version and HEAD generation match. ### M6 Chunk lifecycle -HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). - -**HEAD states** (`active`, `detached`, `deleting`, `purging`, `deleted`, `aborted`). - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork or restore HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork`, `Restore` | `INV-WS-HEAD-CAS-001` | -| `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | -| `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | -| `detached` | `active` | takeover CAS at a higher issued epoch, including a clean move to the same host | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | -| `active`, `detached` | `deleting` | a blockmaster deletion reservation exists and HEAD is not held | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `markHeadDeleting` | `INV-VOLDEL-HELD-HEAD-001`, `INV-VOL-ID-NO-REUSE-001` | -| `deleting` | previous state | a snapshot name record exists: the delete is refused and reverted | `core/frontend/chunkstore/volume_delete.go` `snapshotsBlock`, `revertHeadDeleting` | `INV-VOLDEL-COMMIT-001` | -| `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | -| `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | -| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | -| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | - -**Snapshots and forks.** - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back, unless that attempt is being deleted: then the retry is refused (`snapshot_deleting`), never answered as success, by the replay check and by the create | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName`, `SnapshotReplay` | `INV-SNAP-EXPLICIT-DELETE-001` | -| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | -| published | deleting (retention, class `scheduled`) | the snapshot is not among the newest K of class `scheduled` (K from the newest one's `swb.schedule.keep`, default 7); other classes are planned without it | `core/frontend/chunkstore/retention.go` `planRetention` | `INV-SNAP-SCHEDULED-KEEP-001` | -| published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, check start + deadline before the target `VOLUME`, legacy manifest preparation, copy intent and HEAD writes; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | -| published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | -| restore (Restoring) | Hydrating | M6.Restore.Restoring>Hydrating: the driver starts the walker, paced at a byte rate under the BackgroundFill class | `core/host/volume/chunk_restore.go` `runRestore`; `core/frontend/durable/provider_restore.go` `HydrateVolume`; `core/storage/chunk_hydrate_all.go` `HydrateAllAt` | `INV-RESTORE-HYDRATE-001`, `INV-RESTORE-DRIVER-001` | -| restore (Hydrating) | Owning | M6.Restore.Hydrating>Owning: batch cuts start once chunks are local; the walker and the batches may overlap | `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-DRIVER-001` | -| restore (Owning) | Owning | M6.Restore.Owning>Owning: one bounded batch cut re-uploads at most N local chunks with foreign keys under own keys (one intent, one HEAD CAS); absent chunks wait for the walker | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `INV-RESTORE-OWN-BATCH-001` | -| restore (Owning) | Independent | M6.Restore.Owning>Independent: the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs`; `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-INDEPENDENT-001`, `INV-RESTORE-DRIVER-001` | -| restore (not independent) | name held | refused: `CreateSnapshot` on a restore volume needs the marker, and the supplied image itself must hold no foreign ref; a refused request leaves no name or attempt | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-RESTORE-SNAPSHOT-001` | - -**Intents and key bindings.** - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | -| intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | -| intent live | removed (catalog) | the operation's create is confirmed or can never apply; the delete outlives the caller's cancellation but is bounded by `dropIntentTimeout` | `core/frontend/chunkstore/catalog.go` `dropIntent` | `INV-CAT-INTENT-DROP-BOUNDED-001` | -| intent live | expired | conservative elapsed age exceeds the TTL after pairwise clock skew, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001`, `INV-GC-CLOCK-SKEW-001` | -| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | -| bound | tombstoned, needle deleted | unrooted in two complete marks separated by more than grace plus clock skew, binding age exceeds grace plus skew plus one-second timestamp precision, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001`, `INV-GC-CLOCK-SKEW-001`, `INV-GC-DELETE-EXACT-FID-001`, `INV-GC-GRACE-RESTART-001` | -| tombstoned, DELETE rejected | tombstoned, retry later; continue other bindings | definite HTTP400 is reported per object; no success recorded for the rejected fid; complete mark coverage is saved before returning partial failure; cancellation, unknown/other DELETE errors and metadata errors still stop the pass | `core/frontend/chunkstore/gc.go` `Collector.run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `INV-GC-DELETE-PROGRESS-001` | -| tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | - -GC clock admission (`INV-GC-CLOCK-SKEW-001`): - -```mermaid -flowchart LR - stamp[Persisted timestamp] --> age[Observed age minus pairwise skew and timestamp precision] - age --> young[Not past grace: retain root or candidate] - age --> old[Past grace: existing authority and complete-mark guards] - future[Future or backward mark clock] --> reset[Discard elapsed coverage and start a fresh mark] - old --> reject[HTTP400: retain tombstone and report failure] - reject --> later[Continue later bindings and save complete mark] -``` +B stores snapshots, restore dependencies and the active session in HEAD. The transition tables in M9 below are the canonical guards; the former catalog intent, key-binding and elapsed-TTL transitions have been removed. +| Operation | Guard and outcome | Enforced in | Protects | +|---|---|---|---| +| Begin uploads | Open or replay the holder's session before the first object upload; a failed Begin uploads nothing. | `core/frontend/chunkstore/layout_remote.go` `Begin`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `INV-CUT-INTENT-FIRST-001` | +| Commit snapshot | Verify the complete root and objects written in this session before the conditional HEAD update installs the image and optional snapshot name, then ends the session. | `core/frontend/chunkstore/layout/commit.go` `RunCommit` | `INV-SNAPK-COMMIT-REACH-001` | +| Abort or settle | Keep reusable uploads in their session; retain an unresolved proposal for settlement. Dropped work aborts the open session; a landed commit has already ended it. | `core/storage/chunk_layer.go` `discardStaged`, `captureLocked`, `Close`; `core/frontend/chunkstore/layout_remote.go` `AbortOpenSession` | `INV-CUT-INTENT-CLOSE-001`, `INV-WS-CAS-UNKNOWN-001` | +| Restore | Record the target as a source dependent before creating its root and unclaimed HEAD; owner-qualified references resolve in the source pool. | `core/frontend/chunkstore/catalog_b.go` `BCatalog.Restore`; `core/frontend/chunkstore/layout/create.go` | `INV-SNAPK-COMMIT-REACH-001` | +| Remove snapshot | Remove the name through a conditional HEAD transition; its objects remain governed by the roots and dependents still recorded. | `core/frontend/chunkstore/catalog_b.go` `DeleteSnapshot`; `core/frontend/chunkstore/layout/snapshots.go` | `INV-SNAPK-HEAD-WRITE-001` | +| Clean | Cleaning excludes an open snapshot session. Read and validate HEAD reachability before marking an unreachable pool entry; delete only under the matching mark. | `core/frontend/chunkstore/layout/clean.go`; `core/frontend/chunkstore/layout/remove.go` `RemoveUnreachable` | `INV-SNAPK-CLEAN-EXCL-001`, `INV-SNAPK-REMOVE-MARK-001`, `INV-SNAPK-REMOVE-STOP-001` | +| Delete volume | Reserve deletion, check no live lease inside the deleting transition, release the reservation, remove objects and mark deleted. | `core/frontend/chunkstore/catalog_b.go` `DeleteVolume`; `core/frontend/chunkstore/layout/delete.go` | `INV-WS-DELETE-NO-LIVE-HOLDER-001` | --- @@ -518,11 +472,11 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ### M9 Snapshot kernel: HEAD transactions over the content-named layout -A library, `core/frontend/chunkstore/layout`, with no production caller yet. A volume's HEAD holds its epoch and holder, one activity (`idle`, `snap(s)` or `clean(c)`), the current root and position, and the named snapshots with their dependents. Every transition is one conditional update of HEAD through `runTransition`; no transition creates a HEAD, and an absent HEAD is refused. One exception: the remove-dependent command of the operator writes a deleted HEAD exclusively for a restore target without HEAD (a tombstone), before releasing it from the source. Objects (chunks, segments, roots) are written first under content names; the commit is the only step that makes them reachable. +A library, `core/frontend/chunkstore/layout`, with no production caller yet. A volume's HEAD holds its epoch and holder, one activity (`idle`, `snap(s)` or `clean(c)`), the current root and position, and the named snapshots with their dependents. Every transition is one conditional update of HEAD through `runTransition`; no transition creates a HEAD, and an absent HEAD is refused. Objects (chunks, segments, roots) are written first under content names; the commit is the only step that makes them reachable. ```mermaid stateDiagram-v2 - [*] --> idle: HEAD created outside this package + [*] --> idle: master mints durable layout id; HEAD created outside this package idle --> snap: Begin(s) snap --> idle: Abort(s) snap --> idle: Commit(s, root) @@ -535,20 +489,19 @@ stateDiagram-v2 idle --> clean: BeginClean(c) clean --> idle: EndClean(c) clean --> clean: RemoveUnreachable(shard) - idle --> deleting: MarkDeleting (reserved, no live lease, no dependents) + idle --> deleting: MarkDeleting (no holder, no dependents) deleting --> deleted: MarkDeleted (after release and pool) - [*] --> deleted: tombstone (operator, target without HEAD; exclusive create) - idle --> idle: ReleaseDependent(target) on a source ``` | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| +| no lifecycle record | named volume with immutable layout id | master lifecycle create mints the id once; a lost directory-sync reply settles the same record on retry. Lookup resolves the durable name/id without creating one; workload launch carries both and selects a local directory keyed by id | `core/lifecycle/store.go` `CreateVolume`; master `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient` `ResolveVolume`; launcher `blockVolumeArgs`; blockvolume `parseFlags` | `INV-SNAPK-VOLUME-DIR-001` | | idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` | -| snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains | head.go `Head.Abort` | `INV-SNAPK-ABORT-001` | -| snap(s) | idle, current = root | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001` | +| snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains; before resuming a failed stop, abort its still-open session and re-read HEAD: only matching live/idle resumes, detached goes Down, absent/unknown stays stopped | head.go `Head.Abort`; durable/provider_layout.go `settleLayoutStop` | `INV-SNAPK-ABORT-001` | +| snap(s) | idle, current = root | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present; a new snapshot name records bounded retention facts once, while replay preserves them | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001`, `INV-SNAPK-SNAPSHOT-META-001` | | detached | idle at higher epoch | same-epoch holder operations and Start refused; Claim waits for the old lease | claim.go `Head.Claim`; head.go `holderErr`; start.go `Start` | `INV-SNAPK-DETACHED-001` | | snap(s) | detached, current = root | ordinary Commit preparation checks; caller closed writes and captured its synced L; position = L | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-DETACHED-001` | -| any (Start) | idle at epoch e, claim id k | Start only: at HEAD's epoch it continues on the root carrying HEAD's claim id at or above HEAD's position, else refuses; above, a fresh root or the continuing lineage claims, validated against the HEAD the claim updates | start.go `Start`; claim.go `RunClaim` | `INV-SNAPK-START-ROOT-001`, `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-POSITION-001` | +| any (Start) | idle at epoch e, claim id k | Start only: at HEAD's epoch it continues on the root carrying HEAD's claim id at or above HEAD's position, else refuses; above, a fresh root or the continuing lineage claims, validated against the HEAD the claim updates | start.go `Start`; claim.go `RunClaim` | `INV-SNAPK-START-ROOT-001`, `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-POSITION-001`, `INV-SNAPK-START-ACTIVITY-001` | | idle | clean(c) | holder at HEAD's epoch (epoch, server and claim id); activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` | | clean(c) | idle | holder at HEAD's epoch (epoch, server and claim id); activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` | | clean(c) | clean(c), names removed | holder at HEAD's epoch (epoch, server and claim id) with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; each removal is a mark conditional on the plan's metadata, then a delete conditional on that mark | remove.go `RemoveUnreachable` | `INV-SNAPK-REMOVE-MARK-001` | @@ -682,7 +635,6 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-BATCH-READERS-001` | Each v3 batch block's dirty entry names its data offset in the record, and every reader (store read, flusher, recovery replay, install-path replays, offline reader) uses the block only from a whole valid record whose block has that LBA, LSN and offset. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.readRecordIntoV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`, `WALStore.replayRecordV3`; `core/storage/walstore_readonly_v3.go` `WALStoreReader.readV3` | `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRoundTripAcrossACrash` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | | `INV-WAL-V3-BATCH-ACK-001` | A Sync that covers a v3 batch returns a frontier of at least the batch's last LSN. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`, `WALStore.advanceAfterAppendV3` | `TestWALStoreV3BatchAckCoversItsLastLSN` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | | `INV-WAL-V3-BATCH-MAP-001` | The owned map records every block of a v3 batch at its own LSN. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.recordMapWriteV3` | `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | — | STUB | -| `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED | | `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (expiry and joined physical-fault wire status); `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | | `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | | `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | @@ -733,9 +685,9 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/storage/chunk_restore.go` `ClaimChunkHead`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | +| `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | | `INV-AUTH-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterOperatorMethodsAreStrict` (inverted: a new operator or admin method fails unless strict or named with its reason), `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | -| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, a failed write does not publish it, and an unknown outcome (directory fsync after the rename failed) fail-stops blockmaster: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (`failStopDurabilityUnknown` after a failed directory open or fsync behind the rename, every record; a close error after a good fsync is reported written; Windows keeps its previous behaviour) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename`, `TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | | `INV-AUTH-UNCERTAIN-001` | A failed authority write for a workspace volume, a lease extension included, latches uncertainty until a restart reloads the store: later authority changes and new or extended grants for that volume are refused. See M2 any (workspace) → Uncertain and Uncertain → Uncertain (move answer). | M2 any (workspace) → Uncertain; Uncertain → Uncertain (move answer) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal` (`core/authority/workspace_outcome_uncertain_test.go`), `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (`core/host/master/workspace_uncertain_precedence_test.go`), `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`) | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped`, `UncertainReplyClass` | ACTIVE | @@ -746,7 +698,7 @@ Notes: | `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE | -| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | +| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | | `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE | | `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners bind only loopback: --listen without mutual TLS, and the runtime HTTP listener always; a non-loopback address, and --insecure-external-bind, are refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_PlaintextControlListenersStayOnLoopback`, `TestManifests_NoPlaintextExternalBlockmasterBind` (`cmd/blockmaster/external_bind_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE | @@ -766,7 +718,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-REPL-SESSION-COVERAGE-RETIRE-001` | Superseded logical-session coverage is released only after every already-admitted frame for that session settles; newer sessions do not delay that release. Shared version history and P survive. | M3 replica admission / session retirement | `transport/replica.go` `admitMutation`, `endSessionFrame`; `ReplicaApplyGate.CloseSession` | `TestApplyGate_WireSessionTurnoverRetiresSettledCoverage`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes` | `ReplicaReviewGuards` NoEarlyRetirement/NoSettledHistory | ACTIVE | +| `INV-REPL-SESSION-COVERAGE-RETIRE-001` | Superseded logical-session coverage is released only after every already-admitted frame for that session settles; newer sessions do not delay that release. Shared version history and P survive. | M3 replica admission / session retirement | `core/transport/replica.go` `admitMutation`, `endSessionFrame`; `ReplicaApplyGate.CloseSession` | `TestApplyGate_WireSessionTurnoverRetiresSettledCoverage`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes` | `ReplicaReviewGuards` NoEarlyRetirement/NoSettledHistory | ACTIVE | | `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each runtime observation selects at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryFromPostCloseStalledAck`, `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestMissingProbeAckRestoresNewerDurableProgress`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery; `ReplicaReviewGuards` AckRestoresProgress | ACTIVE | | `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | On a replica, an entry writes data only if its LSN is above both P and its LBA's applied LSN, one value shared by every session and lane; a successful write sets that applied LSN to the entry's LSN. | M3 replica apply / session release | `core/replication/apply_gate.go` `applyRecovery`, `applyLive`; `cmd/blockvolume/replication_ingress.go` `replicationIngress` (one `NewReplicaApplyGate` per replica) | `TestReplicationIngressSharesApplyVersionsAcrossSessions` (`cmd/blockvolume/replication_ingress_apply_test.go`); `TestApplyGate_OverlappingSessionsNeverRegressBytes` (`core/replication/apply_gate_cross_session_test.go`); `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes` (`core/replication/apply_gate_wire_overlap_test.go`); `TestApplyGate_PrunedDurableVersionsRemainStale` (`core/replication/apply_gate_floor_test.go`); `TestApplyGate_LiveAndRecovery_DistinctCoverageSharedVersion` (`core/replication/apply_gate_test.go`) | `ReplicaApplyOrder` NoRegression; `ReplicaPrefixFloor` NoRegression/OnlySuffix | ACTIVE | | `INV-REPL-NO-PER-LBA-STALE-RECOVERY` | A stale recovery-lane entry, LSN at or below max(applied LSN, P), writes no data and still marks its LBA covered for its own session. | M3 replica apply / session release | `core/replication/apply_gate.go` `applyRecovery` | `TestApplyGate_RecoveryLane_StaleSkip_DoesNotRegressData`, `TestApplyGate_RecoveryLane_StaleSkip_AdvancesRecoveryCovered` (`core/replication/apply_gate_test.go`) | — | ACTIVE | @@ -799,34 +751,32 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-WS-HEAD-BELT-001` | After a successful HEAD CAS, takeover or cut, the publisher acts on it only once a re-read of HEAD (the durable frontier) shows that CAS's generation, epoch and holder: a takeover opens I/O only then, a cut settles remoteLSN and the owned map and drops its intents only then. | M4 Claiming → Cooling → Holder; M5 CAS → Settled | `core/storage/chunk_head_belt.go` `casAndConfirmChunkHeadMeasured`, `confirmChunkHead`, `confirmChunkTakeover`; `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach` | `TestHeadBeltTakeoverRefusesLateOldCAS`, `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltConfirmationUsesOnlyRoot` (`core/storage/chunk_head_belt_test.go`) | `WorkspaceTakeover` belt extension pending | ACTIVE | -| `INV-WS-HEAD-BELT-COOLING-001` | The HEAD cooling window W is 0 or at least 2.1 s (the 2 s HEAD operation deadline plus 100 ms settling); with W > 0 a takeover waits W after its CAS, on the local monotonic clock, before its confirming re-read. | M4 Claiming → Cooling → Holder | `core/storage/chunk_head_belt.go` `validateHeadCoolingWindow`, `confirmChunkTakeover`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestHeadBeltCoolingWindowCoversCASAndSettle`, `TestHeadBeltTakeoverWaitsBeforeConfirmation`, `TestHeadBeltSinglePointHasNoCoolingDelay`, `TestHeadBeltRetryOfUnconfirmedClaimStillCools` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE | -| `INV-WS-HEAD-BELT-DEADLINE-001` | Each HEAD CAS and each HEAD confirmation re-read runs under its own deadline of at most 2 s on the local monotonic clock, nested inside the caller's context. | M4 Claiming → Cooling → Holder; M5 CAS | `core/storage/chunk_head_belt.go` `casChunkHead`, `confirmChunkHead`, `readChunkHead` | `TestHeadBeltOperationsHaveOwnDeadline` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE | +| `INV-WS-HEAD-BELT-001` | Retired: the legacy takeover/cut belt required a confirming HEAD re-read before settling; B writes one conditional HEAD transition and handles lost replies through the session/claim rules (`INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-TXN-INTERRUPT-001`, `INV-SNAPK-START-CLAIM-001`). | legacy M4/M5 | — | — | — | ARCHIVED | +| `INV-WS-HEAD-BELT-COOLING-001` | Retired: the legacy HEAD cooling delay is replaced by B's conditional HEAD transition and lease wait (`INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-STALE-HOLDER-001`); B promises no 2.1 s cooling interval. | legacy M4 | — | — | — | ARCHIVED | +| `INV-WS-HEAD-BELT-DEADLINE-001` | Retired: the legacy belt's separate 2 s CAS/re-read deadlines are replaced by B transition and interruption rules (`INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-TXN-INTERRUPT-001`); neither promises that deadline. | legacy M4/M5 | — | — | — | ARCHIVED | | `INV-WS-HEAD-BELT-FENCE-001` | A publisher whose CAS failed or was not confirmed, and whose re-read shows a publication owner different from its own (another epoch, a lower one included, or another holder), fences without retrying the CAS. With an empty last known HEAD its own owner is its configured epoch and holder. | M4 Cooling → HolderFenced; M5 CAS → Fenced | `core/storage/chunk_head_belt.go` `publicationOwnerChanged`, `fencePublication`; `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach` | `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE | -| `INV-WS-HEAD-CAS-001` | Every HEAD publish is conditional on `{gen, epoch}` at one serialization point. A conflicting observed owner fences the publisher. Multiple independent filer serialization points are not made atomic by readback. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | -| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestMemChunkRemote_RefusesLowerRemoteLSN` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | +| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestMemChunkRemote_RefusesLowerRemoteLSN` (`core/storage/chunk_layer_lsn_order_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | | `INV-WS-HEAD-KEY-PROVENANCE-001` | Every key a HEAD names is named by its predecessor HEAD or was uploaded by this owner under an intent that rooted it until the CAS settled; a key that left every root is never named again. | M5 Manifest → CAS | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | — | — | STUB | -| `INV-WS-REOPEN-FENCE-001` | Before I/O, an active reopened holder replaces the observed HEAD generation, including the same epoch/holder and an empty HEAD. A previous incarnation's delayed CAS cannot publish afterward. Local acknowledged WAL is retained. | M4 Claiming -> Holder | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadSameOwnerReopenRejectsKilledProcessCAS`, `TestHeadBeltSameOwnerReopenPreservesAcknowledgedWrites` (`core/storage/chunk_reopen_belt_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `HeadReopenBelt` `OldCASCannotLandAfterReopen` | ACTIVE | -| `INV-WS-SEALED-REOPEN-001` | A same-epoch/holder reopen cannot reactivate a detached HEAD. It refuses before preparation, CAS or serving, retaining the exact generation, owner, frontier, image and detachedBy proof for the planned new holder. | M4 Claiming -> Detached | `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestClaimChunkHeadSameOwnerReopenPreservesSeal` (`core/storage/chunk_reopen_belt_test.go`); `TestRestoreEqualOwnerDetachedHEADStaysSealed` (`core/frontend/durable/provider_seed_order_test.go`) | `SealedReopen` `SealedReopenPreservesProof` | ACTIVE | -| `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after restart, succeeds only from a fresh filer HEAD with exact owner/epoch and detachedBy proof. It returns that original HEAD/frontier without a CAS or new generation. An unreadable or mismatched proof cannot be answered from process memory. | M5 PlainStop -> RemoteProof -> SealedReply | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`; `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`; `cmd/blockvolume/workspace_lease.go` `workspaceDetachedGeneration` | `TestWorkspaceRevocationUsesExactStoredSeal` (`cmd/blockvolume/workspace_proof_test.go`); `TestPlainSealLostAnswerRestartReplaysFilerProof`, `TestPlainSealReplayNeverUsesProcessMemory`, `TestPlainSealReplayDuringDeferredAuthorityStartup` (`core/frontend/durable/provider_plain_seal_replay_test.go`) | `PlainSealReplay` `SuccessNeedsFreshExactProof`, `ValidProofDoesNotNeedProcessMemory` | ACTIVE | -| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | -| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | -| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; an absent record keeps the create path; an unread record exits 75 (filer failed) or 78 (corrupt). | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `TestGeometryFlagsRefusalComparesTheRecord` (`cmd/blockvolume/chunk_remote_test.go`); `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated`, `TestCorruptRecordIsRefusedBeforeTheStoreIsCreated`, `TestWrongGeometryCureAsWritten` (`cmd/blockvolume`, real binaries) | - | ACTIVE | -| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published, or whose local durable LSN is below HEAD's `remote_lsn` (a rolled-back copy), is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`); `TestLocalReopenRejectsForeignClaimImage` (`core/frontend/durable/provider_reopen_belt_test.go`); `TestRolledBackCopyBelowHeadLSNIsRefused` (`core/frontend/durable/rolled_back_copy_test.go`); `TestCutPublishesOnlyLocallyDurableLSN` (`core/frontend/durable/cut_durable_before_cas_test.go`) | — | ACTIVE | +| `INV-WS-REOPEN-FENCE-001` | Retired: the legacy same-holder reopen replaced HEAD generation. B fences by claim id and local-root lineage (`INV-SNAPK-START-ROOT-001`, `INV-SNAPK-START-CLAIM-001`, `INV-SNAPK-STALE-HOLDER-001`); an ordinary same-root reopen may leave HEAD unchanged. | legacy M4 | — | — | — | ARCHIVED | +| `INV-WS-SEALED-REOPEN-001` | A same-epoch Start cannot reactivate a detached HEAD: it refuses before another HEAD update or serving, preserving its current root, position and detached state for a higher-epoch claimant. | M9 detached → higher-epoch idle | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/chunkstore/layout/claim.go` `Claim` | `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition` (`core/frontend/chunkstore/layout/detached_test.go`); `TestRestoreEqualOwnerDetachedHEADStaysSealed` (`core/frontend/durable/provider_seed_order_test.go`) | `INV-SNAPK-DETACHED-001` | ACTIVE | +| `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after a same-epoch detached restart, succeeds only from a fresh B HEAD with exact epoch, holder and local claim id. It returns that HEAD/frontier without a new generation. An unreadable or mismatched proof cannot be answered from process memory. | B detached HEAD read | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`, `readLayoutSeal`; `cmd/blockvolume/workspace_lease.go` `workspaceLayoutDetachedGeneration` | `TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory` (`core/frontend/durable/provider_layout_plain_replay_test.go`); `TestWorkspaceLayoutDetachedProof` (`cmd/blockvolume/workspace_layout_proof_test.go`) | K1: detached proof belongs to the exact claim | ACTIVE | +| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its session stays open; settlement replays the same commit in it. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/frontend/chunkstore/layout_remote.go` | `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestSession_UncertainCommitIsNotAbortedUntilSettled` (`core/storage/chunk_layer_session_test.go`); `TestLayoutRemote_LostReplyOfTheFirstCutIsNotAFence`, `TestLayoutRemote_LostReplyOfALaterCutWithAnInheritedChunkIsNotAFence`, `TestLayoutRemote_LostReplyOfANoOpCutIsNotAFence` (`core/frontend/chunkstore/layout_remote_same_proposal_test.go`) | — | ACTIVE | +| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new B holder claims HEAD at its issued epoch only after the local root is validated against the HEAD it updates; an older epoch or another holder at the same epoch is refused, and guest writes stay closed until assignment and claim. | M9 Start → Claim → Serving | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/durable/provider_layout.go` `startLayoutRoot` | `TestStart_ValidatesAgainstTheHeadItUpdates`, `TestStart_Refusals` (`core/frontend/chunkstore/layout/start_test.go`); `TestStart_TheClaimRechecksTheSeedRule` (`core/frontend/chunkstore/layout/start_seed_test.go`); `TestFreshStoreRefusesWriteBeforeAssignmentThenPublishesAfterClaim` (`core/frontend/durable/provider_restore_schedule_test.go`) | `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-CLAIM-001` | ACTIVE | +| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; an absent record keeps the create path; an unread record exits 75 (filer failed) or 78 (corrupt). | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go`; `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal`; `core/frontend/chunkstore/layout/volume.go`, `start.go`, `create.go`; `core/frontend/chunkstore/catalog_b.go` | `TestGeometryFlagsRefusalComparesTheRecord`, `TestVolumeRequiresGeometry`, `TestVolumeGeometryChecksAndIsImmutable`, `TestStartGeometryMismatchPrecedesClaim`, `TestBCatalogRestoreCopiesVolumeGeometry`, `TestVolumeGeometryLivesOnlyInVolume` | K3: immutable required VOLUME geometry; Start checks the local persisted shape before claim; restores copy source geometry; no resize or compatibility path. | ACTIVE | +| `INV-WS-STALE-LOCAL-ROOT-001` | An old or rolled-back local root is refused by `layout.Start` before serving; synchronous and deferred attach end without retry and report the typed stale-root error and cure. A fresh root at its own epoch likewise ends with `ErrMissingLocalRoot` and its cure. | M4 Claiming → Refused | `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/frontend/durable/provider_chunk.go` `recoverChunk`, `chunkAuthorityWait`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestLayoutProviderRefusesEmptyOwnEpochAndRemountedOldRoot`, `TestFinalLayoutStartRefusalTable` (`core/frontend/durable/provider_layout_test.go`, `provider_layout_start_class_test.go`) | — | ACTIVE | | `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry: same holder and epoch only, no move pending or issued, not revoking, store certain, one durable write, and only once max(horizon, deadline) + skew bound has passed; the new process claims HEAD with a new generation before any I/O, so no older incarnation writes or CASes after. | M2 lease: Expired → Granted | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut`, `TestWorkspaceLeaseRegrantCannotUnsealSameEpoch`, `TestWorkspaceLeaseRegrantEmptyRootClaimsOnlyHEAD` (`core/authority/workspace_regrant_storage_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory` | ACTIVE | +| `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry keeps the same holder and epoch, with no pending move or revocation, a certain store, and one durable write after the horizon/deadline plus skew barrier. Restart begins a new session and voids the old; ordinary reopen keeps HEAD identity (epoch, holder, claim) unchanged. | M2 Expired → Granted; M9 Start | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut` (`core/authority/workspace_regrant_storage_test.go`); `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues` (`core/frontend/chunkstore/layout/start_test.go`); `TestClaim_WritesItsClaimID`, `TestRunClaim_VoidsTheOldSession` (`core/frontend/chunkstore/layout/claim_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory`; `INV-SNAPK-START-ROOT-001` | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | -| `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE | -| `INV-WS-DELETE-NEEDS-ACK-001` | ARCHIVED: replaced by `INV-WS-DELETE-NO-LIVE-HOLDER-001`, which also admits a line whose holder never claimed HEAD at its epoch (HEAD is the proof of "started", not the lease). | — | — | — | — | ARCHIVED | +| `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A same-host move issues a higher epoch: a clean move needs the current holder's sealed HEAD and its recorded epoch/holder/position ACK, and the successor reads that sealed image; a forced move needs the normal lease barrier and a durable lost-range record. | M2 Acked or Expired → Moved; M9 detached → higher-epoch idle | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim` | `TestWorkspaceSameHostForcedMoveRecordsLostRange` (`core/authority/workspace_same_host_forced_test.go`); `TestWorkspaceRPCSameHostForcedRecoveryRecordsLoss` (`core/host/master/workspace_same_host_forced_test.go`); `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestLayoutSameHostCleanSuccessorReadsSealedImage` (`core/frontend/durable/provider_layout_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed`; `INV-SNAPK-DETACHED-001`. The B provider test performs a real plain detach, same-host higher-epoch fresh-root Start, and reads the sealed bytes. | ACTIVE | | `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Revoking/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestDeleteAdmissionVerdicts` (`core/authority/workspace_delete_admission_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r2 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost`, re-run can finish, re-run can settle (exhaustive, 21 of 21 configurations as expected). Not modelled: two delete processes at the same instant; the gap between HEAD deleted and the volume marked deleted | ACTIVE | -| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a revocation ACK matching its epoch, holder and published position; generation is readout only. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation`; `core/host/master/workspace_layout_head.go` `NewLayoutWorkspaceHEADReader` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`); `TestWorkspaceLayoutHEADUsesTheMasterIdentity`, `TestWorkspaceLayoutHEADRefusalsAndStates`, `TestWorkspaceLayoutHEADNeverFollowsRedirects`; `TestWorkspaceLayoutHEADReaderWiring` | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`); `TestProcedureMasterUnreachableFencesBeforeForcedMove` (`cmd/blockvolume/master_loss_integration_test.go`, tags `subprocess chunkstore_integration`) | — | ACTIVE | | `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE | | `INV-WS-FORCED-MOVE-HALF-SKEW-001` | The validity the master gives a host with a lease ends half the clock-skew bound before the reported lease expiry. | M2 Granted → Granted (reply); M4 NoLease, Valid → Valid | `core/authority/workspace_lease_view.go` `WorkspaceLeaseValidity`, `workspaceLeaseValidityAt`; `core/host/master/workspace_service.go` `leaseFact`; `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/volume/workspace_lease.go` `Refresh` | `TestWorkspaceLeaseFactUsesPublisherClockAndSkew` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceAckUsesGrantedHalfSkewBoundary` (`core/authority/workspace_validity_test.go`); `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`) | — | ACTIVE | -| `INV-WS-LOST-RANGE-READOUT-001` | Every issued forced grant the master returns, also on a replay and after a restart, carries the lost range stored in the authority store before the issue, never a recomputed one: see M2 Moved → epoch issued. | M2 lease: Expired → Moved (forced); Moved → epoch issued | `core/authority/workspace_lost_range.go` `recordLostRangeLocked`, `WorkspaceLostRangeReadouts`, `encodeLostRangeEnvelope`; `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/host/master/workspace_head.go` `headFilerMtimeNS`; `core/host/master/workspace_service.go` `grantWithLostRange`, `issuedRecord`; `core/rpc/wsclient/wsclient.go` `Readout` | `TestWorkspaceForcedMoveRecordsTheLostRange`, `TestWorkspaceForcedMoveLostRangeOrdering`, `TestWorkspaceForcedReservationResumeNeedsItsRange` (`core/authority/workspace_lost_range_test.go`); `TestWorkspaceForcedMoveStoresHeadFilerTime` (`core/authority/workspace_lost_range_readout_test.go`); `TestWorkspaceForcedMoveLostRangeOverRPC`, `TestWorkspaceHEADReadsFilerMtime` (`core/host/master/workspace_lost_range_readout_test.go`); `TestReadoutWording` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE | +| `INV-WS-LOST-RANGE-READOUT-001` | Every issued forced grant the master returns, also on a replay and after a restart, carries the lost range stored in the authority store before the issue, never a recomputed one: see M2 Moved → epoch issued. | M2 lease: Expired → Moved (forced); Moved → epoch issued | `core/authority/workspace_lost_range.go` `recordLostRangeLocked`, `WorkspaceLostRangeReadouts`, `encodeLostRangeEnvelope`; `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/host/master/workspace_layout_head.go` `NewLayoutWorkspaceHEADReader`; `core/host/master/workspace_service.go` `grantWithLostRange`, `issuedRecord`; `core/rpc/wsclient/wsclient.go` `Readout` | `TestWorkspaceForcedMoveRecordsTheLostRange`, `TestWorkspaceForcedMoveLostRangeOrdering`, `TestWorkspaceForcedReservationResumeNeedsItsRange` (`core/authority/workspace_lost_range_test.go`); `TestWorkspaceForcedMoveStoresHeadFilerTime` (`core/authority/workspace_lost_range_readout_test.go`); `TestWorkspaceForcedMoveLostRangeOverRPC` (`core/host/master/workspace_lost_range_readout_test.go`); `TestReadoutWording` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE | | `INV-WS-LOST-RANGE-QUERY-001` | `QueryWorkspaceLostRange` returns the stored ranges unchanged: every issued forced move's range in issue order, or the single range of a given request id. | M2 lease: Moved → epoch issued (readout) | `core/authority/workspace_lost_range.go` `WorkspaceLostRangeReadouts`; `core/host/master/workspace_service.go` `QueryWorkspaceLostRange`; `core/rpc/wsclient/wsclient.go` `LostRanges`; `cmd/sw-block/workspace.go` `runWorkspaceLostRange` | `TestWorkspaceLostRangeAccumulatesInIssueOrder` (`core/authority/workspace_lost_range_readout_test.go`); `TestLostRangesBindsTheAnswer` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceLostRangeListsAllInOrder` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-WS-LOST-RANGE-FAILCLOSED-001` | If an issued forced move's range record is missing or fails its range or HEAD-time checksum, the readout fails: the grant carries no range but the reason, the query returns `DataLoss`, the CLI exits 4; none reports the move as no loss. | M2 lease: Moved → epoch issued | `core/authority/workspace_lost_range.go` `LoadWorkspaceLostRanges`, `decodeLostRangeHeadTimes`, `WorkspaceLostRangeReadouts`; `core/host/master/workspace_service.go` `grantWithLostRange`, `QueryWorkspaceLostRange`; `core/rpc/wsclient/wsclient.go` `classify`, `checkRange`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `runWorkspaceLostRange` | `TestWorkspaceLostRangeReadoutFailsClosed`, `TestWorkspaceLostRangeHeadTimeTamperFailsClosed`, `TestWorkspaceLostRangeSkippedWriteIsDetected` (`core/authority/workspace_lost_range_readout_test.go`); `TestForceMoveGrantWithoutRangeIsUnproven` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row7_ReadoutUnproven` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-WS-LOST-RANGE-AUDIT-001` | The master's log records every issued forced move it answers, a replay and an answer that failed after the issue included. | M2 lease: Moved → epoch issued | `core/host/master/workspace_service.go` `MoveWorkspace`, `logForcedGrant` | `TestWorkspaceForcedMoveLostRangeOverRPC` (`core/host/master/workspace_lost_range_readout_test.go`); `TestWorkspaceForceMovePostIssueFailureKeepsTheOutcome` (`cmd/sw-block/workspace_postissue_test.go`) | — | ACTIVE | @@ -857,18 +807,16 @@ Notes: - `INV-WS-SINGLE-FILER-001`: the same census runs in every `sw-block ops chunk` command that writes chunk metadata (snapshot-delete, fork, retain, volume-delete, gc --apply), and in verify, which writes nothing but would report false findings against a split filer view, before it reads or writes; other read-only commands and modes do not run it. - `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. - `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). -- `INV-WS-HEAD-KEY-PROVENANCE-001`: No test asserts it yet in this change. Verify reports a violation it observes during a pass (a key HEAD named, then dropped, then named again is `ROOT_INVALID`): `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`), the named-again cases. +- `INV-WS-HEAD-KEY-PROVENANCE-001`: No test asserts it yet in this change. The legacy verifier that observed a key HEAD named, dropped and named again is removed; on the content-named layout a name is its content, so the case does not arise there. - `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here. -- `INV-WS-LOST-RANGE-READOUT-001`: The HEAD time is the HEAD filer entry's mtime from the filer's `Last-Modified` header on the same read as the HEAD content (1 s resolution). chunkstore writes that mtime from the clock of the host that wrote the entry (the cut); the readout labels it "(publishing host clock as recorded in the filer, 1 s resolution)", and it is not a master time; there is no HEAD format change. The HEAD times sit beside the v1 ranges in the lost-range file with their own checksum, so a binary that predates them still verifies the file; a record without one reads as unknown. The readout reads the ranges loaded at startup: damage after startup shows at the next load. The no-HEAD form ("no remote image exists") is defensive: the master refuses a forced move without a published HEAD. The header is checked against test HTTP servers only; the `chunkstore_integration` test does not assert it. Not in the TLA+ models. +- `INV-WS-LOST-RANGE-READOUT-001`: The HEAD time is the HEAD filer entry's mtime from the same HTTP metadata response as its content and generation (the legacy fixture reader uses `Last-Modified`; both reflect the entry's stored time, at 1 s resolution). chunkstore writes that mtime from the clock of the host that wrote the entry (the cut); the readout labels it "(publishing host clock as recorded in the filer, 1 s resolution)", and it is not a master time; there is no HEAD format change. The HEAD times sit beside the v1 ranges in the lost-range file with their own checksum, so a binary that predates them still verifies the file; a record without one reads as unknown. The readout reads the ranges loaded at startup: damage after startup shows at the next load. The no-HEAD form ("no remote image exists") is defensive: the master refuses a forced move without a published HEAD. The header is checked against test HTTP servers only; the `chunkstore_integration` test does not assert it. Not in the TLA+ models. - `INV-WS-FORCED-CONFIRM-001`: A client-side rule: the master's own guards (explicit force, admission, expected epoch) are `INV-WS-FORCED-MOVE-001`. The holder's logical replica id is read from `QueryWorkspace` (the lease, or the journal on a rerun). The holder check (`INV-WS-FORCED-CONFIRM-HOLDER-001`) sends that one `QueryWorkspace` RPC; only the move is withheld. - `INV-WS-FORCED-MOVE-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-001`: the persisted lease horizon is at least every grant (`INV-WS-LEASE-HORIZON-001`). blockmaster reads HEAD only after the forced admission holds; HEAD must be the expected holder's at the expected epoch, or any HEAD at an older epoch; the lost range starts at that HEAD's remote LSN: see M2 Expired → Moved (forced) (tests `TestWorkspaceUnclaimedGrantForcedReassignOverRPC`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceForcedMoveRecordsTheLostRange`). The publisher checks the admission again when it issues the move. The host counts its validity from the start of its renewal request: see M4 NoLease, Valid → Valid. The authority-owned `WorkspaceLeaseValidity` computes duration on the publisher clock with its configured TTL and the larger configured/persisted skew, including legacy leases with no stored bound. Renewal admission, RPC replies and revocation ACK admission share that calculation; ACK uses the granted deadline clamped to the durable horizon. - `INV-WS-LOST-RANGE-READOUT-001`: a stored range holds the kept HEAD's remote LSN; the forced-move barrier as LostUntil, in master time; the kept HEAD's generation (via the move record); and the HEAD entry's filer mtime read with that HEAD, or "unknown". A missing or damaged record is `INV-WS-LOST-RANGE-FAILCLOSED-001`. A failure after the issue (for example the binding reconciliation) is answered `Internal` naming the move ISSUED, never as a refusal: see M2 Moved → epoch issued. `PreviewWorkspaceMove` runs the forced admission, reads HEAD only once admitted, and writes nothing: see M2 Expired → Moved (forced) (tests `TestWorkspaceForcedMovePreviewWritesNothing`, `TestWorkspaceForceMove_Row2_DryRunPreview`). - `INV-WS-LOST-RANGE-UNCERTAIN-001`, `INV-WS-LOST-RANGE-PRE-ISSUE-001`: on a volume already uncertain, every failed move, an admission refusal or a HEAD-read error included, is answered as an unknown outcome and logged as unknown; only the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see `INV-AUTH-UNCERTAIN-001` and M2 Uncertain → Uncertain (move answer). - Enforced by reading (no test asserts it): the publisher's second admission check when it issues a forced move (`prepareWorkspaceMoveLocked` calls `forcedMoveAdmissionLocked`). - `INV-WS-STOP-PENDING-001`: `WorkspaceTakeover` has no renewal cadence (a host may renew at any step), so StopPending adds no state to the model and no configuration is re-run; `INV-WS-LEASE-001` and `INV-WS-REVOKE-ACK-001` hold in StopPending unchanged. Stop-pending changes only when the guard renews, never what it admits, fences or acknowledges: see M4 Valid → StopPending. It clears only for the latest detach attempt, provably not applied, with serving resumed: see M4 StopPending → Valid. The 250 ms bound is on scheduling only; it does not bound the time from a revocation to its acknowledgement, which also includes a renewal already in flight, the drain and the ACK. The detach hook runs on the plain path only after the idle stop succeeds, so a busy plain detach never sets stop-pending. -- `INV-WS-HEAD-BELT-001`: an unconfirmed publication keeps its intents through Close: see `INV-CUT-INTENT-CLOSE-001`. The takeover half also follows from M4 Claiming → Holder ("an exact generation/epoch/holder readback"); the row is kept for the cut half, which no Part A guard states. -- `INV-WS-HEAD-BELT-COOLING-001`: the supported mode is a single serialization point with W = 0; a W > 0 window is explicit and experimental. ASSUMPTION (class TIME across hosts): W ≥ 2.1 s outlasts an old holder's in-flight CAS only if the filer applies no CAS more than 100 ms after its client's 2 s deadline, which runs on the old holder's clock. That margin is the CAS apply bound, the bound `INV-GC-GRACE-DEADLINE-001` and `INV-SNAP-DELETE-ANY-ORDER-001` name; here it is assumed to be at most 100 ms. The code cannot check it. -- `INV-WS-CAS-UNKNOWN-001`: Close keeps the intents of a proposal still pending: see `INV-CUT-INTENT-CLOSE-001`. +- `INV-WS-HEAD-BELT-001` and `INV-WS-HEAD-BELT-COOLING-001` describe the retired flat-HEAD publication belt. The old 2.1 s cooling assumption is not a B guarantee. `INV-WS-CAS-UNKNOWN-001` remains active for B's pending-session settlement and same-commit replay. ### B.5 Workspace: the cut pipeline @@ -886,8 +834,7 @@ Notes: | `INV-CUT-FROZEN-DETACH-REFUSED-001` | A detach request with `frozen` set is refused with HTTP409 `frozen_detach_unsupported`, retryable=false, before any provider call, admission or cut work. | M5 [*] → Refused (valid frozen request) | `core/host/volume/chunk_control.go` `handleChunkDetach` | `TestChunkDetachFrozenRefusedBeforeProvider` (`core/host/volume/chunk_frozen_refused_test.go`), `TestChunkFrozenDetachWireContractAndPrecedence`, `TestChunkFrozenRequestRefusalCarriesNoBudget` (`core/host/volume/chunk_frozen_budget_test.go`) | — (request refusal) | ACTIVE | | `INV-CUT-PRECOPY-FLAG-REFUSED-001` | blockvolume refuses to start with `--chunk-detach-precopy` set: flag validation fails with "--chunk-detach-precopy is not supported in this release", so no blockvolume process runs the pre-copy detach. | M5 Admit (pre-copy admission never entered) | `cmd/blockvolume/chunk_remote.go` `validateChunkFlags` | `TestChunkDetachPrecopyFlagRefused` (`cmd/blockvolume/chunk_remote_test.go`) | — (startup validation) | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE | -| `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED | +| `INV-CUT-BIRTH-001` | Retired: B does not store per-chunk BirthLSN; `INV-SNAPK-COMMIT-REACH-001` protects the published object graph, and the surviving barrier-image test protects the cut image. | legacy M5 | — | — | — | ARCHIVED | | `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | | `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE | @@ -902,7 +849,6 @@ Notes: | `PROGRESS-DESTRUCTIVE` | Supported guest zero-data writes use ordinary COW and do not abort every update. Unsupported DSM/discard/write-zeroes opcodes reach no storage mutation. Administrative Recover/reset/BASE still invalidate and drain; progress assumes these lifecycle transitions eventually stop. | M1 Write / M5 Save | `chunk_cut_cow.go` `beforeCOWMutation`; frontend dispatch | `TestCutCOWV3_ZeroWritesDoNotAbortUpdates` (`core/storage/chunk_cut_alignment_test.go`); `TestDispatch_UnsupportedOperations` (`core/frontend/ublk/dispatch_test.go`); `TestT2Batch11a_IdentifyController_ONCSAllZero` (`core/frontend/nvme/identify_test.go`) | Guest/lifecycle distinction not modelled; native controls | ACTIVE | | `INV-CUT-PAYLOAD-BOUNDED-001` | One volume's cut upload workers, active COW savers and cached COW saves together hold at most its payload byte budget (default max(64 MiB, six chunks)), whatever the number of candidate chunks. | M5 Stage / Copy / Upload | `core/storage/chunk_cut_payload.go` `cutPayloadWorkers`; `core/storage/chunk_cut_cow.go` `installCOWWindow`, `save` | `TestCutPayloadBudgetBoundsSlots` (`core/storage/chunk_cut_payload_budget_test.go`); `TestCutBudgetRefusesBeforeBarrier` (`core/storage/chunk_cut_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE | | `INV-CUT-PAYLOAD-MIN-001` | A chunk layer is not attached with a negative payload budget or an explicit one below six chunks; zero selects the default. | M5 Stage / Copy / Upload (layer attach) | `core/storage/chunk_layer.go` `attachChunkLayerImpl` | `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`) | — | ACTIVE | -| `INV-CUT-PAYLOAD-SAVER-WAIT-001` | A write waits at most 250 ms, on the local monotonic clock, for a COW saver slot, holding no window lock and making no remote call; on expiry only the cut aborts and the write proceeds. | M5 Copy (COW save) | `core/storage/chunk_cut_cow.go` `acquireSaver`, `beforeCOWMutation` | `TestCutCOWV3_SaverCapacityAbortsWithoutParkingGuest`, `TestCutCOWV3_SaverBurstWaitsAndPublishes` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestCutAbortReasonsAreCountedAndCopied` (`core/storage/chunk_review271_test.go`) | — | ACTIVE | | `INV-CUT-PAYLOAD-BUDGET-COW-001` | With a host Budget, each COW save reserves its chunk bytes on the cut's ticket while holding no window lock; a refused reservation or a revocation aborts only that cut, never the write. | M5 Copy → Aborted (budget revocation) | `core/storage/chunk_cut_cow.go` `save`; `core/storage/chunk_cut_budget.go` `reserve`; `core/storage/chunk_layer.go` `captureLocked` | `TestCutBudgetCOWRefusalAbortsOnlyCut` (`core/storage/chunk_cut_budget_test.go`) | — | ACTIVE | | `INV-CUT-PAYLOAD-BUDGET-RELEASE-001` | A cut's host Budget ticket is released only after all of that cut's COW savers and upload workers have returned, also after a revocation. | M5 Aborted, Closed | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/chunk_cut_cow.go` `join`; `core/storage/chunk_upload.go` `uploadBatch` | `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`) | — | ACTIVE | | `INV-CUT-PAYLOAD-SCRATCH-001` | Reading one block from a WAL batch record allocates block-sized scratch, not the record's size, and still verifies the whole-record CRC. | M5 Copy (cut read) | `core/storage/walstore_v3.go` `readRecordV3`, `readDirtyV3Into` | `TestV3ReadLargeBatchScratchIsBlockBounded` (`core/storage/chunk_review271_test.go`) | — | ACTIVE | @@ -922,9 +868,8 @@ Notes: | `INV-HOST-LAUNCH-CHECK-001` | blockvolume refuses to start with a --host-limit-dir that is missing or not a directory, under a temporary directory, on a network file system, or already in use with different host-limit flags. | M7 host cut admission (process start) | `core/hostlimit/launch.go` `CheckLaunch`; `core/hostlimit/remotefs_linux.go`; `cmd/blockvolume/main.go` | `TestCheckLaunch` (`core/hostlimit/pending_test.go`) | — | ACTIVE | | `INV-LOCAL-HEADROOM-001` | blockvolume refuses to create a volume when the durable root's free space is below the volume size plus its WAL, naming both numbers, before it creates the store, WAL or fresh marker, and warns at start when an existing volume's remaining sparse growth plus the WAL exceed the free space. | M1 open/create (durable provider start) | `core/frontend/durable/headroom.go`; `core/frontend/durable/provider.go` `createFresh`, `openExisting` | `TestCreateRefusesWithoutLocalHeadroom`, `TestOpenWarnsWithoutLocalHeadroom` (`core/frontend/durable/headroom_test.go`) | — | ACTIVE | | `INV-HOST-SLOT-BUSY-CODE-001` | The chunk control API refuses a cut, snapshot or detach that host admission refused because every slot is held (or urgent work is pending) with 503 host_slot_busy, retryable; every other capture refusal keeps capture_refused. | M7 free → admitted (refused, wait) | `core/host/volume/chunk_control.go` `chunkErrorCode` | `TestHostSlotHeldHasItsOwnCode` (`core/host/volume/chunk_host_slot_code_test.go`) | — | ACTIVE | -| `INV-CUT-INTENT-FIRST-001` | Before the first chunk or segment PUT of a cut or staging round, an intent naming every key of that kind the round preallocated is durable in the filer: one for all candidate chunks, however many upload waves the round uses, and one for all new segments. | M5 Intent → Upload → CAS | `core/storage/chunk_cut_payload.go` `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS`, `TestChunkIntent_FailedPutIntentUploadsNothing` (`core/storage/chunk_layer_intent_test.go`); `TestCutPayloadIntentCountIndependentOfCandidates`, `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget` (`core/storage/chunk_review271_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`); `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | -| `INV-CUT-INTENT-CLOSE-001` | Close deletes the intents of reusable uploads and leftover intents, but never an intent of a proposal whose CAS outcome is still unresolved. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `dropIntents` | `TestChunkCloseDropsReusableButKeepsUnknownCASRoots` (`core/storage/chunk_review271_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE | -| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | +| `INV-CUT-INTENT-FIRST-001` | Before the first chunk or segment PUT of a cut or staging round, the holder's session is begun (Begin; a replay while it is open): one Begin per round, however many upload waves it uses; every object the cut writes belongs to that session until its commit. | M5 Begin → Upload → CAS | `core/storage/chunk_cut_payload.go` `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Begin` | `TestSession_BegunBeforeFirstUploadAndClosedByCommit`, `TestSession_FailedBeginUploadsNothing` (`core/storage/chunk_layer_session_test.go`); `TestCutPayloadSessionBeginsIndependentOfCandidates`, `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget` (`core/storage/chunk_review271_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | +| `INV-CUT-INTENT-CLOSE-001` | The session lives as long as the staged uploads: it is aborted only when they are dropped (Close, fenced, a HEAD moved past the commit's base, a settled proposal), never while a proposal's commit is unresolved; a refused cut that keeps its uploads keeps its session for the retry. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `discardStaged`, `requeueCut` | `TestChunkCloseAbortsTheOpenSessionUnlessACommitIsUnresolved` (`core/storage/chunk_review271_test.go`); `TestSession_AdmissionRefusedBeforeCommitKeepsReusableUploads` (`core/storage/chunk_layer_session_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsSessionAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE | | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | | `INV-CUT-HYDRATION-PROGRESS-001` | The status reports per volume the HEAD-named chunks still to hydrate (`AbsentChunks`) and the chunks hydrated so far (`Hydration.Completed`, cumulative); a read of an un-hydrated chunk moves both by one, a repeat read neither. Observation only. | M5 hydration (reader; no transition) | `core/storage/chunk_layer.go` `Stats` (`absentHydratable`); `core/storage/chunk_hydration.go` `hydrationWorker` | `TestHydrationProgressCountersFollowFirstReads` (`core/frontend/durable/hydration_progress_test.go`) | — | ACTIVE | | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch) | — | ACTIVE | @@ -949,8 +894,8 @@ Notes: - `INV-CUT-PAYLOAD-BOUNDED-001`: upload-worker buffers are not counted at run time; the budget reserves four chunk buffers per uploader and two per saver before any cached save is admitted (`cutPayloadWorkers`, `installCOWWindow`). Host-wide policy is a separate limiter module (`INV-HOST-CUT-BUDGET-001`). A host Budget admits a cut for this payload ceiling before staging or the barrier: see M5 Admit (test `TestCutBudgetRefusesBeforeBarrier`). Physical local I/O stays joined (`INV-CUT-COW-DRAIN-001`), and native at-H reads protect unsent candidates with COW (`INV-CUT-COW-OWNER-001`, `INV-CUT-HOOK-BEFORE-APPEND`). - `INV-CUT-PAYLOAD-SPILL-SOURCE-001`: `applyEntryV3` (base install and replicated applies) runs the same COW hook, so it would charge the side file if a cut window were open. That is believed unreachable, since cut admission needs a healthy primary and no base install, but nothing prevents it (enforced by reading: none). - `INV-CUT-ERROR-PRECEDENCE-001`: class ORDER, a wire contract: the order of the cases in `chunkErrorCode` decides which code a caller sees when one error carries several causes. -- `INV-CUT-INTENT-FIRST-001`: unused preallocated keys are harmless: they hold no payload and no binding. An intent is deleted only once the CAS outcome is known: see M6 intent live → removed. -- `INV-CUT-INTENT-CLOSE-001`: the one home of the Close rule; `INV-WS-HEAD-BELT-001` and `INV-WS-CAS-UNKNOWN-001` point here. "Unresolved" includes a CAS that failed or was not confirmed and whose re-read showed a foreign owner (the fence path, `INV-WS-HEAD-BELT-FENCE-001`). Those intents remain for later epoch fencing by GC (`INV-GC-INTENT-EXPIRY-001`). +- `INV-CUT-INTENT-FIRST-001`: Begin opens or replays the holder session before its first upload; a failed Begin uploads nothing. Commit verifies the objects before installing their root (`INV-SNAPK-COMMIT-REACH-001`). +- `INV-CUT-INTENT-CLOSE-001`: the session is retained while reusable uploads or an unresolved commit need it. Settled or abandoned work ends through commit or abort (`INV-SNAPK-ABORT-001`); no elapsed intent TTL or later-epoch GC fence decides this lifetime. - `INV-WS-FREEZE-ACCOUNTING-001` details retained: A frozen detach validates a positive, non-future origin before admission, converts it once to a local monotonic origin, and subtracts elapsed time from the five-second freeze budget at forecast and barrier. Only explicit final override may exceed the forecast budget, and its report records that override and actual elapsed time. New F2 wire fields are durations, not a changed clock-origin request. Existing Unix-nanosecond origin validation/conversion remains; new advice is same-host only. Estimate growth and request delay may cause a bounded refusal, not a promise every advised cycle admits. No new margin. @@ -958,51 +903,21 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-HEAD-FLAT-001` | Every HEAD and snapshot root is a complete image map, directly or through immutable segments. Forks preserve original object owners; reads never fall through to a parent HEAD or snapshot, so successive forks add no backing-chain depth. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`; `core/frontend/chunkstore/manifest.go` `qualifyManifestKey`, `resolveManifest` | `TestForkGrandchildReadsEveryBlockWithoutAncestorImages` (`core/frontend/chunkstore/flat_head_test.go`); `TestFork_ForkOfForkKeepsOriginalOwner` (`core/frontend/chunkstore/catalog_test.go`); `TestManifest_ForkAfterParentSnapshotDelete` (`core/frontend/chunkstore/manifest_test.go`) | —; existing representation, no new transition | ACTIVE | -| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | | `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE | -| `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE | | `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and the scheduled-snapshot worker and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass`, `TestScheduledSnapshotLoop_StopJoinsTheAttempt` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE | -| `INV-GC-REACHABLE-001` | GC tombstones the binding and deletes the needle of a key only when no HEAD, snapshot, snapshot attempt (a deleting one within its grace) or live intent references the key in the current complete mark; those roots are durable catalog entries in the filer. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/gc_copy.go` `snapshotAttemptHeads` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | -| `INV-GC-REACHABLE-OWNER-001` | A ref qualified by an owner volume (`@/`) in any root roots the owner's binding of that key, also after the owner's snapshot and volume are gone. | M6 snapshot: published → fork \| restore | `core/frontend/chunkstore/chunk_remote.go` `keyLocation`; `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`); `TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE | -| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | -| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | -| `INV-GC-DELETE-PROGRESS-001` | A definite HTTP 400 refusal of one needle DELETE does not end the GC pass: later eligible bindings are still reclaimed in that pass and every other candidate keeps its mark coverage. | M6 bound/tombstoned → physical reclamation | `core/frontend/chunkstore/gc.go` `Collector.run`, `reclaimBinding`; `core/frontend/chunkstore/gc_execution.go` `executeGC`; `core/frontend/chunkstore/swfs.go` `DeleteBlob` | `TestGCPermanentDeleteDoesNotStarveLaterBindings` (`core/frontend/chunkstore/gc_delete_progress_test.go`); `TestSWFS_DeleteBlobStatusesAndExactPath` (`core/frontend/chunkstore/gc_test.go`) | `GCDeleteProgress` `NoFalseSuccess`, `FailureVisible`, `LaterProgress` | ACTIVE | -| `INV-GC-CLOCK-SKEW-001` | GC counts a persisted timestamp as older than a threshold (grace or intent TTL) only when its age on the collector's wall clock exceeds the threshold plus the configured pairwise skew bound (default 1 min), plus 1 s for second-resolution binding times. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `Collector.run`, `NewCollector`; `core/frontend/chunkstore/gc_copy.go` `snapshotAttemptHeads` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewPersistedCoverageAcrossHosts` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `EventuallyEligibleAtBound` | ACTIVE | -| `INV-GC-CLOCK-SKEW-FUTURE-001` | A capture intent, copy intent or deleting-snapshot stamp later than the collector's wall clock stays a root and does not stop the pass from expiring, settling or reclaiming other objects. | M6 intent expiry, deleting snapshot roots | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies`, `snapshotAttemptHeads` | `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement`, `TestGCSkewSnapshotDeleteGraceBothDirections` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `FutureProtects`, `IndependentProgress` | ACTIVE | -| `INV-GC-CLOCK-SKEW-MARK-001` | A GC mark supplies elapsed coverage only if it is complete, was written with the same grace, intent TTL, skew bound and operation deadline, and is not later than the collector's wall clock; a backward clock step since the last in-process pass discards coverage. | M6 GC clock admission | `core/frontend/chunkstore/gc_execution.go` `executeGC`, `readMark`; `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewPersistedCoverageAcrossHosts` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | — | ACTIVE | -| `INV-GC-CLOCK-SKEW-MARK-FORMAT-001` | A saved GC mark that fails validation (entry kind, token, format, scope, base, durations, times or candidate entries) makes the GC run fail before it changes anything. | M6 GC clock admission | `core/frontend/chunkstore/gc_execution.go` `readMark`, `executeGC` | `TestGCSkewConfigAndMarkCoverage` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | — | ACTIVE | -| `INV-GC-COPY-SETTLE-001` | GC deletes a snapshot or fork copy intent past its deadline only after an exclusive create at the copy's target settles it: GC's aborted tombstone (attempt entry or HEAD) or the published one already there; an unknown claim or read keeps the intent. | M6 HEAD: — → `aborted`; M6 copy intent: live → removed | `core/frontend/chunkstore/gc_copy.go` `SweepCopies`; `core/frontend/chunkstore/catalog.go` `AbortSnapshot`, `AbortFork` | `TestGC_CopySweepClaimsSnapshotAttemptBeforeRelease`, `TestGC_CopySweepClaimsForkHEADNotExistingVolume`, `TestGC_CopyClaimUnknownRetainsIntent` (`core/frontend/chunkstore/gc_copy_test.go`); `TestFork_TombstoneLosesToPublishedFork` (`core/frontend/chunkstore/catalog_tombstone_test.go`) | — | ACTIVE | -| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | -| `INV-GC-DELETE-EXACT-FID-001` | GC deletes a needle only after tombstoning its key binding, and only by the exact fid recorded in that binding (volume id, needle key and cookie), never a rebuilt one. | M6 key: Bound → Tombstoned, needle deleted | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/swfs.go` `SWFS.DeleteBlob` | `TestSWFS_DeleteBlobStatusesAndExactPath` (`core/frontend/chunkstore/gc_test.go`); `TestGCPermanentDeleteDoesNotStarveLaterBindings` (`core/frontend/chunkstore/gc_delete_progress_test.go`) | — | ACTIVE | -| `INV-GC-GRACE-RESTART-001` | A binding's grace counts from the first complete mark that finds it unrooted and past its age bound, and restarts when a mark finds it rooted or its binding changed; a deleting snapshot attempt roots its keys until its deleting time is past the grace. | M6 key: Bound → Tombstoned; M6 snapshot: Deleting | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/gc_copy.go` `snapshotAttemptHeads`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace` (`core/frontend/chunkstore/gc_copy_test.go`) | `RetentionGCTiming` `NoLiveDelete` | ACTIVE | -| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`, `SnapshotReplay`, `CreateSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`); `TestCatalogReplayOfASnapshotBeingDeletedIsNotSuccess`, `TestCatalogCreateFindingItsAttemptDeletingIsNotSuccess` (`core/frontend/chunkstore/catalog_replay_deleting_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | -| `INV-SNAP-SEAL-POINT-001` | A named snapshot request for a free name runs exactly one cut and stores the HEAD that cut installed as the snapshot; a retry of a recorded request replays that snapshot without cutting; if the cut fails (including a COW window abort) the request fails with that error and records no snapshot. | M5 Admit → Settled, then M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`); `TestChunkControl_SnapshotStoresTheCutHead` (`core/host/volume/chunk_control_adapter_test.go`) | — | ACTIVE | -| `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after its cut's HEAD CAS is confirmed (every referenced chunk uploaded first) and its attempt entry is confirmed by its exclusive create or a read-back; an unknown outcome of either reports failure, and an unknown create keeps the snapshot's intent. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `createResolved` | `TestCatalog_SnapshotUncertainCreateKeepsIntent`, `TestCatalog_SnapshotAppliedResponseLostIsConfirmed` (`core/frontend/chunkstore/catalog_settle_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE | -| `INV-FORK-FROM-SEALED-001` | A fork reads only a published, active snapshot: a name with no published attempt or an aborted one is `snapshot_not_found`, a deleting one is `snapshot_deleting`, and every attempt of a fork, a retry included, reads the parent again. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `resolveSnap` | `TestFork_RefusalsAndDeadline` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_SweepTombstonesADeadSnapshotAttempt` (`core/frontend/chunkstore/catalog_held_create_test.go`); `TestCatalog_ForkAfterTheMarkRefuses` (`core/frontend/chunkstore/retention_review_test.go`); `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ChunkLifecycleFixed` models the snapshot as a name record plus an attempt path; no fork-from-unpublished property | ACTIVE | -| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestFork_ExpiredAttemptWritesNoNewMetadata`, `TestFork_ExpiredLegacyPreparationWritesNoIntent` (`core/frontend/chunkstore/catalog_deadline_test.go`); `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE | -| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retention.go` `planRetention`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retention_test.go`) | — | ACTIVE | -| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | -| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | -| `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | -| `INV-VERIFY-READONLY-001` | Verify writes nothing to the filer or the blob store at any depth: no intent, mark, tombstone, binding or needle. | M6 (reader; no transition) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_ReadOnlyAtEveryDepth` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-RECHECK-001` | No finding is reported for a chunk or segment that no root of the final view names: the HEAD the closing read returned (none if it found none or could not decode it), then the selected snapshots still published. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `round`, `readHead`, `reconcile` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot`, `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete`, `TestVerify_DroppedReferenceProblemIsCounted` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-ONE-READ-001` | Verify checks each distinct chunk and reads each segment key at most once per pass: a settled object is never checked again, however often or under whatever reference a root names it again. | M6 (reader) | `core/frontend/chunkstore/verify.go` `discover`, `settle`, `segment` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DedupSharedChunkReadOnce`, `TestVerify_HeadRefreshRewalksChangedSegments`, `TestVerify_SegmentIsOneObjectPerKey` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-NAMED-HAVE-OUTCOME-001` | In a complete pass every chunk the final view names has a settled outcome: the final view is the closing read itself, one that names no chunk the pass had not seen, with no read after it. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `round` | `TestVerify_PublishDuringClosingReadIsChecked`, `TestVerify_QuietClosingReadIsTheFinalView`, `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-REPORT-ONCE-001` | A complete pass yields at most one finding per chunk or segment key and class, computed only at Reconcile from the outcomes and the final view. | M6 (reader) | `core/frontend/chunkstore/verify.go` `reconcile`, `reconcileSegment` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_TwoWrongReferencesAreOneFinding`, `TestVerify_SameKeyWithAnotherHashIsAFinding`, `TestVerify_SegmentIsOneObjectPerKey` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-ORDER-FREE-001` | Findings and counters are a function of the outcomes, the references seen and the final view, not of the order of reads. | M6 (reader) | `core/frontend/chunkstore/verify.go` `judgeChunk`, `judgeSegment`, `reconcile` | `TestVerify_SegmentFindingsDoNotDependOnOrder`, `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DroppedReferenceProblemIsCounted` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-NO-FALSE-CLEAN-001` | In a complete pass, a chunk the final view names that was bad when checked, or whose key HEAD dropped earlier in the pass and names again, has a finding. | M6 (reader) | `core/frontend/chunkstore/verify.go` `refresh`, `reconcile` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_PublishDuringClosingReadIsChecked` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-CLOSE-BOUND-001` | A pass completes only on a closing read that returns a decodable HEAD naming no chunk it had not seen, within `ClosingRounds` such reads (default 3); otherwise it is incomplete, with its reason, never clean. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `readHead`, `Catalog.Verify` | `TestVerify_ClosingRoundsExhaustedIsIncomplete`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-NOTFOUND-001` | Verify reports `NEEDLE_MISSING` only when the blob store answers that the needle does not exist (for SeaweedFS, every location of a fresh volume lookup answers 404); any other read failure is retried and then reported as `READ_ERROR`, which means not verified. | M6 (reader) | `core/frontend/chunkstore/verify.go` `Catalog.Verify`; `core/frontend/chunkstore/swfs.go` `Get` (`ErrBlobNotFound`) | `TestVerify_PersistentReadErrorIsNotAMissingNeedle`, `TestVerify_TransientReadIsRetried`, `TestSWFS_GetNotFoundIsErrBlobNotFound`, `TestSWFS_GetStaleCachedLocationLooksUpAgain`, `TestVerify_MovedVolumeIsNotAMissingNeedle` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-CANCEL-001` | A failed dispatch of chunk reads (a filer error, or the caller's context ending) cancels the reads in progress before joining them, and Verify returns the originating error. | M6 (reader) | `core/frontend/chunkstore/verify.go` `checkData` | `TestVerify_FailedRefreshCancelsReadInProgress`, `TestVerify_CancelDuringReadJoinsReaders` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE | -| `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`nc_red_SnapDuringRestore`) | ACTIVE | -| `INV-RESTORE-PARENT-HOLD-001` | Retired: retention no longer keeps a snapshot because of a fork or restore (`INV-SNAP-DELETE-ANY-ORDER-001`). | — | — | — | — | ARCHIVED | +| `INV-SNAP-SEAL-POINT-001` | A named snapshot request for a free name runs exactly one cut and stores the HEAD that cut installed as the snapshot; a retry of a recorded request replays that snapshot without cutting; if the cut fails (including a COW window abort) the request fails with that error and records no snapshot. | M5 Admit → Settled, then M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ARCHIVED | +| `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after the commit naming it is confirmed (every object its root reaches written by the session first); an unknown outcome reports failure, settled by reading HEAD. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead`; `core/frontend/chunkstore/layout/commit.go` `RunCommit` | `TestLayoutRemote_CutCommitsThroughTheKernel` (`core/frontend/chunkstore/layout_remote_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE | +| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retain/retain.go` `Plan`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retain/retain_test.go`) | — | ACTIVE | +| `INV-VERIFY-READONLY-001` | Verify writes nothing at any depth: it reaches the store only through Fetch and List, and a full pass with orphans leaves every filer entry and blob unchanged. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyLayoutThroughTheAdapter` (`core/frontend/chunkstore/layout_verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NOTFOUND-001` | Verify reports `MISSING` only when the store answers that the object does not exist; any other read failure ends the pass as incomplete with that error, and is never a finding. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyReadErrorIsReturned`, `TestVerifyFindsMissingAndCorrupt` (`core/frontend/chunkstore/layout/verify_test.go`); `TestOpsChunk_VerifyReadErrorIsIncomplete` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-REACH-001` | A complete pass checks every object the current root and every snapshot root name (roots, segments, chunks): an absent one is `MISSING`; one whose bytes do not hash to its name, at depth full, is `CORRUPT`. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyCleanVolume`, `TestVerifyFindsMissingAndCorrupt`, `TestVerifyWalksSnapshotRoots` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-INCOMPLETE-001` | A volume whose VOLUME or HEAD is absent or does not decode is never reported clean: the pass is incomplete and says which object. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyHeadMissingOrMalformedIsIncomplete` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-ORPHAN-001` | With orphans on, `ORPHAN` is reported only for this volume's own names that no root names and no live restore target names; an unreadable live target suppresses every orphan finding, and verify deletes none. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyOrphans`, `TestVerifyDependentReachIsNotOrphanAndUnreadableDependentSuppresses` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-IDENTITY-001` | HEAD is judged against the VOLUME record's id, and a chunk reference whose owner VOLUME holds another id (a volume created again under the name) is an `IDENTITY` finding, not a clean read. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyVolumeRecordAndHeadID`, `TestVerifyChunkOwnerIdentity` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE | | `INV-RESTORE-HYDRATE-001` | The background hydrate walker fetches a chunk only through that chunk's shared fill flight: at most one fetch per chunk absence, and a fetched block is never installed over a block written locally. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `nextHydrateTarget`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked`; `core/storage/chunk_layer.go` `fillOnce` | `TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage`, `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | | `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE | -| `INV-RESTORE-DRIVER-001` | The restore driver decides only from the target's VOLUME, HEAD and marker (never the source), writes the marker only after a batch leaves no foreign ref, and a rerun resumes from the target's remote state. | M6.Restore (all transitions) | `core/host/volume/chunk_restore.go` `runRestore`, `chunkControl.Restore` | `TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly`, `TestRestoreDriver_ResumesAfterAFailedBatch`, `TestRestoreDriver_RefusesAVolumeNotMadeByRestore` (`core/host/volume/chunk_restore_test.go`) | `RestoreIndependence` `Independent`, `StateRemote` | ACTIVE | -| `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | -| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot`, `sealSnapshot` (explicit and scheduled snapshots) | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — | ACTIVE | +| `INV-RESTORE-READ-REF-001` | A restore target reads each chunk its HEAD names from the pool of the reference's owner, by the reference alone (no other copy, no name-built path); a chunk missing there is an error on a fresh host, never zeros. | M6 restore target read (no transition) | `core/frontend/chunkstore/layout/read.go` `Reader.ReadRef`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Get` | `TestLayoutRemote_RestoreTargetReadsItsSource` (`core/frontend/chunkstore/layout_restore_read_test.go`) | — | ACTIVE | +| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot`, `sealSnapshot` (explicit and scheduled snapshots) | none (legacy share guard removed) | — | ARCHIVED | | `INV-PUBLISH-SETTLED-001` | With `OnPublishSettled` set, each confirmed publication (a new HEAD generation) is delivered once, in publication order, one at a time, outside the capture and state locks. After Close begins, no report is dequeued. | M5 CAS → Settled; M6 HEAD: published | `core/storage/chunk_publish_settled.go` `noteSettled`, `unlockCap`, `runPublishSettled`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestChunkPublishSettled_ReportsEachPublication`, `TestChunkPublishSettled_ReportsALatePublication`, `TestChunkPublishSettled_ClosedAndUnset`, `TestChunkPublishSettled_OverlappingPublishersStayOrdered`, `TestChunkPublishSettled_CloseDropsUnstartedReports`, `TestChunkPublishSettled_HookThatPublishes`, `TestChunkPublishSettled_PeriodicCutReports` (`core/storage/chunk_publish_settled_test.go`); `TestWALStoreChunk_PublishSettledHook` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | Notes: @@ -1029,7 +944,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | | `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | -| `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | +| `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/probe_round.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-PROBE-001` | For a replicated volume (two or more slots), the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (the gate, RF=2 and up) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release | — | ACTIVE | | `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | @@ -1043,7 +958,6 @@ Notes: | `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | | `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | | `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | -| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | | `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | | `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | | `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | @@ -1101,22 +1015,24 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| | `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool//`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; an absent HEAD is refused; the one HEAD the package creates is the exclusive deleted HEAD the operator writes (tombstone) for a restore target without HEAD. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the mark-gated RemoveUnreachable and the ordered DeleteVolume. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 100 snapshots and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort` | `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-COMMIT-REACH-001` | A commit never names an object that is not written: before its one HEAD update it finds present the own chunks new against HEAD's current root (that root rebuilt from the previous manifest, an empty image included), every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `Head.Commit` | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-DETACHED-001` | A detached HEAD remains closed to its same-epoch holder; only a higher-epoch Claim returns it to live. | M9 snap → detached → higher-epoch idle | `core/frontend/chunkstore/layout` `commit.go`, `head.go`, `claim.go`, `start.go` | `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition`, `TestDetachedHEAD_NewGrantStillWaitsForTheOldLease` | Caller write-barrier and synced-position join, master clean-proof reader and composed model review remain cutover gates. | ACTIVE | +| `INV-SNAPK-SNAPSHOT-META-001` | Snapshot retention metadata (creation time, class, expiry and at most four bounded labels) is written by the commit that creates the snapshot name and never changed by a replay. | M9 snap -> idle (named Commit) | `core/frontend/chunkstore/layout/head.go` `SnapshotMeta`, codec; `commit.go` `Head.Commit`, `RunCommit`; host `chunkControl.Snapshot`, `ListSnapshots` | `TestSnapshotMeta_WrittenOnceByTheCommit`, `TestHead_BoundsRefused`, `TestGuard_SafetyIgnoresSnapshotMeta`; `TestChunkControlPassesRetentionFactsToTheNamedCommit`, `TestChunkControlUsesTheBoundLayoutIdentity` | Retention facts affect policy only; the safety guard forbids their use in reachability/removal. Actual provider and scheduled capture integration remain cutover work; no live-path claim. | ACTIVE | +| `INV-SNAPK-DETACHED-001` | A detached HEAD remains closed to its same-epoch holder; only a higher-epoch Claim returns it to live. | M9 snap → detached → higher-epoch idle | `core/frontend/chunkstore/layout` `commit.go`, `head.go`, `claim.go`, `start.go` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestWorkspaceLayoutDetachedProof`, `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition`, `TestDetachedHEAD_NewGrantStillWaitsForTheOldLease` | Caller write-barrier and synced-position join, master clean-proof reader and composed model review remain cutover gates. | ACTIVE | | `INV-SNAPK-TXN-INTERRUPT-001` | A snapshot transaction killed at any of its writes (Begin, each object, Commit), before the write or after it applied with its reply lost, never leaves HEAD reaching a missing object, and the restarted holder (roll back, new session, base recomputed from HEAD) ends at the committed image. | M9 idle → snap → idle | `core/frontend/chunkstore/layout` `head.go`, `commit.go` (the transitions above) | `TestSnapshotSession_InterruptAtEveryStep`, `TestReachableMissing_Controls`, `TestAbort_AfterCommitLeavesTheCommit` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-CLAIM-LEASE-001` | A claim takes HEAD only at a newer epoch and only after every older holder's lease has ended (checked after the read, before the update); it voids any open session or cleaning, so the old holder's commit, abort and begin are refused. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `claim.go` `RunClaim`, `Head.Claim` | `TestClaim_Closure`, `TestRunClaim_WaitsForTheOldLease`, `TestRunClaim_VoidsTheOldSession`, `TestRunClaim_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-CLEAN-EXCL-001` | A cleaning and a snapshot exclude each other through HEAD's one activity field, so no name is removed while a snapshot is open; a claim voids an open cleaning. | M9 idle → clean → idle | `core/frontend/chunkstore/layout` `clean.go` `Head.BeginClean`, `Head.EndClean` | `TestBeginClean_Closure`, `TestEndClean_Closure`, `TestEndClean_IdleMeansNoActivityRemains`, `TestClean_ExcludesSnapshot`, `TestRunBeginClean_InterruptAtEveryStep`, `TestRunEndClean_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-CLEAN-HOLDER-PASS-001` | The holder's periodic cleaning runs as the identity Start established: Begin refuses any other holder, claim or epoch; a pass with no identity, or whose retention failed, removes nothing; every opened cleaning is closed, also on error. | M9 idle → clean → idle (holder pass) | `core/frontend/chunkstore/clean_b.go` `BCatalog.Clean`; `cmd/blockvolume/chunk_maintenance.go` `newChunkMaintenance` | `TestBCatalog_CleanIsHolderOnly`, `TestBCatalog_CleanClosesOnError`, `TestBCatalog_CleanRemovesOnlyUnreachable`, `TestBCatalog_CleanWaitsForAnOpenSnapshot`, `TestBCatalog_CleanAfterOverwriteAndSnapshotDelete` (`core/frontend/chunkstore/clean_b_test.go`); `TestMaintenanceCleansOnlyAsTheHolder`, `TestMaintenanceRetentionFailureNeverStartsCleaning` (`cmd/blockvolume/chunk_maintenance_test.go`) | — | ACTIVE | | `INV-SNAPK-READ-MISSING-001` | A read resolves root, segment, chunk; an index the root does not name is zeros; a root, segment or chunk the root reaches but the store lacks is ErrMissing, never zeros; bytes that do not hash to their name are ErrCorrupt; a foreign chunk is read from its owner's pool. | Content-named layout (read path, no state transition) | `core/frontend/chunkstore/layout` `read.go` `Reader.Open`, `Image.Segment`, `Image.Chunk` | `TestRead_AbsentIndexIsZeros`, `TestRead_ForeignChunkFromSourcePool`, `TestRead_MissingObjectIsAnErrorNeverZeros`, `TestRead_FetchFailureAndCorruption`, `TestRead_SegmentOfAnotherShardRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REMOVE-MARK-001` | A pool name is removed only inside the holder's own cleaning, when no root in HEAD names it: tags read first, HEAD read and validated after, then a mark conditional on the tag and a delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as RemoveUnreachable's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep`, `TestLayoutStoreCreateExistsReclaimsOnlyItsUnusedUpload`, `TestLayoutStoreCreateUnknownOutcomeKeepsItsUpload` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-IDENTITY-001` | A volume is identified by the random id in its VOLUME record, never by its name alone; HEAD carries the volume id and refuses to encode without it. | Content-named layout; M9 every transition | `core/frontend/chunkstore/layout` `volume.go` `Volume`, `VolumeID`; `head.go` `Head.check` | `TestVolumeID_RandomAndParsed`, `TestVolume_GoldenEncodingRoundTrip`, `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-ID-001` | HEAD is decoded only for the volume whose VOLUME carries its volume id; a HEAD of another id, left by an interrupted delete or an old restore under a reused name, is ErrIdentity; a holder without a claim id is malformed. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `DecodeHead`, `Head.check` | `TestDecodeHead_RefusesAnotherVolumesHead`, `TestHead_HolderNeedsAClaimID` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REF-ID-001` | Every chunk reference in a segment carries its owner's volume id; a read checks it against the owner's VOLUME before fetching (another id is ErrIdentity), and the remover tells its own chunks by its VOLUME id. | Content-named layout | `core/frontend/chunkstore/layout` `layout.go` `Segment.Encode`; `read.go` `Image.Chunk`; `remove.go` | `TestSegment_EncodeRefusals`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`, `TestRemoveUnreachable_NeedsItsOwnVolumeID` | — (the snapshot kernel model is not in this repository) | ACTIVE | @@ -1124,16 +1040,22 @@ Notes: | `INV-SNAPK-CLAIM-ID-001` | A holder is its epoch, its server and the claim id its claim wrote into HEAD; every transition refuses the same server at the same epoch with another claim id. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `heldBy`; `claim.go` `Head.Claim` | `TestClaim_WritesItsClaimID`, `TestTransitions_RefuseAStaleHolder`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-ORDER-001` | A volume delete runs in its order, each prefix safe and the whole re-runnable: HEAD deleting, this volume released from every source, its objects deleted, HEAD deleted. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume` | `TestDeleteVolume`, `TestDeleteVolume_InterruptAtEveryStep`, `TestRunMarkDeleting_InterruptAtEveryStep`, `TestRunMarkDeleted_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-OWNED-001` | Every object entry carries the id of its volume; a volume delete removes an object only if it carries that id, so a late delete of a finished run never removes the object of a volume created again under the name. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; `objects.go` `ObjectStore.DeleteOfVolume` | `TestDeleteVolume_ALateDeleteSparesTheNameReused`, `TestDeleteVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-DELETE-GATE-001` | HEAD becomes deleting only after the master reserved the volume (no grant after) and saw no live lease between the HEAD read and the update, with no open activity and no snapshot with dependents; then no holder transition, claim or removal applies. | M9 idle → deleting | `core/frontend/chunkstore/layout` `delete.go` `Head.MarkDeleting`; `head.go` `holderErr` | `TestMarkDeleting_Closure`, `TestMarkDeleted_Closure`, `TestDeleting_RefusesEveryHolderStep`, `TestDeleteVolume`, `TestDeleteVolume_AGrantRaceNeverDeletesALiveVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-DELETE-GUARD-001` | A source scan requires DeleteVolume to run reservation, deleting (whose transition checks live leases), release, object deletes and deleted in that order, and allows it as the only remover besides RemoveUnreachable. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-VOLUME-DIR-001` | A volume lives in the directory -, created exclusively and never reused; a foreign chunk is read from the directory its reference's owner name and id give, after that directory's VOLUME id is checked. | Content-named layout | `core/frontend/chunkstore/layout` `volume.go` `VolumeDir`; `read.go` `Image.Chunk` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-DELETE-GATE-001` | HEAD becomes deleting only with a committed deletion reservation, no live lease (unclaimed grants included), no open activity and no snapshot with dependents; from deleting on, no holder transition, claim or removal applies. | M2 any → DeleteReserved; M9 idle → deleting | `core/frontend/chunkstore/layout` `delete.go` `Head.MarkDeleting`; `head.go` `holderErr`; `core/authority/workspace_delete_reservation.go`; `core/host/master/volume_delete_authority.go` `ReserveVolumeDeletion`, `CheckVolumeNoLiveLease`; `cmd/sw-block/chunk_volume_delete.go` `masterAuthority` | `TestMarkDeleting_Closure`, `TestMarkDeleted_Closure`, `TestDeleting_RefusesEveryHolderStep`, `TestDeleteVolume`; `TestCommittedDeleteStopsGrantsAndWaitsForTheWholeLease`, `TestDeleteReservationClosesPausedGrantWriters`, `TestDeleteReservationMustBeDurableBeforeItCanProveNoLease`, `TestDeleteReservationContextAndPersistenceFailuresStayUnknown`, `TestDeleteOfALiveVolumeIsRefusedBeforePersisting`, `TestDeleteReservationReplayAndRestart`, `TestDeletionReservationGuardSites` (`core/authority`); `TestVolumeDeleteAuthorityReservationSurvivesRestart`, `TestVolumeDeleteAuthorityRPCs` (`core/host/master`; durable RPC/restart probes run on Linux); `TestOpsChunkVolumeDeleteRequiresTheMastersLeaseProof`, `TestOpsChunkVolumeDeleteClosesAPausedFirstGrant`, `TestChunkVolumeDeleteAuthorityRPCSites` (`cmd/sw-block`) | The reservation makes no-live-lease stable; a claim racing the conditional HEAD update still fails its generation check. The snapshot kernel model is external; composed model review pending. | ACTIVE | +| `INV-SNAPK-DELETE-GUARD-001` | A source scan requires DeleteVolume to run no-holder check, deleting, release, object deletes and deleted in that order, and allows it as the only remover besides RemoveUnreachable. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-VOLUME-DIR-001` | A volume's master-minted layout identity is immutable; its directory is -, created exclusively and never reused. A foreign chunk's owning directory is checked against its full VOLUME id. | Content-named layout and lifecycle create/lookup/launch | `core/frontend/chunkstore/layout` `VolumeDir`, `Image.Chunk`; `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient` `ResolveVolume`; `core/launcher/k8s_renderer.go`; `cmd/blockvolume/main.go` `parseFlags`; `core/host/volume/chunk_control.go` `catalogVolume`, `ListSnapshots`, `DeleteSnapshot`, `Usage`; `cmd/blockvolume/chunk_remote.go` `chunkAttachCheck` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`; `TestLifecycleLayoutIdentity`, `TestLayoutIdentityWriterAndReaders`; `TestGetLifecycleVolumeResolvesOnlyTheDurableIdentity`; `TestResolveVolumeNeverInventsAnIdentity`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestBlockvolumeLayoutIdentitySelectsTheLocalRoot`; `TestChunkControlUsesTheBoundLayoutIdentity`, `TestChunkControlCatalogLookupErrorIsNotAbsence`, `TestChunkAttachCheckAppliesVolumeRules`; `TestHeadReaders_Enumeration`, `TestDeleteAndDirectorySites_Enumeration` | Lifecycle ids are durable record fields, not assignment epochs. Old records without the field are refused by the new-layout lookup; host metadata is bound to the full name/id and does not fall back to a previous incarnation. Data-path, scheduled snapshot and cleaning callers plus Linux crash qualification remain cutover work. | ACTIVE | | `INV-SNAPK-TOMBSTONE-001` | For a restore target without HEAD (never created, or a restore died between its two creates) the operator writes a deleted HEAD exclusively in its directory before releasing, so the restore cannot create it later. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent`, `TargetStore.CreateDeletedHead` | `TestOperatorReleaseDependent`, `TestOperatorReleaseDependent_TombstoneLosesToTheRestore`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-KEEP-HEAD-001` | Nothing removes a HEAD, a VOLUME or a volume directory: a volume delete removes only pool, segment and root objects; a source scan lists every delete and every directory-naming site in core/ and cmd/. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; (source scan) | `TestDeleteVolume_RemovesOnlyObjects`, `TestDeleteAndDirectorySites_Enumeration` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-CREATE-001` | A new volume or restore target gets VOLUME then an unclaimed HEAD (epoch 0, no holder, no claim id, idle), each created exclusively; only createVolume and the operator's tombstone create a HEAD; the first Start claims it from a fresh root. | M9 absent → idle | `core/frontend/chunkstore/layout` `create.go` `CreateVolume`, `CreateTarget` | `TestCreateVolume`, `TestCreateVolume_InterruptAtEveryStep`, `TestUnclaimedHead_Shape`, `TestStart_ClaimsAnUnclaimedHeadFromAFreshRoot`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-RESTORE-ORDER-001` | Master checks the source HEAD and named snapshot and refuses RF>1 before persisting. The target binds source layout id, snapshot, request id and VOLUME geometry as not-ready; then AddDependent, copy root/segments, create VOLUME and unclaimed HEAD, and mark ready. A retry keeps the binding. | M9 source HEAD, dependents | `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`; `core/frontend/chunkstore/layout/create.go` `CreateTarget`; `cmd/sw-block/chunk_b.go` `chunkRestore` | `TestRestoreRequestBindsTargetName`, `TestRestoreCreateVolumePersistsRequestBeforeTargetAndHealsRetry`, `TestOpsChunkRestoreUsesOnlyMasterCreate`, `TestCreateTarget`, `TestRunAddDependent_RefusesAForeignSource` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-SNAP-DELETE-001` | A named snapshot leaves HEAD by one conditional update, refused while it has dependents; the automatic delete (retention) also refuses a snapshot pinned at its time. | M9 idle → idle | `core/frontend/chunkstore/layout` `snapshots.go` `Head.DeleteSnapshot`, `Head.RetireSnapshot` | `TestDeleteSnapshot_Closure`, `TestRetireSnapshot_Closure`, `TestRunRetireSnapshot_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-RETAIN-META-001` | Reachability, removal and the volume delete never read a snapshot's retention facts (source guard); the policy entry beside VOLUME changes by one conditional update and is read only by retain. | M9 snap → idle | `core/frontend/chunkstore/layout` `head.go` `SnapshotMeta`; `core/frontend/chunkstore` `retain_b.go` | `TestSnapshotMeta_WrittenOnceByTheCommit`, `TestGuard_SafetyIgnoresSnapshotMeta`, `TestBCatalog_RetainKeepsTheOldBehaviour`, `TestBCatalog_RetentionPolicyIsConditional` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-BOUND-001` | HEAD stays inline: at most 10 snapshots, names at most 64 bytes, 4 labels, 4 dependents per snapshot and 16 per HEAD, refused where they enter with the cure; Encode refuses a HEAD above 64 KiB. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `check`, `Encode`; `snapshots.go` `AddDependent` | `TestHead_SizeAtTheSnapshotCap`, `TestHead_BoundsRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-001` | A target is released from a source's dependents by its volume id, from every snapshot, in one conditional update; a volume created again under its name releases nothing; an absent target writes nothing. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `Head.ReleaseDependent`, `RunReleaseDependent` | `TestReleaseDependent_Closure`, `TestRunReleaseDependent_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-CALLERS-001` | Only the target's own delete (its HEAD already deleting) and the operator's command release a dependent; a source scan restricts the callers and requires the operator's read of the target. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-OPERATOR-001` | The operator's command releases a target that is deleted (HEAD deleting or deleted, or its directory's VOLUME of another id), one whose live roots name no chunk of the source, or one without HEAD, after its tombstone. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RELEASE-REFUSE-001` | The operator's command refuses a live target still naming the source and one whose HEAD appeared before its tombstone, and then writes nothing to the source. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent` | `TestOperatorReleaseDependent` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-START-ROOT-001` | At its own epoch a holder continues only on the local root whose claim id HEAD holds; a fresh root with another id is refused as a missing local root naming the cure, an older one as stale and fenced; neither writes HEAD. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues`, `TestStart_LostClaimReplyContinues`, `TestStart_SameHostForcedSuccessorRefusesTheRemountedOldRoot` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-START-ROOT-001` | At its own epoch a holder continues only on the local root whose claim id HEAD holds; a fresh root with another id is refused as a missing local root naming the cure, an older one as stale and fenced; neither writes HEAD. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start`; `core/frontend/durable/provider_layout.go` `startLayoutRoot`, `initializeLayoutRoot`; `core/frontend/durable/provider_chunk.go` `attachChunk` | `TestLayoutProviderRefusesEmptyOwnEpochAndRemountedOldRoot`, `TestLayoutStartCrashAtEachDurableArrow`, `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues`, `TestStart_LostClaimReplyContinues`, `TestStart_SameHostForcedSuccessorRefusesTheRemountedOldRoot` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-START-ACTIVITY-001` | Before acknowledging guest writes, Start conditionally ends any open activity of a restarted holder's claim; a failed closure refuses attach. | M9 Start -> activity settled -> Serving | `core/frontend/chunkstore/layout/start.go` `Start`, `RunAbort`, `RunEndClean`; `core/frontend/durable/provider_layout.go` `startLayoutRoot` | `TestLayoutRestartClosesActivityBeforeGuestWrites`, `TestKernelTable` | K3; one process per local root: production `HostVolumeLock` holds `/run/sw-block/locks/.lock` before opening the store until Close. Provider close/reopen is tested; process-kill qualification and model review remain release gates. | ACTIVE | | `INV-SNAPK-START-LINEAGE-001` | At an epoch above HEAD's a holder claims only with a fresh root (it restores from HEAD) or the root whose claim id HEAD holds; any other root holds older data and is refused as stale, HEAD unchanged. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_HigherEpochRefusesAnOlderLineage`, `TestStart_FreshRootAtHigherEpochClaims`, `TestStart_StaleRootNamesTheCure`, `TestStart_DeletingVolumeRefused`, `TestStart_ValidatesAgainstTheHeadItUpdates` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-START-POSITION-001` | A root carrying HEAD's claim id but synced below HEAD's published position is an old copy of that lineage and is refused as stale, at its own epoch and above, HEAD unchanged. | M9 start (before any transition) | `core/frontend/chunkstore/layout` `start.go` `Start` | `TestStart_OldCopyOfTheRightRootRefused`, `TestStart_FreshAcrossACrashContinuesTheRestore` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-START-CLAIM-001` | A claim is made only by Start, at an epoch above HEAD's, with the local root's claim id; a source scan refuses any other caller of RunClaim. | M9 any → idle (Claim) | `core/frontend/chunkstore/layout` `start.go` `Start`; (source scan) | `TestStart_FreshRootAtHigherEpochClaims`, `TestStart_Refusals`, `TestStart_InterruptAtTheClaim`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | @@ -1230,7 +1152,7 @@ A row that names a function existing only on an open pull request says so ("on # | `TERM-STOP-LEASE-FENCED-001` Lease fenced / revoked | The lease guard has latched: its deadline passed, a reply was invalid or late, the lease is revoking, or the process is stopping. A fenced guard never reopens. The host drains, and only when the lease was revoked does it acknowledge with the HEAD generation. | `WorkspaceLeaseGuard` `fenced`, `cause`, `revoked` (`core/host/volume/workspace_lease.go`) | Volume: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.fenceLocked`, the one writer of `fenced`; it is read through `permits`. | `Host.FenceWorkspaceLease` and `runWorkspaceLease` (`core/host/volume/workspace_runtime.go`) set `fenced` directly, with no cause, and keep a second latch, `Host.workspaceLeaseFenced`: open. On `main` a guard fence ends the process with status 0: #409 makes it exit 75. | volume host | | `TERM-STOP-HEAD-FENCED-001` HEAD fenced | HEAD shows a higher epoch, or another holder at this epoch. The chunk layer latches fenced and publishes nothing more, and the backend refuses I/O as stale. | HEAD `Epoch`, `Holder`, `Gen`; `chunkLayerImpl` `fenced` (`core/storage`) | Volume: `core/storage/chunk_layer.go` `chunkLayerImpl.supersededBy`. | `ClaimChunkHead` (`core/storage/chunk_restore.go`) repeats the comparison inline: open. Four cut and detach paths in `chunk_layer.go` set `fenced` directly, next to the setter `fencePublication`: open (one setter). A HEAD fence after startup ends the process with 78 (`head_fenced`): on #410. A refused startup claim exits with 78: on #409. | chunk layer | | `TERM-STOP-STALE-ROOT-001` Stale local root | An existing local root whose HEAD another holder has published, or whose local durable LSN is below HEAD's `remote_lsn`, is refused before the claim and never served. A rolled-back copy exits 78; a foreign holder below the assignment's epoch stays up without serving. | HEAD `Holder`, `RemoteLSN`; `ProviderConfig.ChunkHolder`; the store's durable LSN (`WALStore.Boundaries`) | Volume: the `PrepareRestore` check inside `DurableProvider.newChunkLayer` (`core/frontend/durable/provider_chunk.go`). It is not a named function: open. | A copy of the root taken after its last cut has HEAD's LSN and passes: no local check sees it (never restore a root from a copy). | volume host | -| `TERM-STOP-SEALED-001` Sealed | HEAD is detached by this holder at this epoch with a matching `DetachedBy` proof (generation, epoch, holder). The sealing process never reopens it, and only that proof licenses a clean move. | HEAD `State`, `DetachedBy` `Gen`, `Epoch`, `Holder` | Volume: `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead`. Master: `core/host/master/workspace_head.go` `NewWorkspaceHEADReader`, whose reader checks the proof before `workspaceHeadAdmits` sees the HEAD. | Revocation ACK also delegates to `ReadDetachedChunkHead` through `workspaceDetachedGeneration` (`cmd/blockvolume/workspace_lease.go`); `TestWorkspaceRevocationUsesExactStoredSeal` (`cmd/blockvolume/workspace_proof_test.go`) checks assigned epoch/holder, fresh proof and read errors without a write. The sealed-reopen test in `ClaimChunkHead` checks state, epoch and holder without the proof: open. | chunk layer (volume side); authority (master side) | +| `TERM-STOP-SEALED-001` Sealed | B HEAD is detached by this holder at this epoch and claim id. The sealing process never reopens it, and only that proof licenses a clean move. | B HEAD `State`, `Gen`, `Epoch`, `Holder`, `ClaimID` | Volume: `core/frontend/durable/provider_seal_replay.go` `readLayoutSeal`. Master: the B HEAD reader checks the detached claim before admitting a clean move. | Revocation ACK reads the same B HEAD through `workspaceLayoutDetachedGeneration` (`cmd/blockvolume/workspace_lease.go`); `TestWorkspaceLayoutDetachedProof` checks assigned epoch/holder/claim, fresh proof and read errors without a write. | volume host; authority (master side) | | `TERM-STOP-EXIT-001` Exit class of a stopped workspace primary | A workspace primary that stops ends its process with one latched class. 75 means retry (start-time wait exhausted, lease fence, unconfirmed ACK). 78 means superseded (the line names another holder, or the master refused the lease as moved or deleted). 0 is used only after an ACKed revocation or a signal. | `workspaceExit` `code`, `reason`; the `processExit` decision (`cmd/blockvolume/process_exit.go`, on #409) | Volume: `cmd/blockvolume/process_exit.go` `workspaceRetryOutcome`, on #409. `processExit.choose` latches the first outcome. | `chooseChunkStartupExit` (on #409) turns 75 into 78 on a refused HEAD claim (`DurableProvider.ChunkStartupSuperseded`), outside `workspaceRetryOutcome`: open. On #409 alone, "superseded" means another replica; the same replica on another server counts only with #411's `IsSuperseded`: open until both merge. | volume host | | `TERM-ONE-PROCESS-001` One live process per volume per host | At most one blockvolume process serves a volume on one host: each holds `/run/sw-block/locks/.lock` from before its store opens, whatever its `--durable-root`. Across hosts the assignment and the workspace lease keep holders apart. | The host lock file (`durable.HostVolumeLockDir`, `deploy/systemd/sw-block.tmpfiles.conf`); the store file `<--durable-root>/.bin` (`cmd/blockvolume/main.go` `durableCreateGeometry`); their exclusive OS file locks; the HEAD `Holder` | Volume: `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` (on #439; `ProviderConfig.HostVolumeLock`, set by blockvolume; a missing directory refuses the provider), taken in `ensureHandle` before the store opens and released after it closes. `core/storage/volume_lock.go` `LockWALStoreFile`: an exclusive, non-blocking `flock` in `volume_lock_unix.go` and an exclusive, fail-immediately `LockFileEx` in `volume_lock_windows.go`. It is taken by v3 create and open and by the read-only open. | Not a second derivation but the locks' limit: they cover one host. A second process is not refused when it runs on another host with the same server id, in a container without the host's `/run/sw-block/locks` (the Kubernetes renderer does not mount it: open), or on a copied root on another host. Two such processes with one holder string both pass `ClaimChunkHead` and both renew. A failed CAS against the other process's same-epoch, same-holder HEAD is treated as a conflict, not a fence (`publicationOwnerChanged`): open. #416 refuses a server id that heartbeats from another host's address (`refuseServerIDFromOtherHost`), which covers part of this. The master's grants carry no per-process identity: open. | storage engine | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index d314a6b9f0..c3165c57e3 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -157,7 +157,9 @@ named like an admin client's or blockmaster's, but it cannot see a certificate's - **`--host-limit-dir`:** keep it on a local file system with free space. When it cannot be written, background cuts are refused (they fail closed); the seal at stop still runs. - **SeaweedFS space:** every cut and snapshot stores the chunks that changed since the previous one. Space comes - back only by GC and then a SeaweedFS vacuum (below). + back only by GC and then a SeaweedFS vacuum (below). An upload interrupted before its filer entry is + created can leave an unreferenced needle; include this crash-window overhead in space accounting. + Do not run volume.fsck with real deletion on a block cluster. Each volume process reports its own heartbeat slot (server, volume and replica). The master orders each slot against that slot's previous report. In version 1.0, @@ -186,6 +188,13 @@ default) can expire the host's slots; keep host clocks synchronized. ## Snapshots, restore and space +A chunk volume delete refuses to reserve a volume while its lease may still be live. Once the permanent +reservation succeeds at blockmaster, the volume cannot be returned to service, even if a snapshot dependent +refuses the next step. Resolve snapshot dependents and rerun with the same request id; +the command asks blockmaster for a fresh no-live-lease proof before the HEAD compare-and-swap. +A late upload by a dead holder into a deleted volume can remain; rerun volume-delete to sweep it. + + [Standalone deployment: snapshots, restore and space](standalone-deployment.md#snapshots-restore-and-space-walstore-chunk): - scheduled and manual snapshots; - deleting snapshots, and getting space back: @@ -272,8 +281,7 @@ Every command on the pages above, and the test that runs it. | `sw-block ops workspace force-move [--dry-run]`, `lost-range` | `TestProcedureForcedMoveWithTheOldHostReturning`, `TestProcedureRevokeWithoutACKThenForcedMove` | binary | | `sw-block ops volume-unheld --path` | `cmd/sw-block/volume_unheld_test.go` | CLI | | `sw-block ops chunk snapshot`, `snapshots`, `snapshot-delete` | `cmd/sw-block/chunk_test.go` | CLI | -| `sw-block ops chunk gc --chunk-filer --master --apply [--grace]` | `cmd/sw-block/chunk_gc_test.go`; `chunk_gc_integration_test.go` (real SeaweedFS) | CLI | -| `sw-block ops chunk verify --all-snapshots --depth data` | `cmd/sw-block/chunk_verify_test.go` | CLI | +| `sw-block ops chunk verify --depth data [--orphans]` | `cmd/sw-block/chunk_verify_test.go` | CLI | | `sw-block ops chunk restore --source --snapshot --target`, `--volume ... [--status]` | `cmd/sw-block/chunk_restore_test.go` | CLI | | `curl STATUS/status?volume=v1` | the status checks in the binary tests above | binary | | `nvme connect`, `nvme list`, `nvme disconnect` | not run here: the binary tests use an NVMe/TCP host inside the test | not run | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 6224300df9..6237c89a4e 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -503,21 +503,16 @@ sw-block ops chunk snapshot --volume v1 --name before-upgrade --status-addr STAT Space comes back in two steps. Neither is immediate. -1. **GC deletes the chunks**, after the grace. The grace is `sw-block ops chunk gc --grace`, **1 hour by default**. - - A deleted snapshot keeps its chunks rooted for the grace after the delete. - - A chunk is then reclaimed only once two complete GC marks, at least the grace apart, have both seen it unreferenced. - - With the default grace, a deleted snapshot's unreferenced chunks are reclaimed about **2 hours** after the delete. Chunks still referenced by another snapshot, fork or restore remain live. That needs a GC pass at least 1 hour after the delete and another at least 1 hour after that. - - Automatic GC is off by default (`--chunk-maintenance-gc`), so run the passes yourself: +1. **The holder's cleaning deletes the chunks.** + - Cleaning runs only on the volume server that holds the volume, in its maintenance pass (`--chunk-maintenance-interval`, hourly by default), and only with `--chunk-maintenance-gc`. It is off by default. There is no operator command. + - A pass removes the volume's own chunks that no root in HEAD names: not the current image, not a snapshot. A chunk that a restore target still names stays, because the source's snapshot keeps it while the target depends on it. + - A deleted snapshot's unshared chunks are therefore removed by the first pass after the delete. A pass waits while a snapshot is being taken, and a server that no longer holds the volume removes nothing. ```bash sw-block ops chunk snapshot-delete --volume v1 --name sched-20261120T031204Z --chunk-filer FILER - # one hour or more later, and again one hour or more after that: - sw-block ops chunk gc --chunk-filer FILER --master MASTER --apply + # with --chunk-maintenance-gc on the holder, the next maintenance pass removes the chunks only it named; + # each pass logs "maintenance volume=... removed=N" ``` - - - Each pass prints its `Candidates`, `Reclaimed` and `failed_deletes`. - - A chunk shows as a candidate in the first pass that sees it and is reclaimed in a later pass. - - Without `--apply`, a pass is read-only. 2. **SeaweedFS vacuum compacts the volume files.** Reclaimed chunks are deleted needles. - SeaweedFS counts them at once in `DeletedByteCount`. - The disk space returns only when SeaweedFS vacuums those volumes, which runs asynchronously. @@ -561,7 +556,7 @@ therefore see every chunk of every volume and snapshot as unreferenced. without regard to what refers to them. - `filer.sync`, `filer.backup` and `filer.replicate` copy file chunk lists. They do **not** copy a walstore-chunk volume: the copied records would point at needles that do not exist on the target. -- Space is returned only by the two steps above (`sw-block ops chunk gc`, then a SeaweedFS vacuum). `volume.vacuum` +- Space is returned only by the two steps above (the holder's cleaning, then a SeaweedFS vacuum). `volume.vacuum` is safe: it compacts needles that were already deleted. ### Forking a snapshot into a new volume @@ -605,10 +600,9 @@ Prerequisites: `v1` is serving, its only snapshot is `seed`, and the standalone ```bash sw-block ops chunk verify --volume template-holder --all-snapshots --depth data --timeout 2m --chunk-filer FILER sw-block ops chunk verify --volume consumer --all-snapshots --depth data --timeout 2m --chunk-filer FILER - sw-block ops chunk gc --chunk-filer FILER --master MASTER --apply ``` - Read back the known data again and repeat both verify commands after the pass. This immediate pass is not a reclamation measurement: its default grace has not elapsed. Continue namespace-wide GC as described above for unused objects; attached-volume maintenance alone does not collect a deleted source's namespace. + Read back the known data again and repeat both verify commands after the holder's next maintenance pass. Each holder cleans only its own volume; the objects of a deleted volume are removed by the volume delete itself. Keep `template-holder/template-v1` while it is offered for new consumers. Retiring that snapshot later does not delete objects still referenced by existing consumers. Deleting the holder volume itself still requires the ordinary seal/revoke/ACK and snapshot-deletion procedure; do not remove its backing filer directory or object bindings by hand. diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index dced2a578b..b25abcae3d 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -250,7 +250,6 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.ManifestNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.CommitStateNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | -| `Volumes[].Chunk.Stats.LastCut.IntentCleanupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.NonPayloadCopyNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.PayloadNs` | int64 | disjoint streaming/copy/upload wall intervals | | `Volumes[].Chunk.Stats.LastCut.COWWALReadAttempts` | uint64 | Local validated WAL attempts and local copy duration, including savers. | @@ -323,33 +322,14 @@ The engine's replica projection (only with recovery enabled). Go type `engine.Re ### `GET /status/chunk` -Chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint). Go type `chunkstore.VolumeUsage`. +Chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint). Go type `chunkstore.Usage`. | Field | Type | Meaning | |---|---|---| -| `volumeID` | string | the volume | -| `chunkBytes` | uint64 | one full chunk | -| `liveChunks` | int | chunks HEAD references | -| `liveBytes` | uint64 | their bytes (the last chunk clipped) | -| `snapshots[]` | object | one entry per live snapshot | -| `snapshots[].name` | string | the snapshot name | -| `snapshots[].createdNs` | int64 | when it was created (Unix ns) | -| `snapshots[].class` | string | its retention class | -| `snapshots[].pinned` | bool | retention never deletes it | -| `snapshots[].chunks` | int | chunks its manifest references | -| `snapshots[].exclusiveBytes` | uint64 | bytes no other holder references: what deleting it makes eligible for GC | -| `manifestBindings` | int | stored chunk-key bindings some manifest references | -| `manifestBytes` | uint64 | their exact bytes | -| `storedBindings` | int | all chunk-key bindings in the filer, referenced or not | -| `storedBytes` | uint64 | their bytes; unreferenced ones counted at full chunk size | -| `storedUpperBound` | bool | StoredBytes is an upper bound (some bindings are unreferenced) | -| `policy` | object | the snapshot retention policy in force | -| `policy.keepNewest` | int | keep the newest N unpinned snapshots | -| `policy.keepYoungerNs` | int64 | keep every snapshot younger than this (ns) | -| `policy.keepHourly` | int | keep the newest snapshot of each of the last N hours | -| `policy.keepDaily` | int | keep the newest snapshot of each of the last N days | -| `policy.keepWeekly` | int | keep the newest snapshot of each of the last N weeks | -| `policySet` | bool | the volume set its own policy (else the default applies) | +| `snapshots` | int | — | +| `dependents` | int | — | +| `own_chunks` | int | — | +| `foreign_chunks` | int | — | ### `GET /status/nvme` diff --git a/seaweed-block/internal/invcheck/invariants_test.go b/seaweed-block/internal/invcheck/invariants_test.go index 08629162c7..2894b5fe3b 100644 --- a/seaweed-block/internal/invcheck/invariants_test.go +++ b/seaweed-block/internal/invcheck/invariants_test.go @@ -22,6 +22,7 @@ type invRow struct { tests []string status string line int + paths []string // repository .go paths the code and test cells cite } // maxStatement is the longest Statement cell, in characters, a row may have. @@ -30,6 +31,7 @@ const maxStatement = 300 var ( rowID = regexp.MustCompile("^\\| `(INV-[A-Z0-9-]+)` \\|") testName = regexp.MustCompile("`(Test[A-Za-z0-9_]+)`") + goPath = regexp.MustCompile("`([a-z][A-Za-z0-9_.-]*(?:/[A-Za-z0-9_.-]+)+\\.go)`") testFunc = regexp.MustCompile(`(?m)^func (Test[A-Za-z0-9_]+)\(`) countLine = regexp.MustCompile("(\\d+) (?:`INV-` )?rows: (\\d+) ACTIVE, (\\d+) STUB, (\\d+) ARCHIVED") ) @@ -81,6 +83,9 @@ func partB(t *testing.T, root string) ([]invRow, string) { for _, tm := range testName.FindAllStringSubmatch(cells[4], -1) { r.tests = append(r.tests, tm[1]) } + for _, pm := range goPath.FindAllStringSubmatch(cells[3]+" "+cells[4], -1) { + r.paths = append(r.paths, pm[1]) + } rows = append(rows, r) } return rows, doc @@ -175,6 +180,24 @@ func TestInvariantRowsNameExistingTests(t *testing.T) { } } +// An ACTIVE row names the code and tests that hold it now: every repository +// .go path its code and test cells cite must exist (a deleted file is +// rebound to its successor, or the row is retired). +func TestActiveInvariantRowsCiteExistingPaths(t *testing.T) { + root := repoRoot(t) + rows, _ := partB(t, root) + for _, r := range rows { + if r.status != "ACTIVE" { + continue + } + for _, p := range r.paths { + if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(p))); err != nil { + t.Errorf("invariants.md:%d: %s is ACTIVE and cites %s, which does not exist", r.line, r.id, p) + } + } + } +} + func TestInvariantRowCount(t *testing.T) { rows, doc := partB(t, repoRoot(t)) by := map[string]int{} diff --git a/seaweed-block/testops/scenarios/layout-realcluster-integration-gate.yaml b/seaweed-block/testops/scenarios/layout-realcluster-integration-gate.yaml new file mode 100644 index 0000000000..aabb735fc0 --- /dev/null +++ b/seaweed-block/testops/scenarios/layout-realcluster-integration-gate.yaml @@ -0,0 +1,303 @@ +# Runner-native real-cluster gate for the content-named layout. +# +# One scenario for the layout's real-process tests. Each entry is one tagged Go +# test that owns its stock filer, block processes and NVMe frontend; the +# scenario builds an exact product commit, runs the selected entries, and +# passes an entry only on that test's own top-level "--- PASS" line together +# with exit code 0. A test that is skipped, renamed, or not compiled in by its +# tags prints no such line, so it fails the entry. +# +# Parameters never enter shell source: every value reaches the commands as an +# environment variable (the runner single-quotes env.* params), and each is +# validated before use. The verified product commit and weed digest are +# recorded in result.json (emit_provenance) whether or not the entries pass. +# +# Entries (all six by default; select a subset with -env tests="..."): +# move TestIntegrationWorkspaceLayoutMove (clean and forced move) +# lease TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown +# systemd TestSystemdExpiredStartupExits75ThenRegrantServes +# (system systemd; run as a user allowed to systemd-run) +# catalog TestIntegration_CatalogRestoreAndDelete +# cutover-e2e TestCutoverWriteSnapshotKillRestartRestore (write, snapshot, +# kill, restart, restore) +# cutover-create TestCutoverCreateFromSnapshot (the master creates the +# target identity and its restored image in one request) +# fence-heal TestFencingRoundHealContinuesThePrimary (a failed fencing +# round heals by continuing the primary). Not in the default +# set until the promotion fence is on the base. +# fence-rejoin TestFencingRoundSurvivorRejoins (the fence-heal scenario +# carried on: the survivor that could not fence rejoins the +# healed primary). Not in the default set until the promotion +# fence is on the base. +# double-failover TestDoubleFailoverReadsBackEveryAckedWrite (RF3 +# sync_quorum: two failovers, the first primary rejoining in +# between; every acknowledged write reads back on the last +# primary). Not in the default set until the promotion fence +# is on the base. +# +# Expected invocation (on the Linux host): +# swblock run \ +# -env product_repo=/path/to/seaweed-block -env head=<40-hex commit> \ +# -env weed_binary=/path/to/weed -env weed_sha256= \ +# -env go_bin=/path/to/go/bin \ +# -env tests="move lease systemd catalog cutover-e2e cutover-create" \ +# testops/scenarios/layout-realcluster-integration-gate.yaml + +name: layout-realcluster-integration-gate +timeout: 120m +always_timeout: 5m + +env: + product_repo: "/path/to/seaweed-block" + head: "" + weed_binary: "/path/to/weed" + weed_sha256: "" + go_bin: "/usr/local/go/bin" + tests: "move lease systemd catalog cutover-e2e cutover-create" + scratch_root: "/tmp/sw-layout-gate" + +topology: + nodes: + host: + is_local: true + +phases: + - name: prepare + actions: + - action: exec + node: host + timeout: 2m + env.GATE_RUN: "{{ run_id }}" + env.GATE_ROOT: "{{ scratch_root }}" + env.GATE_HEAD: "{{ head }}" + env.GATE_TESTS: "{{ tests }}" + env.GATE_REPO: "{{ product_repo }}" + env.GATE_WEED: "{{ weed_binary }}" + env.GATE_WEED_SHA: "{{ weed_sha256 }}" + env.GATE_GO: "{{ go_bin }}" + save_as: gate_token + cmd: | + set -euf + fail() { echo "$1" >&2; exit 2; } + case "$GATE_HEAD" in *[!0-9a-f]*|'') fail 'head must be a full lowercase hexadecimal commit' ;; esac + [ ${#GATE_HEAD} -eq 40 ] || fail 'head must be 40 characters' + case "$GATE_WEED_SHA" in *[!0-9a-f]*|'') fail 'weed_sha256 must be lowercase hexadecimal' ;; esac + [ ${#GATE_WEED_SHA} -eq 64 ] || fail 'weed_sha256 must be 64 characters' + case "$GATE_RUN" in *[!0-9A-Za-z_-]*|'') fail 'run_id has unexpected characters' ;; esac + case "$GATE_ROOT" in /*) ;; *) fail 'scratch_root must be absolute' ;; esac + case "$GATE_ROOT" in *[!0-9A-Za-z_./-]*|*..*) fail 'scratch_root has unexpected characters' ;; esac + case "$GATE_TESTS" in *[!0-9a-z\ -]*|'') fail 'tests must be entry names separated by spaces' ;; esac + n=0 + for t in $GATE_TESTS; do + case "$t" in move|lease|systemd|catalog|cutover-e2e|cutover-create|fence-heal|fence-rejoin|double-failover) ;; *) fail "unknown entry: $t" ;; esac + n=$((n + 1)) + done + [ "$n" -gt 0 ] || fail 'tests names no entry' + [ -x "$GATE_GO/go" ] || fail 'go_bin/go is not executable' + [ -f "$GATE_WEED" ] || fail 'weed_binary is not a file' + [ "$(sha256sum < "$GATE_WEED" | cut -d' ' -f1)" = "$GATE_WEED_SHA" ] || fail 'weed_binary does not match weed_sha256' + [ "$(git -C "$GATE_REPO" rev-parse --verify "$GATE_HEAD^{commit}")" = "$GATE_HEAD" ] || fail 'head is not that commit in product_repo' + d="$GATE_ROOT/$GATE_RUN" + mkdir -p "$GATE_ROOT" + # Created here, atomically, or refused: cleanup removes only a + # directory whose marker holds this run's token. + mkdir "$d" 2>/dev/null || fail 'run directory already exists' + token=$(od -An -tx1 -N16 /dev/urandom | tr -d ' \n') + printf '%s\n' "$token" > "$d/.layout-gate-owned" + printf '%s\n' "$token" + - action: exec + node: host + timeout: 2m + env.GATE_DIR: "{{ scratch_root }}/{{ run_id }}" + env.GATE_HEAD: "{{ head }}" + env.GATE_TESTS: "{{ tests }}" + env.GATE_REPO: "{{ product_repo }}" + env.GATE_WEED_SHA: "{{ weed_sha256 }}" + env.GATE_GO: "{{ go_bin }}" + cmd: | + set -euf + d="$GATE_DIR" + mkdir "$d/source" "$d/bin" "$d/tmp" "$d/evidence" + git -C "$GATE_REPO" archive "$GATE_HEAD" | tar -xf - -C "$d/source" + printf '%s\n' "$GATE_HEAD" > "$d/evidence/product.sha" + printf '%s weed\n' "$GATE_WEED_SHA" > "$d/evidence/weed.sha256" + "$GATE_GO/go" version > "$d/evidence/go.version" + printf '%s\n' $GATE_TESTS > "$d/evidence/selected.txt" + # Pins, recorded before any entry runs; gate_pass stays 0 unless run_tests passes. + - action: emit_provenance + product: seaweed-block + tested_sha: "{{ head }}" + gate_pass: "0" + gate_status: "pinned" + __weed_sha256: "{{ weed_sha256 }}" + __entries: "{{ tests }}" + + - name: build + actions: + - action: exec + node: host + timeout: 20m + env.GATE_DIR: "{{ scratch_root }}/{{ run_id }}" + env.GATE_GO: "{{ go_bin }}" + env.GATE_TESTS: "{{ tests }}" + cmd: | + set -eu + d="$GATE_DIR" + export PATH="$GATE_GO:$PATH" + cd "$d/source" + for b in blockmaster blockvolume sw-block; do go build -o "$d/bin/$b" "./cmd/$b"; done + # Only the test binaries the selected entries run: a package that + # no selected entry uses cannot fail the build of the others. + bv=0 sd=0 cs=0 + for t in $GATE_TESTS; do + case "$t" in + systemd) sd=1 ;; + catalog) cs=1 ;; + *) bv=1 ;; + esac + done + [ "$bv" = 0 ] || go test -c -tags 'subprocess chunkstore_integration' -o "$d/bin/blockvolume.test" ./cmd/blockvolume + [ "$sd" = 0 ] || go test -c -tags 'subprocess chunkstore_integration systemd_integration' -o "$d/bin/blockvolume-systemd.test" ./cmd/blockvolume + [ "$cs" = 0 ] || go test -c -tags 'chunkstore_integration' -o "$d/bin/chunkstore.test" ./core/frontend/chunkstore + sha256sum "$d/bin/"* > "$d/evidence/binaries.sha256" + + - name: run_tests + actions: + - action: exec + node: host + timeout: 95m + env.GATE_DIR: "{{ scratch_root }}/{{ run_id }}" + env.GATE_GO: "{{ go_bin }}" + env.GATE_WEED: "{{ weed_binary }}" + env.GATE_TESTS: "{{ tests }}" + receipt_path: "{{ bundle_dir }}/run_tests.receipt.json" + cmd: | + set -f + d="$GATE_DIR" + export PATH="$GATE_GO:$PATH" TMPDIR="$d/tmp" CHUNKSTORE_WEED="$GATE_WEED" SWBLOCK_TEST_BINS="$d/bin" + : > "$d/evidence/verdicts.txt" + failed=0 + n=0 + for t in $GATE_TESTS; do + n=$((n + 1)) + extra= + case "$t" in + move) pkg=cmd/blockvolume bin=blockvolume.test name=TestIntegrationWorkspaceLayoutMove to=14m ;; + lease) pkg=cmd/blockvolume bin=blockvolume.test name=TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown to=9m ;; + systemd) pkg=cmd/blockvolume bin=blockvolume-systemd.test name=TestSystemdExpiredStartupExits75ThenRegrantServes to=14m extra=GAP1_SYSTEMD_AUTHORIZED=1 ;; + catalog) pkg=core/frontend/chunkstore bin=chunkstore.test name=TestIntegration_CatalogRestoreAndDelete to=9m ;; + cutover-e2e) pkg=cmd/blockvolume bin=blockvolume.test name=TestCutoverWriteSnapshotKillRestartRestore to=40m ;; + cutover-create) pkg=cmd/blockvolume bin=blockvolume.test name=TestCutoverCreateFromSnapshot to=20m ;; + fence-heal) pkg=cmd/blockvolume bin=blockvolume.test name=TestFencingRoundHealContinuesThePrimary to=10m ;; + fence-rejoin) pkg=cmd/blockvolume bin=blockvolume.test name=TestFencingRoundSurvivorRejoins to=10m ;; + double-failover) pkg=cmd/blockvolume bin=blockvolume.test name=TestDoubleFailoverReadsBackEveryAckedWrite to=15m ;; + *) echo "unknown entry: $t" >&2; exit 2 ;; + esac + log="$d/evidence/$t.log" + (cd "$d/source/$pkg" && env $extra "$d/bin/$bin" -test.run "^$name\$" -test.v -test.count 1 -test.timeout "$to") > "$log" 2>&1 + rc=$? + if [ "$rc" -eq 0 ] && grep -qE "^--- PASS: $name \(" "$log"; then + echo "PASS $t $name" >> "$d/evidence/verdicts.txt" + else + echo "FAIL $t $name rc=$rc" >> "$d/evidence/verdicts.txt" + tail -40 "$log" >&2 + failed=1 + fi + done + passes=$(grep -c '^PASS ' "$d/evidence/verdicts.txt" 2>/dev/null) || passes=0 + if [ "$n" -eq 0 ] || [ "$passes" -ne "$n" ]; then + echo "verdicts: $passes PASS of $n selected entries" >&2 + failed=1 + fi + cat "$d/evidence/verdicts.txt" >&2 + exit "$failed" + + - name: collect + always: true + actions: + - action: collect_path + node: host + path: "{{ scratch_root }}/{{ run_id }}/evidence" + name: "layout-gate" + + # Runs only when every earlier ordinary phase passed (the runner runs the + # always phases after them). The pass is read back from a collected copy of + # the evidence: a failed collection fails the gate, and the archive must + # hold one PASS verdict per selected entry and no other line. + - name: mark_pass + actions: + - action: collect_path + node: host + path: "{{ scratch_root }}/{{ run_id }}/evidence" + name: "layout-gate-pass" + - action: exec + node: host + timeout: 1m + env.GATE_ARCHIVE: "{{ artifacts_dir }}/layout-gate-pass.tgz" + env.GATE_TESTS: "{{ tests }}" + cmd: | + set -euf + v=$(tar -xzOf "$GATE_ARCHIVE" evidence/verdicts.txt) + n=0 + for t in $GATE_TESTS; do + n=$((n + 1)) + printf '%s\n' "$v" | grep -qE "^PASS $t Test[A-Za-z0-9_]+\$" || { echo "collected verdicts lack PASS for $t" >&2; exit 1; } + done + lines=$(printf '%s\n' "$v" | grep -c .) + [ "$n" -gt 0 ] && [ "$lines" -eq "$n" ] || { echo "collected verdicts: $lines lines for $n entries" >&2; exit 1; } + - action: emit_provenance + product: seaweed-block + tested_sha: "{{ head }}" + gate_pass: "1" + gate_status: "ok" + __weed_sha256: "{{ weed_sha256 }}" + __entries: "{{ tests }}" + + # Always runs and ends with the zero-residue assertion: no process whose cwd, + # executable or command line is inside this run's directory (the tests build + # and start every binary there, systemd units included), and no gap1-* unit. + # The run directory is removed only after that holds. + - name: cleanup + always: true + actions: + - action: exec + node: host + timeout: 3m + env.GATE_RUN: "{{ run_id }}" + env.GATE_ROOT: "{{ scratch_root }}" + env.GATE_TOKEN: "{{ gate_token }}" + receipt_path: "{{ bundle_dir }}/cleanup.receipt.json" + cmd: | + set -u + case "$GATE_RUN" in *[!0-9A-Za-z_-]*|'') echo 'run_id has unexpected characters' >&2; exit 2 ;; esac + case "$GATE_ROOT" in /*) ;; *) echo 'scratch_root must be absolute' >&2; exit 2 ;; esac + d="$GATE_ROOT/$GATE_RUN" + [ -e "$d" ] || exit 0 + # No token: prepare created nothing; whatever is there is not ours. + case "$GATE_TOKEN" in *[!0-9a-f]*|'') echo "this run created no directory; left untouched: $d" >&2; exit 0 ;; esac + [ ${#GATE_TOKEN} -eq 32 ] || { echo "this run created no directory; left untouched: $d" >&2; exit 0; } + [ "$(cat "$d/.layout-gate-owned" 2>/dev/null)" = "$GATE_TOKEN" ] || { echo "not created by this run; left untouched: $d" >&2; exit 2; } + residue() { + n=0 + for p in /proc/[0-9]*; do + [ "${p##*/}" = "$$" ] && continue + cwd=$(readlink "$p/cwd" 2>/dev/null || true) + exe=$(readlink "$p/exe" 2>/dev/null || true) + cmd=$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null || true) + case "$cwd|$exe|$cmd" in *"$d"/*) echo "residue process ${p##*/}: $exe" >&2; n=$((n + 1)) ;; esac + done + if command -v systemctl >/dev/null 2>&1; then + units=$(systemctl list-units --all --plain --no-legend 'gap1-*' 2>/dev/null | awk '{print $1}') + [ -z "$units" ] || { echo "residue units: $units" >&2; n=$((n + 1)); } + fi + [ "$n" -eq 0 ] + } + i=0 + until residue; do + i=$((i + 1)) + [ "$i" -lt 30 ] || { echo "residue remains after 60s; run directory kept: $d" >&2; exit 1; } + sleep 2 + done + rm -rf -- "$d" + [ ! -e "$d" ] || { echo "run directory not removed: $d" >&2; exit 1; } + echo "zero residue: $d"