diff --git a/seaweed-block/.gitattributes b/seaweed-block/.gitattributes index 22dc0a8d6c..68dbe2f417 100644 --- a/seaweed-block/.gitattributes +++ b/seaweed-block/.gitattributes @@ -1,2 +1,3 @@ *.sh text eol=lf core/chunkkernel/chunk-kernel-2.tsv text eol=lf +.github/model-code-trace.tsv text eol=lf diff --git a/seaweed-block/.github/model-code-trace.md b/seaweed-block/.github/model-code-trace.md index 3c8b881d25..d08e45cec9 100644 --- a/seaweed-block/.github/model-code-trace.md +++ b/seaweed-block/.github/model-code-trace.md @@ -8,6 +8,17 @@ path and `Module.Action`. Repeat a path to list alternative actions that cover it. Paths are case-sensitive; directories and glob patterns are not expanded. Missing, empty or malformed mappings refuse the check. +Source line numbers are not part of this file-wide mapping. Moving a function +or test within its file does not change its model obligations or rewrite the +table. The time-bound registry separately keys individual bounds by file, +function, bound kind and occurrence; CI scans current source locations for +diagnostics rather than committing those locations. + +Git uses its built-in union merge for this table so concurrent row additions +are retained. After a merge, sort and deduplicate the non-comment rows; the +checker refuses unsorted or duplicate rows. Review removals explicitly: a +union merge does not decide whether an old mapping should be removed. + The reviewed map uses the neutral public module names: `SnapshotRemoval`, `RestoreTarget`, `HolderInterface`, `EngineAdapter`, `StopAndRestart`, `MoveAdmission`, `Promotion`, `ProbeRound`, `FencingRound`, `VolumeCreate`, diff --git a/seaweed-block/.github/model-code-trace.tsv b/seaweed-block/.github/model-code-trace.tsv index 15a49d44f8..ecb232dab0 100644 --- a/seaweed-block/.github/model-code-trace.tsv +++ b/seaweed-block/.github/model-code-trace.tsv @@ -1,8 +1,24 @@ # Exact repository-relative pathModule.Action; repeat a path for alternatives. +cmd/blockvolume/snapshot_operation_shutdown.go SnapOps.Stall +cmd/sw-block/chunk.go CutTime.Poll +cmd/sw-block/cut_progress_poll.go CutTime.CliGiveUp +cmd/sw-block/cut_progress_poll.go CutTime.CliServerUnknown +cmd/sw-block/cut_progress_poll.go CutTime.CliSilent +cmd/sw-block/cut_progress_poll.go CutTime.HolderRestart +cmd/sw-block/cut_progress_poll.go CutTime.Poll +cmd/sw-block/snapshot_operation.go SnapOps.Send cmd/sw-block/volume_backup.go RestoreCommand.Abort cmd/sw-block/volume_backup.go RestoreCommand.AbortVerify cmd/sw-block/volume_backup.go RestoreCommand.Run cmd/sw-block/volume_backup.go RestoreCommand.Start +cmd/sw-block/volume_start_release.go StopAndRestart.IssueClean +cmd/sw-block/volume_start_release.go StopAndRestart.ReadClean +cmd/sw-block/volume_start_release.go StopAndRestart.SameEpochReopen +cmd/sw-block/volume_verbs.go CutTime.CliGiveUp +cmd/sw-block/volume_verbs.go CutTime.Poll +cmd/sw-block/workspace_show.go MoveAdmission.ReadForMove +core/authority/authority.go DeleteRetire.Retire +core/authority/authority_store_file.go DeleteRetire.Retire core/authority/workspace.go HolderInterface.ForcedMove core/authority/workspace.go HolderInterface.PlannedMove core/authority/workspace.go MoveAdmission.Ack @@ -20,7 +36,30 @@ core/authority/workspace_delete_reservation.go MoveAdmission.DelCheck core/authority/workspace_delete_reservation.go MoveAdmission.Reserve core/authority/workspace_lease_view.go HolderInterface.Grant core/authority/workspace_lease_view.go HolderInterface.Regrant +core/authority/workspace_retirement.go DeleteRetire.Retire core/engine/apply.go ReplicationPeer.Reconcile +core/frontend/chunkstore/catalog_b.go CleanBatch.Publish +core/frontend/chunkstore/catalog_b.go CleanBatch.Request +core/frontend/chunkstore/catalog_snapshot_operation.go CleanBatch.Publish +core/frontend/chunkstore/clean_admission.go CleanBatch.Begin +core/frontend/chunkstore/clean_admission.go CleanBatch.Close +core/frontend/chunkstore/clean_admission.go CleanBatch.Request +core/frontend/chunkstore/clean_b.go CleanBatch.BeginIn +core/frontend/chunkstore/clean_b.go CleanBatch.Close +core/frontend/chunkstore/clean_b.go CleanBatch.Effects +core/frontend/chunkstore/clean_b.go CleanBatch.PrepIn +core/frontend/chunkstore/clean_b.go CleanBatch.PrepOut +core/frontend/chunkstore/clean_b.go CutTime.Complete +core/frontend/chunkstore/clean_b.go PageChain.Sweep +core/frontend/chunkstore/clean_b.go SnapshotRemoval.BeginClean +core/frontend/chunkstore/clean_b.go SnapshotRemoval.EndClean +core/frontend/chunkstore/clean_b.go StaleClean.HeadRead +core/frontend/chunkstore/clean_intent_b.go CleanBatch.Publish +core/frontend/chunkstore/clean_intent_b.go CleanBatch.Request +core/frontend/chunkstore/clean_intent_b.go PageChain.CRead +core/frontend/chunkstore/clean_intent_b.go QueueCap.Consume +core/frontend/chunkstore/cut_verification_window.go CutTime.Complete +core/frontend/chunkstore/cut_verification_window.go CutWindow.CallTimeout core/frontend/chunkstore/layout/claim.go EngineAdapter.Takeover core/frontend/chunkstore/layout/claim.go MoveAdmission.ClaimB core/frontend/chunkstore/layout/claim.go SnapshotRemoval.Claim @@ -29,8 +68,16 @@ core/frontend/chunkstore/layout/clean.go EngineAdapter.MaintBegin core/frontend/chunkstore/layout/clean.go EngineAdapter.MaintEnd core/frontend/chunkstore/layout/clean.go SnapshotRemoval.BeginClean core/frontend/chunkstore/layout/clean.go SnapshotRemoval.EndClean +core/frontend/chunkstore/layout/clean_batch.go CleanBatch.PrepIn +core/frontend/chunkstore/layout/clean_batch.go CleanBatch.PrepOut +core/frontend/chunkstore/layout/clean_batch.go SnapshotRemoval.EndClean +core/frontend/chunkstore/layout/clean_batch.go SnapshotRemoval.Validate +core/frontend/chunkstore/layout/commit.go CutTime.Complete core/frontend/chunkstore/layout/commit.go EngineAdapter.Apply +core/frontend/chunkstore/layout/commit.go QueueCap.TakeBack core/frontend/chunkstore/layout/commit.go SnapshotRemoval.Commit +core/frontend/chunkstore/layout/commit.go StaleClean.CommitCheck +core/frontend/chunkstore/layout/commit.go StaleClean.HeadCommit core/frontend/chunkstore/layout/commit.go VolumeCreate.Commit core/frontend/chunkstore/layout/create.go RestoreTarget.CreateHead core/frontend/chunkstore/layout/create.go RestoreTarget.CreateVol @@ -39,14 +86,49 @@ core/frontend/chunkstore/layout/delete.go MoveAdmission.DelMark core/frontend/chunkstore/layout/delete.go MoveAdmission.DelRead core/frontend/chunkstore/layout/delete.go RestoreTarget.OpRelease core/frontend/chunkstore/layout/delete.go RestoreTarget.OpTomb +core/frontend/chunkstore/layout/delete_intent.go CutTime.Complete +core/frontend/chunkstore/layout/delete_intent.go PageChain.CAdvance +core/frontend/chunkstore/layout/delete_intent.go PageChain.CApply +core/frontend/chunkstore/layout/delete_intent.go PageChain.CRead +core/frontend/chunkstore/layout/delete_intent.go PageChain.CResolve +core/frontend/chunkstore/layout/delete_intent.go PageChain.Resend +core/frontend/chunkstore/layout/delete_intent.go PageChain.Send +core/frontend/chunkstore/layout/delete_intent.go PageChain.WritePage +core/frontend/chunkstore/layout/delete_intent.go QueueCap.Consume +core/frontend/chunkstore/layout/delete_intent.go QueueCap.Produce +core/frontend/chunkstore/layout/delete_intent.go VolDelSweep.Land +core/frontend/chunkstore/layout/delete_intent.go VolDelSweep.Stage +core/frontend/chunkstore/layout/format_level.go FormatGate.PublishOp +core/frontend/chunkstore/layout/format_level.go FormatGate.Upgrade1 +core/frontend/chunkstore/layout/head.go CleanBatch.Publish +core/frontend/chunkstore/layout/head.go CleanBatch.Request core/frontend/chunkstore/layout/head.go SnapshotRemoval.Abort core/frontend/chunkstore/layout/head.go SnapshotRemoval.Begin core/frontend/chunkstore/layout/head.go StopAndRestart.Apply core/frontend/chunkstore/layout/head.go StopAndRestart.Begin +core/frontend/chunkstore/layout/list_chain.go CutTime.Complete +core/frontend/chunkstore/layout/list_chain.go PageChain.CAdvance +core/frontend/chunkstore/layout/list_chain.go PageChain.CRead +core/frontend/chunkstore/layout/list_chain.go PageChain.CResolve +core/frontend/chunkstore/layout/list_chain.go PageChain.Resend +core/frontend/chunkstore/layout/list_chain.go PageChain.Send +core/frontend/chunkstore/layout/list_chain.go PageChain.WritePage +core/frontend/chunkstore/layout/list_chain.go QueueCap.Produce +core/frontend/chunkstore/layout/list_chain.go VolDelSweep.Land +core/frontend/chunkstore/layout/list_chain.go VolDelSweep.Stage +core/frontend/chunkstore/layout/maintenance_progress.go CutTime.Complete core/frontend/chunkstore/layout/objects.go SnapshotRemoval.Upload +core/frontend/chunkstore/layout/read.go CutTime.Complete +core/frontend/chunkstore/layout/remove.go CleanBatch.Effects +core/frontend/chunkstore/layout/remove.go CutTime.Complete +core/frontend/chunkstore/layout/remove.go PageChain.Sweep core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Issue core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Stat core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Validate +core/frontend/chunkstore/layout/remove.go StaleClean.DeleteIt +core/frontend/chunkstore/layout/remove.go StaleClean.HeadRead +core/frontend/chunkstore/layout/remove.go StaleClean.MarkIt +core/frontend/chunkstore/layout/remove.go StaleClean.Stat core/frontend/chunkstore/layout/snapshots.go EngineAdapter.OpWrite core/frontend/chunkstore/layout/snapshots.go MoveAdmission.OpWrite core/frontend/chunkstore/layout/snapshots.go RestoreTarget.AddDep @@ -56,42 +138,115 @@ core/frontend/chunkstore/layout/start.go StopAndRestart.CrashRestart core/frontend/chunkstore/layout/start.go VolumeCreate.Claim core/frontend/chunkstore/layout_create.go VolumeCreate.IssueHead core/frontend/chunkstore/layout_create.go VolumeCreate.IssueVol +core/frontend/chunkstore/layout_remote.go CleanBatch.Begin +core/frontend/chunkstore/layout_remote.go CleanBatch.Publish +core/frontend/chunkstore/layout_remote.go CutTime.Complete core/frontend/chunkstore/layout_remote.go EngineAdapter.Begin core/frontend/chunkstore/layout_remote.go EngineAdapter.ReadHead core/frontend/chunkstore/layout_remote.go EngineAdapter.SendCommit core/frontend/chunkstore/layout_remote.go EngineAdapter.SettleAbort core/frontend/chunkstore/layout_remote.go EngineAdapter.TakeAbandon +core/frontend/chunkstore/layout_remote.go FormatGate.CutPublish +core/frontend/chunkstore/layout_remote.go FormatGate.Upgrade1 +core/frontend/chunkstore/layout_remote.go PageChain.CRead core/frontend/chunkstore/layout_remote.go StopAndRestart.SendCommit core/frontend/chunkstore/layout_remote.go StopAndRestart.SettleAbort +core/frontend/chunkstore/layout_store.go CleanBatch.Publish +core/frontend/chunkstore/layout_store.go CleanBatch.Request core/frontend/chunkstore/layout_store.go SnapshotRemoval.ApplyDelete core/frontend/chunkstore/layout_store.go SnapshotRemoval.ApplyMark +core/frontend/chunkstore/layout_store.go StaleClean.Adopt +core/frontend/chunkstore/maintenance_request.go CutTime.CallTimeout +core/frontend/chunkstore/retain_b.go CleanBatch.Publish +core/frontend/chunkstore/retain_b.go CleanBatch.Request +core/frontend/chunkstore/retain_b.go CutTime.Complete +core/frontend/chunkstore/snapshot_delete_operation.go FormatGate.AdmitOp +core/frontend/chunkstore/snapshot_delete_operation.go SnapDelete.Send +core/frontend/chunkstore/snapshot_delete_target.go FormatGate.AdmitOp +core/frontend/chunkstore/snapshot_operation.go SnapOps.Retire +core/frontend/chunkstore/snapshot_operation.go SnapOps.Send +core/frontend/chunkstore/snapshot_operation.go SnapOps.TornAdmit +core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Delete +core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Publish +core/frontend/chunkstore/snapshot_operation_index.go SnapOps.GC +core/frontend/chunkstore/snapshot_operation_index.go SnapOps.Poll +core/frontend/chunkstore/snapshot_operation_index.go SnapOps.TermFlag core/frontend/chunkstore/swfs.go VolumeCreate.Land +core/frontend/durable/maintenance_progress.go CutTime.Complete +core/frontend/durable/maintenance_progress.go CutTime.Fail +core/frontend/durable/maintenance_progress.go CutTime.Tick +core/frontend/durable/provider_chunk.go CutTime.Admit +core/frontend/durable/provider_chunk.go CutWindow.Fail core/frontend/durable/provider_chunk.go EngineAdapter.SettleResume core/frontend/durable/provider_chunk.go EngineAdapter.StartStop +core/frontend/durable/provider_chunk.go FormatGate.CutPublish core/frontend/durable/provider_chunk.go HolderInterface.StopBegin core/frontend/durable/provider_chunk.go StopAndRestart.SendDetach core/frontend/durable/provider_chunk.go StopAndRestart.SettleResume core/frontend/durable/provider_layout.go EngineAdapter.SettleDown core/frontend/durable/provider_layout.go StopAndRestart.SettleDown +core/frontend/durable/provider_preempt.go CutTime.Preempt +core/frontend/durable/provider_preempt.go CutTime.Settle core/frontend/durable/storage_adapter.go EngineAdapter.GuestWrite core/frontend/durable/storage_adapter.go HolderInterface.Write +core/frontend/durable/storage_adapter.go WALHold.Resubmit +core/frontend/iscsi/scsi.go WALHold.Stall +core/frontend/nvme/io.go WALHold.Stall +core/host/master/format_gate.go FormatGate.Finalize +core/host/master/format_gate.go FormatGate.Grant +core/host/master/format_gate.go FormatGate.Place +core/host/master/format_gate.go FormatGate.Report +core/host/master/format_gate.go FormatGate.Retire +core/host/master/journal_isolation.go DeleteRetire.HostRetire core/host/master/layout_ready.go VolumeCreate.Place +core/host/master/observation_snapshot.go DeleteRetire.HostRetire core/host/master/probe_round.go FencingRound.Deliver core/host/master/probe_round.go FencingRound.Open core/host/master/product_loop.go FencingRound.Decide core/host/master/product_loop.go Promotion.Decide +core/host/master/services.go FormatGate.Report +core/host/master/spec_retirement.go DeleteRetire.ReadOK core/host/master/store_attestation.go ReplicationPeer.Attest +core/host/master/workspace_binding.go FormatGate.Grant +core/host/master/workspace_binding.go MoveAdmission.Ack +core/host/master/workspace_service.go FormatGate.Place +core/host/master/workspace_service.go FormatGate.Renew core/host/master/workspace_service.go MoveAdmission.ReadForMove core/host/master/workspace_service.go StopAndRestart.ReadClean +core/host/volume/chunk_control.go CutTime.InProgress +core/host/volume/chunk_control.go CutWindow.Fail +core/host/volume/chunk_control.go FormatGate.Upgrade1 +core/host/volume/chunk_control.go SnapOps.Start +core/host/volume/host.go FormatGate.Downgrade +core/host/volume/host.go FormatGate.Renew +core/host/volume/host.go FormatGate.Upgrade +core/host/volume/manual_cut.go CutTime.Admit +core/host/volume/manual_cut.go CutTime.InProgress +core/host/volume/manual_cut.go CutTime.Poll +core/host/volume/manual_cut.go CutTime.Retire +core/host/volume/plain_detach_handle.go CutTime.OtherEnd +core/host/volume/plain_detach_handle.go CutTime.OtherStep +core/host/volume/plain_detach_handle.go CutTime.Preempt +core/host/volume/plain_detach_handle.go CutTime.Settle +core/host/volume/plain_detach_handle.go CutTime.SettleStall core/host/volume/primary_evidence.go FencingRound.Adopt core/host/volume/primary_evidence.go Promotion.Adopt core/host/volume/primary_evidence.go Promotion.Refuse core/host/volume/probe_round.go FencingRound.Answer +core/host/volume/recovery_watchdog.go RecoveryProgress.Authority +core/host/volume/recovery_watchdog.go RecoveryProgress.Fence +core/host/volume/recovery_watchdog.go RecoveryProgress.Replay +core/host/volume/recovery_watchdog.go RecoveryProgress.Stall +core/host/volume/recovery_watchdog.go RecoveryProgress.ToFence +core/host/volume/snapshot_operation.go SnapOps.Start +core/host/volume/workspace_lease.go FormatGate.Renew core/host/volume/workspace_lease.go HolderInterface.Expire core/host/volume/workspace_lease.go MoveAdmission.StopOnExpiry core/host/volume/workspace_lease.go MoveAdmission.Write core/host/volume/workspace_lease.go SnapshotRemoval.Expire core/host/volume/workspace_lease.go StopAndRestart.Write +core/host/volume/workspace_runtime.go FormatGate.Renew +core/host/volume/workspace_startup.go FormatGate.Renew core/lifecycle/store.go VolumeCreate.MarkReady core/lifecycle/store.go VolumeCreate.Record core/replication/peer.go Promotion.Ship1 @@ -107,102 +262,58 @@ core/replication/volume.go Promotion.Write1 core/replication/volume.go Promotion.Write2 core/replication/volume.go ReplicationPeer.Ack core/replication/volume.go ReplicationPeer.Write +core/storage/chunk_coverage.go SlotFence.Publish +core/storage/chunk_coverage_map.go MoveWide2.Write core/storage/chunk_head_belt.go HolderInterface.Fence +core/storage/chunk_layer.go CutTime.Settle +core/storage/chunk_layer.go CutWindow.Publish +core/storage/chunk_layer.go CutWindow.Retry core/storage/chunk_layer.go EngineAdapter.EngineReRead core/storage/chunk_layer.go EngineAdapter.NoOpCut +core/storage/chunk_layer.go FormatGate.Upgrade1 core/storage/chunk_layer.go HolderInterface.Commit core/storage/chunk_layer.go HolderInterface.StopCommit core/storage/chunk_layer.go MoveAdmission.Detach core/storage/chunk_layer.go MoveAdmission.Publish core/storage/chunk_layer.go SnapshotRemoval.Write +core/storage/chunk_manual_cut.go CutTime.Busy +core/storage/chunk_manual_cut.go CutTime.PublishLost +core/storage/chunk_manual_cut.go CutTime.Settle +core/storage/chunk_manual_cut.go CutTime.SettleInherited +core/storage/chunk_manual_cut.go CutTime.SettleStall +core/storage/chunk_manual_cut.go HolderInterface.Fence +core/storage/chunk_preempt.go CutTime.OtherStep +core/storage/chunk_preempt.go CutTime.Preempt +core/storage/chunk_public.go FormatGate.Upgrade1 +core/storage/chunk_seam.go FormatGate.Upgrade1 core/storage/chunk_state_upgrade.go SlotFence.Publish core/storage/chunk_state_upgrade.go SlotFence.Sync +core/storage/chunk_upload.go CutWindow.CallTimeout +core/storage/chunk_upload.go CutWindow.Start +core/storage/cut_progress_window.go CutTime.Complete +core/storage/cut_progress_window.go CutWindow.CallTimeout +core/storage/cut_progress_window.go CutWindow.Complete +core/storage/cut_progress_window.go CutWindow.Fail +core/storage/cut_progress_window.go CutWindow.Tick +core/storage/flusher.go WALHold.Reclaim +core/storage/recovery_progress.go RecoveryProgress.Replay +core/storage/wal_admission.go WALHold.Arrive +core/storage/wal_admission_fast.go WALHold.FastArrive +core/storage/wal_admission_fast.go WALHold.FastReEnter +core/storage/wal_admission_fast.go WALHold.FastResubmit +core/storage/wal_admission_fifo.go WALHold.Admit +core/storage/wal_admission_fifo.go WALHold.Arrive +core/storage/wal_admission_fifo.go WALHold.ReEnter +core/storage/wal_hold_window.go WALHold.CapAnswer +core/storage/wal_hold_window.go WALHold.Stall +core/storage/wal_write_hold.go WALHold.CapAnswer +core/storage/wal_write_hold.go WALHold.Stall +core/storage/walstore.go WALHold.Admit +core/storage/walstore_v3.go RecoveryProgress.Fence +core/storage/walstore_v3.go SlotFence2.OpenNew core/transport/catchup_sender.go ReplicationPeer.CatchUp core/transport/rebuild_sender.go ReplicationPeer.Rebuild core/transport/replica.go FencingRound.Recv core/transport/replica.go ReplicationPeer.CatchUp core/transport/replica.go ReplicationPeer.Rebuild core/transport/replica.go ReplicationPeer.Ship -core/storage/chunk_coverage.go SlotFence.Publish -core/storage/chunk_coverage_map.go MoveWide2.Write -core/storage/walstore_v3.go SlotFence2.OpenNew - -core/frontend/chunkstore/snapshot_operation.go SnapOps.Send -core/frontend/chunkstore/snapshot_operation.go SnapOps.TornAdmit -core/frontend/chunkstore/snapshot_operation.go SnapOps.Retire -core/frontend/chunkstore/snapshot_operation_index.go SnapOps.TermFlag -core/frontend/chunkstore/snapshot_operation_index.go SnapOps.GC -core/frontend/chunkstore/snapshot_operation_index.go SnapOps.Poll -core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Publish -core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Delete -core/host/volume/chunk_control.go SnapOps.Start -cmd/sw-block/snapshot_operation.go SnapOps.Send -core/host/volume/snapshot_operation.go SnapOps.Start -cmd/blockvolume/snapshot_operation_shutdown.go SnapOps.Stall -core/frontend/chunkstore/snapshot_delete_operation.go SnapDelete.Send -core/storage/wal_admission_fast.go WALHold.FastArrive -core/storage/wal_admission_fast.go WALHold.FastReEnter -core/storage/wal_admission_fast.go WALHold.FastResubmit -core/storage/wal_admission.go WALHold.Arrive -core/storage/wal_admission_fifo.go WALHold.Arrive -core/storage/wal_admission_fifo.go WALHold.ReEnter -core/storage/wal_admission_fifo.go WALHold.Admit -core/storage/walstore.go WALHold.Admit -core/frontend/durable/storage_adapter.go WALHold.Resubmit -core/storage/flusher.go WALHold.Reclaim -core/storage/wal_hold_window.go WALHold.Stall -core/storage/wal_write_hold.go WALHold.Stall -core/storage/wal_hold_window.go WALHold.CapAnswer -core/storage/wal_write_hold.go WALHold.CapAnswer -core/frontend/nvme/io.go WALHold.Stall -core/frontend/iscsi/scsi.go WALHold.Stall -core/host/master/format_gate.go FormatGate.Finalize -core/host/master/format_gate.go FormatGate.Place -core/host/master/workspace_service.go FormatGate.Place -core/host/master/format_gate.go FormatGate.Grant -core/host/master/workspace_binding.go FormatGate.Grant -core/host/master/format_gate.go FormatGate.Report -core/host/master/services.go FormatGate.Report -core/host/master/format_gate.go FormatGate.Retire -core/host/volume/host.go FormatGate.Upgrade -core/host/volume/host.go FormatGate.Downgrade -core/frontend/chunkstore/layout/format_level.go FormatGate.Upgrade1 -core/frontend/chunkstore/layout/format_level.go FormatGate.PublishOp -core/frontend/chunkstore/snapshot_delete_target.go FormatGate.AdmitOp -core/frontend/chunkstore/snapshot_delete_operation.go FormatGate.AdmitOp -core/storage/recovery_progress.go RecoveryProgress.Replay -core/host/volume/recovery_watchdog.go RecoveryProgress.Replay -core/storage/walstore_v3.go RecoveryProgress.Fence -core/host/volume/recovery_watchdog.go RecoveryProgress.Fence -core/host/volume/recovery_watchdog.go RecoveryProgress.ToFence -core/host/volume/recovery_watchdog.go RecoveryProgress.Authority -core/host/volume/recovery_watchdog.go RecoveryProgress.Stall -core/frontend/chunkstore/layout/delete_intent.go PageChain.WritePage -core/frontend/chunkstore/layout/list_chain.go PageChain.WritePage -core/frontend/chunkstore/layout/delete_intent.go PageChain.Send -core/frontend/chunkstore/layout/list_chain.go PageChain.Send -core/frontend/chunkstore/layout/delete_intent.go PageChain.Resend -core/frontend/chunkstore/layout/list_chain.go PageChain.Resend -core/frontend/chunkstore/layout/delete_intent.go PageChain.CRead -core/frontend/chunkstore/layout/list_chain.go PageChain.CRead -core/frontend/chunkstore/layout/delete_intent.go PageChain.CApply -core/frontend/chunkstore/layout/delete_intent.go PageChain.CAdvance -core/frontend/chunkstore/layout/list_chain.go PageChain.CAdvance -core/frontend/chunkstore/layout/delete_intent.go PageChain.CResolve -core/frontend/chunkstore/layout/list_chain.go PageChain.CResolve -core/frontend/chunkstore/clean_intent_b.go PageChain.CRead -core/frontend/chunkstore/layout_remote.go PageChain.CRead -core/frontend/chunkstore/layout/remove.go PageChain.Sweep -core/frontend/chunkstore/clean_b.go PageChain.Sweep -core/frontend/chunkstore/layout/remove.go StaleClean.Stat -core/frontend/chunkstore/layout/remove.go StaleClean.HeadRead -core/frontend/chunkstore/layout/remove.go StaleClean.MarkIt -core/frontend/chunkstore/layout/remove.go StaleClean.DeleteIt -core/frontend/chunkstore/layout_store.go StaleClean.Adopt -core/frontend/chunkstore/layout/commit.go StaleClean.HeadCommit -core/frontend/chunkstore/layout/commit.go StaleClean.CommitCheck -core/frontend/chunkstore/layout/delete_intent.go QueueCap.Produce -core/frontend/chunkstore/layout/list_chain.go QueueCap.Produce -core/frontend/chunkstore/layout/delete_intent.go QueueCap.Consume -core/frontend/chunkstore/clean_intent_b.go QueueCap.Consume -core/frontend/chunkstore/layout/commit.go QueueCap.TakeBack diff --git a/seaweed-block/.github/process-level-tests.txt b/seaweed-block/.github/process-level-tests.txt index 6960f23b0e..741d925ac5 100644 --- a/seaweed-block/.github/process-level-tests.txt +++ b/seaweed-block/.github/process-level-tests.txt @@ -89,3 +89,11 @@ TestProcedureLogTimesUseTheUTCInstant # Snapshot operation intent and publication receipts survive real holder kills. TestSnapshotOperationIntentAndPublicationCrashBoundaries TestSnapshotOperationKillReceiptRejectsOrdinaryExit + +# Two weed clusters side by side: a filer of one that reaches the other's master +# is in its own filer group, so the other's single-filer census still passes. +TestWeedClustersSideBySideKeepTheirOwnFilerCensus + +# Kubernetes state: a holder on a wiped state directory never comes up empty. +TestRF1HolderOnAWipedStateDirectoryRefusesStoreLost +TestRF3WipedPrimaryRefusesAndASurvivorServesItsData diff --git a/seaweed-block/.github/pull_request_template.md b/seaweed-block/.github/pull_request_template.md index 61589136cc..f8bd94d181 100644 --- a/seaweed-block/.github/pull_request_template.md +++ b/seaweed-block/.github/pull_request_template.md @@ -3,6 +3,7 @@ Machine/INV: / Model: Red-first: Simplest: +Time bounds: Five questions, answered in plain words before review: Serves: diff --git a/seaweed-block/.github/scripts/known-bugs-test.sh b/seaweed-block/.github/scripts/known-bugs-test.sh new file mode 100644 index 0000000000..6540438cbe --- /dev/null +++ b/seaweed-block/.github/scripts/known-bugs-test.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +root=$(mktemp -d) +trap 'rm -rf "$root"' EXIT +mkdir -p "$root/bin" +cat >"$root/bin/go" <<'EOF' +#!/usr/bin/env bash +printf '%s\n' "$FAKE_GO_OUTPUT" +exit "$FAKE_GO_STATUS" +EOF +chmod +x "$root/bin/go" +export PATH="$root/bin:$PATH" +cd "$root" +check() { + local name=$1 status=$2 output=$3 want=$4 message=$5 actual=0 + FAKE_GO_STATUS="$status" FAKE_GO_OUTPUT="$output" bash "$here/known-bugs.sh" >result 2>&1 <<'LIST' || actual=$? +#1 ./fixture TestKnown +LIST + if [ "$actual" != "$want" ] || ! grep -q "$message" result; then + echo "FAIL: $name (exit $actual, expected $want)"; cat result; exit 1 + fi + if [ "$message" != 'now PASSES' ] && grep -q 'now PASSES' result; then + echo "FAIL: $name falsely called fixed"; cat result; exit 1 + fi +} +check failure 1 '--- FAIL: TestKnown (0.00s)' 0 'still fails' +check pass 0 '--- PASS: TestKnown (0.00s)' 1 'now PASSES' +check missing 0 'ok fixture [no tests to run]' 1 'did not run' +check skipped 0 '--- SKIP: TestKnown (0.00s)' 1 'did not run' +check build 1 'FAIL fixture [build failed]' 1 'failed to build' +check other 1 '--- FAIL: TestKnownOther (0.00s)' 1 'did not run' +check subtest 1 ' --- FAIL: TestKnown/child (0.00s)' 1 'did not run' +check interrupted 1 '=== RUN TestKnown' 1 'did not run' +check inconsistent 0 '--- FAIL: TestKnown (0.00s)' 1 'did not run' +echo 'known-bugs: exact failure, pass, missing, skip, build, other test and interruption controls PASS' diff --git a/seaweed-block/.github/scripts/known-bugs.sh b/seaweed-block/.github/scripts/known-bugs.sh new file mode 100644 index 0000000000..59d17d53fe --- /dev/null +++ b/seaweed-block/.github/scripts/known-bugs.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Read "issue package test" rows. Only an observed failure of that exact test +# proves the reproduction still runs; a missing/skipped test is not a fix. +set -uo pipefail +ok=1 +while read -r issue pkg test; do + [ -n "$issue" ] || continue + out="out-${test}.txt" + status=0 + go test -v -count=1 -run "^${test}\$" "$pkg" >"$out" 2>&1 || status=$? + if [ "$status" -ne 0 ] && grep -q "^--- FAIL: ${test} (" "$out"; then + echo "${test} (${issue}) still fails, as expected" + elif [ "$status" = 0 ] && grep -q "^--- PASS: ${test} (" "$out"; then + echo "::error::${test} (${pkg}) now PASSES: ${issue} looks fixed, remove its skip" + ok=0 + else + echo "::error::${test} (${pkg}) did not run to a verdict or failed to build (exit ${status}):" + tail -20 "$out" + ok=0 + fi +done +[ "$ok" = 1 ] diff --git a/seaweed-block/.github/scripts/model-trace-check-test.py b/seaweed-block/.github/scripts/model-trace-check-test.py index cb6d35f58f..436a75f736 100644 --- a/seaweed-block/.github/scripts/model-trace-check-test.py +++ b/seaweed-block/.github/scripts/model-trace-check-test.py @@ -35,6 +35,19 @@ class ModelTraceTests(unittest.TestCase): def test_unmapped_files_keep_existing_policy(self): self.assertEqual(checker.check("existing prose", ["docs/a.md", "core/a.go.bak"], self.mapping), []) + def test_line_only_rebase_keeps_committed_mapping_and_obligations(self): + with tempfile.TemporaryDirectory() as tmp: + source = Path(tmp) / "a.go" + mapping = Path(tmp) / "model-code-trace.tsv" + mapping.write_text("core/a.go\tEngineAdapter.Begin\n", encoding="utf-8") + committed = mapping.read_bytes() + for padding in ("", "// unrelated rebase\n\n\n"): + source.write_text(padding + "package a\nfunc begin() {}\n", encoding="utf-8") + actual = checker.read_mapping(mapping) + self.assertEqual(checker.check("EngineAdapter.Begin", ["core/a.go"], actual), []) + self.assertEqual(len(checker.check("Other.Begin", ["core/a.go"], actual)), 1) + self.assertEqual(mapping.read_bytes(), committed) + def test_repository_map_covers_claimed_head_create(self): mapping = checker.read_mapping(SCRIPT.parent.parent / "model-code-trace.tsv") paths = ["core/frontend/chunkstore/layout/create.go"] @@ -72,6 +85,58 @@ class ModelTraceTests(unittest.TestCase): with self.assertRaises(ValueError): checker.read_mapping(mapping) + def test_mapping_requires_sorted_unique_rows_after_resolution(self): + with tempfile.TemporaryDirectory() as tmp: + mapping = Path(tmp) / "map.tsv" + a = "core/a.go\tEngineAdapter.Begin\n" + b = "core/b.go\tMoveAdmission.Revoke\n" + for content in (b + a, a + a): + with self.subTest(content=content): + mapping.write_text(content, encoding="utf-8") + with self.assertRaisesRegex(ValueError, "sorted and unique"): + checker.read_mapping(mapping) + mapping.write_text(a + b, encoding="utf-8") + self.assertEqual(set(checker.read_mapping(mapping)), {"core/a.go", "core/b.go"}) + + def test_model_trace_deletion_and_adjacent_addition_require_resolution(self): + attributes = (SCRIPT.parent.parent.parent / ".gitattributes").read_text(encoding="utf-8") + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + def git(*args, check=True): + return subprocess.run(["git", *args], cwd=root, capture_output=True, + check=check, text=True, timeout=15) + git("init", "-b", "base") + git("config", "user.name", "Example") + git("config", "user.email", "example@example.invalid") + git("config", "commit.gpgsign", "false") + (root / ".gitattributes").write_text(attributes, encoding="utf-8") + mapping = root / ".github" / "model-code-trace.tsv" + mapping.parent.mkdir() + a = "core/a.go\tEngineAdapter.Begin\n" + removed = "core/b.go\tMoveAdmission.Revoke\n" + added = "core/b.go\tVolumeCreate.Claim\n" + c = "core/c.go\tVolumeCreate.Claim\n" + mapping.write_text(a + removed + c, encoding="utf-8") + git("add", ".") + git("commit", "-m", "base") + git("switch", "-c", "remove") + mapping.write_text(a + c, encoding="utf-8") + git("commit", "-am", "remove obsolete binding") + git("switch", "-c", "add", "base") + mapping.write_text(a + removed + added + c, encoding="utf-8") + git("commit", "-am", "add adjacent binding") + git("switch", "remove") + merged = git("merge", "--no-edit", "add", check=False) + self.assertEqual(merged.returncode, 1, merged.stdout + merged.stderr) + self.assertIn("<<<<<<<", mapping.read_text(encoding="utf-8")) + # Resolve deliberately: keep the new binding, preserve the deletion. + mapping.write_text(a + added + c, encoding="utf-8") + self.assertNotIn(removed, mapping.read_text(encoding="utf-8")) + self.assertEqual(checker.read_mapping(mapping)["core/b.go"], {"VolumeCreate.Claim"}) + attr = subprocess.run(["git", "check-attr", "merge", "--", ".github/model-code-trace.tsv"], + cwd=SCRIPT.parent.parent.parent, capture_output=True, check=True, text=True, timeout=15) + self.assertEqual(attr.stdout.strip(), ".github/model-code-trace.tsv: merge: unspecified") + if __name__ == "__main__": unittest.main() diff --git a/seaweed-block/.github/scripts/model-trace-check.py b/seaweed-block/.github/scripts/model-trace-check.py index cec3ecc1a4..d3d9da064a 100644 --- a/seaweed-block/.github/scripts/model-trace-check.py +++ b/seaweed-block/.github/scripts/model-trace-check.py @@ -11,6 +11,7 @@ PURE = re.compile(rf"NONE \(pure function of ({IDENT})\)") def read_mapping(path): mapping = {} + previous = None for number, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1): if not line.strip() or line.startswith("#"): continue @@ -25,6 +26,9 @@ def read_mapping(path): raise ValueError(f"mapping line {number}: expected a repository-relative exact path") if not ACTION.fullmatch(action): raise ValueError(f"mapping line {number}: invalid Module.Action") + if previous is not None and line <= previous: + raise ValueError(f"mapping line {number}: rows must be sorted and unique; sort and deduplicate the union") + previous = line mapping.setdefault(file, set()).add(action) if not mapping: raise ValueError("model mapping is empty; populate it before enabling this gate") diff --git a/seaweed-block/.github/scripts/pr-gate-base-test.py b/seaweed-block/.github/scripts/pr-gate-base-test.py new file mode 100644 index 0000000000..34f843f73b --- /dev/null +++ b/seaweed-block/.github/scripts/pr-gate-base-test.py @@ -0,0 +1,58 @@ +"""Trusted-base gate contracts and a PR that replaces its own checkers.""" +from pathlib import Path +import os, shutil, subprocess, tempfile, unittest + +ROOT = Path(__file__).resolve().parents[2] + +class BaseGateTests(unittest.TestCase): + def test_readonly_events_and_separate_base_checkout(self): + for filename in ('spec-trace.yml', 'post-merge-review.yml'): + with self.subTest(workflow=filename): + text=(ROOT/'.github/workflows'/filename).read_text() + self.assertIn(' pull_request:',text) + self.assertNotIn('pull_request_target:',text) + self.assertIn(' contents: read',text) + self.assertNotIn('secrets.',text) + self.assertIn(' runs-on: ubuntu-latest',text) + self.assertIn('ref: ${{ github.event.pull_request.base.sha }}',text) + self.assertIn('path: trusted-base',text) + self.assertIn('working-directory: trusted-base',text) + self.assertIn('persist-credentials: false',text) + self.assertNotIn('ref: ${{ github.event.pull_request.head.sha }}',text) + self.assertNotIn('ref: ${{ github.sha }}',text) + text=(ROOT/'.github/workflows/spec-trace.yml').read_text() + self.assertIn('go-version-file: trusted-base/go.mod',text) + + def test_pr_cannot_replace_base_validators_or_allowlist(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp); source=root/'source'; source.mkdir() + scripts=source/'.github/scripts'; scripts.mkdir(parents=True) + names=('spec-trace-check.sh','post-merge-review-check.sh','post-merge-review-changed.sh') + for name in names: shutil.copyfile(ROOT/'.github/scripts'/name,scripts/name) + allow=source/'.github/post-merge-review-allow.txt'; allow.write_text('docs/**\n') + def git(*args,cwd=source): + return subprocess.check_output(['git',*args],cwd=cwd,stderr=subprocess.PIPE,timeout=15) + git('init','-b','main'); git('config','user.name','Example'); git('config','user.email','example@example.invalid'); git('config','commit.gpgsign','false') + git('add','.'); git('commit','-m','base') + base=git('rev-parse','HEAD').decode().strip() + (source/'docs').mkdir(); (source/'docs/example.md').write_text('Documentation') + git('add','.'); git('commit','-m','documentation') + good=git('rev-parse','HEAD').decode().strip() + for name in ('spec-trace-check.sh','post-merge-review-check.sh'): + (scripts/name).write_text('#!/bin/sh\ntouch ../pr-code-ran\nexit 0\n') + allow.write_text('*\n') + git('add','.'); git('commit','-m','replace validators') + bad=git('rev-parse','HEAD').decode().strip() + checkout=root/'trusted-base'; git('clone','--quiet',str(source),str(checkout)); git('checkout','--detach',base,cwd=checkout) + self.assertEqual(git('rev-parse','HEAD',cwd=checkout).decode().strip(),base) + body=checkout/'body.txt' + valid='Feature: documentation\nMachine/INV: DOCS\nModel: NONE (documentation fixture only)\nRed-first: fixture validation\n' + for head,description,success in ((good,valid,True),(bad,'missing trace',False)): + body.write_text(description) + changes=git('diff','-z','--name-status','--no-renames',base+'...'+head,cwd=checkout) + for command in (['spec-trace-check.sh',str(body)],['post-merge-review-check.sh','.github/post-merge-review-allow.txt']): + result=subprocess.run(['bash','.github/scripts/'+command[0],*command[1:]],cwd=checkout,input=changes,capture_output=True,timeout=15) + self.assertEqual(result.returncode==0,success,result.stdout.decode()+result.stderr.decode()) + self.assertFalse((root/'pr-code-ran').exists()) + +if __name__=='__main__': unittest.main() diff --git a/seaweed-block/.github/scripts/public-text-check-test.sh b/seaweed-block/.github/scripts/public-text-check-test.sh index a59dc7e096..fb55839c2a 100755 --- a/seaweed-block/.github/scripts/public-text-check-test.sh +++ b/seaweed-block/.github/scripts/public-text-check-test.sh @@ -16,6 +16,34 @@ expect() { # expect RC NAME } echo "plain line" >> a.txt; git commit -q -am "add a plain line" expect 0 "clean change" "$mb" HEAD title body +# Synthetic equivalents exercise private-path and run-metadata signatures. +for leaked in \ + 'Parsing file /home/example/run-1/Example.tla' \ + 'Synthetic model run with 1 worker on 2 cores with 123MB heap [pid: 12345]' \ + '[pid: 12345]' \ + 'pid=12345' \ + '2 cores with 123MB heap'; do + echo "$leaked" >> a.txt; git commit -q -am "model output" + expect 1 "raw run metadata in added text" "$mb" HEAD title body + git reset -q --hard HEAD~1 +done +echo '/home/example/run-1' > body +expect 1 "home path in description" "$mb" HEAD title body; : > body +echo 'docs/spec/example/recorded-example/RESULT.txt' > body +expect 1 "artifact reference in description" "$mb" HEAD title body; : > body +echo '[pid: 12345]' > title +expect 1 "run metadata in title" "$mb" HEAD title body; : > title +for artifact in docs/spec/example/recorded-example/RESULT.txt docs/spec/recorded-example.txt; do + mkdir -p "$(dirname "$artifact")"; echo 'all checks passed' > "$artifact" + git add "$artifact"; git commit -q -m "add model artifact" + expect 1 "artifact path even with clean contents" "$mb" HEAD title body + artifact_base=$(git rev-parse HEAD) + git rm -q "$artifact"; git commit -q -m "remove model artifact" + expect 0 "artifact removal is allowed" "$artifact_base" HEAD title body + git reset -q --hard HEAD~2 +done +echo 'Model workers execute in parallel; heap limits and PID namespaces are documented.' > body +expect 0 "ordinary explanatory prose" "$mb" HEAD title body; : > body seat="clau""de06"; path="V:/sha""re/x"; nas="share/rd""ma/y" echo "// asked by $seat" >> a.txt; git commit -q -am "comment" expect 1 "seat name in an added line" "$mb" HEAD title body @@ -41,6 +69,23 @@ expect 1 "backslash form of the share path in the title" "$mb2" HEAD title body; expect 2 "a missing title file is an error, not clean" "$mb2" HEAD no-such-title body expect 2 "a missing description file is an error, not clean" "$mb2" HEAD title no-such-body expect 2 "an unknown commit is an error, not clean" 0000000000000000000000000000000000000000 HEAD title body +# Only the NUL-separated artifact enumeration fails, after partial output; +# every other git call delegates to the real executable. +real_git=$(command -v git) +mkdir -p fakegit +cat > fakegit/git <<'EOF' +#!/usr/bin/env bash +if [[ $1 == diff && ${2:-} == --name-only && ${3:-} == -z ]]; then + printf 'docs/spec/clean.txt\0' + exit 7 +fi +exec "$PUBLIC_TEXT_REAL_GIT" "$@" +EOF +chmod +x fakegit/git +rc=0 +PUBLIC_TEXT_REAL_GIT="$real_git" PATH="$PWD/fakegit:$PATH" bash "$here/public-text-check.sh" "$mb2" HEAD title body >out 2>&1 || rc=$? +[ "$rc" = 2 ] || { echo "public-text-check-test: failed artifact enumeration: exit $rc, want 2"; cat out; exit 1; } +if grep -q 'public-text: clean' out; then echo 'public-text-check-test: failed artifact enumeration printed clean'; cat out; exit 1; fi # A grep that fails (exit 2) is an error: the check must refuse and never print "clean". mkdir -p fakebin; printf '#!/bin/sh exit 2 diff --git a/seaweed-block/.github/scripts/public-text-check.sh b/seaweed-block/.github/scripts/public-text-check.sh index 3146d095c5..f4e7067548 100755 --- a/seaweed-block/.github/scripts/public-text-check.sh +++ b/seaweed-block/.github/scripts/public-text-check.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Refuses internal names in what a pull request makes public: the lines it # adds, its commit messages, its title and its description. This repository is -# public; internal seat names and internal file-share paths do not belong in it. +# public; internal names, machine paths and raw run artifacts do not belong in it. # # Usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE # Exit 0: clean. Exit 1: at least one hit (each printed). Exit 2: usage. @@ -18,8 +18,9 @@ git rev-parse -q --verify "$mb^{commit}" >/dev/null && git rev-parse -q --verify { echo "public-text: unknown commit $mb or $head" >&2; exit 2; } # match: a grep error fails the check instead of reading as "no hit". match() { local rc=0; grep -E -i -- "$pat" "$@" || rc=$?; [ "$rc" -le 1 ] || { echo "public-text: grep failed ($rc)" >&2; exit 2; }; } -pat='(claude|codex)0[0-9]|share[/\]rdma|V:[/\]share|diskstation' -out=$(mktemp); trap 'rm -f "$out"' EXIT +pat='(claude|codex)0[0-9]|share[/\]rdma|V:[/\]share|diskstation|/home/[^/[:space:]]+/|(^|[^[:alnum:]_])pid[[:space:]]*[:=][[:space:]]*[0-9]+|[0-9]+[[:space:]]+cores[[:space:]]+with[[:space:]]+[0-9]+([.][0-9]+)?[[:space:]]*(KB|MB|GB|KiB|MiB|GiB)?[[:space:]]+heap|docs/spec/([^/[:space:]]+/)*recorded-[^/[:space:]]+' +out=$(mktemp); paths=; trap 'rm -f "$out" "$paths"' EXIT +paths=$(mktemp) report() { # report WHERE < matching lines local where=$1 line while IFS= read -r line; do @@ -27,6 +28,17 @@ report() { # report WHERE < matching lines ' "$where" "${line:0:160}" >>"$out" done } +# Raw run artifacts are not public specs, even with scrubbed contents. +# Allow deletions so existing artifacts can be removed. +if ! git diff --name-only -z --no-renames --diff-filter=ACMT "$mb" "$head" -- docs/spec/ >"$paths"; then + echo 'public-text: cannot enumerate artifact paths' >&2 + exit 2 +fi +while IFS= read -r -d '' path; do + if [[ $path =~ ^docs/spec/(.*/)?recorded-[^/]+(/|$) ]]; then + printf '%s\n' "$path" | report "artifact path" + fi +done <"$paths" # Added lines of the diff, with file and line number. git diff --no-color --no-renames -U0 "$mb" "$head" -- . \ ':(exclude).github/scripts/public-text-check.sh' ':(exclude).github/scripts/public-text-check-test.sh' | diff --git a/seaweed-block/.github/scripts/release-binary-assets-test.py b/seaweed-block/.github/scripts/release-binary-assets-test.py new file mode 100644 index 0000000000..38cd2f81d8 --- /dev/null +++ b/seaweed-block/.github/scripts/release-binary-assets-test.py @@ -0,0 +1,92 @@ +"""Exercise release packaging without Docker, GitHub writes or product builds.""" +from pathlib import Path +import json, os, subprocess, tarfile, tempfile, unittest + +HERE = Path(__file__).resolve().parent +REV = "a" * 40 +DIGEST = "example.invalid/block@sha256:" + "b" * 64 + +class ReleaseAssets(unittest.TestCase): + def run_case(self, bad=None, mode="revision", existing=True, tag="v1.1.1", + docker_rm_rc=0, rm_rc=0, publish_rc=0): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp); tools=root/"tools"; tools.mkdir(); image=root/"image"; image.mkdir() + expected={} + for name in ("blockmaster", "blockvolume", "sw-block"): + revision=REV; modified="false"; suffix=""; status=0 + if bad == name: + if mode == "revision": revision="c"*40 + elif mode == "dirty": modified="true" + elif mode == "unknown": revision="unknown" + elif mode == "lab": suffix=" LAB BUILD(example)" + elif mode == "provenance-failure": status=17 + else: self.fail("invalid fixture mode") + data=(f"#!/bin/sh\necho '{name} revision={revision} modified={modified}{suffix}'\nexit {status}\n").encode() + (image/name).write_bytes(data); (image/name).chmod(0o755); expected[name]=data + log=root/"calls.jsonl"; state=root/"release.json"; state.write_text(json.dumps({"prerelease":"-" not in tag})) + common="""#!/usr/bin/env python3 +import json,os,pathlib,shutil,sys +args=sys.argv[1:] +with open(os.environ['CALLS'],'a') as f: f.write(json.dumps([pathlib.Path(sys.argv[0]).name,*args])+chr(10)) +""" + (tools/"docker").write_text(common+""" +if args[0]=='create': print('owned-container') +elif args[0]=='cp': shutil.copy2(pathlib.Path(os.environ['IMAGE'])/args[1].rsplit('/',1)[1],args[2]) +elif args[0]=='rm': sys.exit(int(os.environ['DOCKER_RM_RC'])) +""") + (tools/"rm").write_text(common+""" +if os.environ['RM_RC']!='0': sys.exit(int(os.environ['RM_RC'])) +shutil.rmtree(args[-1]) +""") + (tools/"gh").write_text(common+""" +if args[:2]==['release','view']: sys.exit(0 if os.environ['EXISTING']=='1' else 1) +if args[1] in ('edit','create'): + flag=next((a for a in args if a.startswith('--prerelease')), '--prerelease=false') + pathlib.Path(os.environ['STATE']).write_text(json.dumps({'prerelease':flag in ('--prerelease','--prerelease=true')})) +if args[1] in ('upload','create'): sys.exit(int(os.environ['PUBLISH_RC'])) +""") + for tool in tools.iterdir(): tool.chmod(0o755) + out=root/"assets" + env=dict(os.environ,PATH=str(tools)+os.pathsep+os.environ['PATH'],CALLS=str(log),IMAGE=str(image), + EXISTING=str(int(existing)),STATE=str(state),GITHUB_REPOSITORY='example/block', + DOCKER_RM_RC=str(docker_rm_rc),RM_RC=str(rm_rc),PUBLISH_RC=str(publish_rc)) + result=subprocess.run(['bash',str(HERE/'release-binary-assets.sh'),DIGEST,REV,tag,str(out)], + env=env,capture_output=True,text=True,timeout=15) + calls=[json.loads(line) for line in log.read_text().splitlines()] if log.exists() else [] + primary=(17 if mode=='provenance-failure' else 1) if bad else publish_rc + self.assertEqual(result.returncode,primary or docker_rm_rc or rm_rc,result.stderr) + if bad: + self.assertFalse(any(c[0]=='gh' for c in calls),calls) + self.assertFalse((out/'SHA256SUMS').exists()) + elif not publish_rc: + archive=out/f'sw-block-{tag}-linux-amd64.tar.gz' + with tarfile.open(archive) as tar: + self.assertEqual(set(tar.getnames()),set(expected)) + for name,data in expected.items(): self.assertEqual(tar.extractfile(name).read(),data) + subprocess.run(['sha256sum','--check','SHA256SUMS'],cwd=out,check=True,capture_output=True) + command='upload' if existing else 'create' + self.assertTrue(any(c[:3]==['gh','release',command] for c in calls),calls) + self.assertEqual(json.loads(state.read_text())['prerelease'],'-' in tag) + self.assertEqual(calls[0],['docker','pull',DIGEST]) + self.assertIn(['docker','create',DIGEST],calls) + self.assertEqual(calls[-2],['docker','rm','owned-container']) + self.assertEqual(calls[-1][:4],['rm','-rf','--',calls[-1][-1]]) + if not rm_rc: self.assertFalse(Path(calls[-1][-1]).exists()) + + def test_release_kind_on_create_and_existing(self): + for existing in (False,True): + for tag in ('v1.1.1','v1.1.1-rc1'): + with self.subTest(existing=existing,tag=tag): self.run_case(existing=existing,tag=tag) + + def test_every_binary_refuses_invalid_provenance(self): + for name in ('blockmaster','blockvolume','sw-block'): + for mode in ('revision','dirty','unknown','lab','provenance-failure'): + with self.subTest(binary=name,mode=mode): self.run_case(bad=name,mode=mode) + + def test_cleanup_preserves_primary_error_and_tries_both(self): + self.run_case(publish_rc=37,docker_rm_rc=41,rm_rc=43) + self.run_case(bad='blockmaster',mode='provenance-failure',docker_rm_rc=41,rm_rc=43) + self.run_case(docker_rm_rc=41) + self.run_case(rm_rc=43) + +if __name__=='__main__': unittest.main() diff --git a/seaweed-block/.github/scripts/release-binary-assets.sh b/seaweed-block/.github/scripts/release-binary-assets.sh new file mode 100644 index 0000000000..8c23355c81 --- /dev/null +++ b/seaweed-block/.github/scripts/release-binary-assets.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Copy release executables unchanged from the exact published Linux image. +set -euo pipefail +[ "$#" = 4 ] || { echo "usage: release-binary-assets.sh IMAGE@DIGEST REVISION TAG OUT" >&2; exit 2; } +image=$1; revision=$2; tag=$3; out=$4 +[[ "$image" =~ @sha256:[a-f0-9]{64}$ ]] || { echo "an immutable image digest is required" >&2; exit 2; } +[[ "$revision" =~ ^[a-f0-9]{40}$ ]] || { echo "a full Git revision is required" >&2; exit 2; } +[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "invalid release tag" >&2; exit 2; } +work=$(mktemp -d) +container= +cleanup() { + local status=$? cleanup_status=0 next_status=0 + trap - EXIT + if [ -n "$container" ]; then + docker rm "$container" >/dev/null || cleanup_status=$? + fi + rm -rf -- "${work:?}" || { + next_status=$? + if [ "$cleanup_status" = 0 ]; then cleanup_status=$next_status; fi + } + if [ "$status" = 0 ]; then status=$cleanup_status; fi + exit "$status" +} +trap cleanup EXIT +mkdir -p "$work/bin" +docker pull "$image" +container=$(docker create "$image") +for binary in blockmaster blockvolume sw-block; do + docker cp "$container:/usr/local/bin/$binary" "$work/bin/$binary" + version=$("$work/bin/$binary" -version) + if [ "$version" != "$binary revision=$revision modified=false" ]; then + echo "$binary revision mismatch: expected $revision modified=false, got $version" >&2 + exit 1 + fi +done +mkdir -p "$out" +asset="sw-block-${tag}-linux-amd64.tar.gz" +tar -C "$work/bin" -czf "$out/$asset" blockmaster blockvolume sw-block +(cd "$out" && sha256sum "$asset" >SHA256SUMS) +prerelease=false +if [[ "$tag" == *-* ]]; then prerelease=true; fi +if gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + gh release edit "$tag" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease" + gh release upload "$tag" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber +else + args=(--repo "$GITHUB_REPOSITORY" --verify-tag --title "Seaweed Block $tag" --generate-notes) + args+=(--prerelease="$prerelease") + gh release create "$tag" "$out/$asset" "$out/SHA256SUMS" "${args[@]}" +fi diff --git a/seaweed-block/.github/scripts/run-unit-groups-test.py b/seaweed-block/.github/scripts/run-unit-groups-test.py new file mode 100644 index 0000000000..a54a144188 --- /dev/null +++ b/seaweed-block/.github/scripts/run-unit-groups-test.py @@ -0,0 +1,144 @@ +"""Run fake recorders through the real group executor, without product tests.""" +from pathlib import Path +import json +import os +import subprocess +import time +import sys +import tempfile +import unittest +from unittest.mock import Mock, patch +import importlib.util +import signal + +SCRIPT = Path(__file__).with_name("run-unit-groups.py") +FAKE = r'''import json, os, sys, time +from pathlib import Path +out = Path(sys.argv[1]); group = out.parent.name +root = Path(os.environ["FIXTURE_ROOT"]) +(root / (group + ".started")).write_text("started") +deadline = time.monotonic() + 5 +while not all((root / (g + ".started")).exists() for g in os.environ["EXPECTED_GROUPS"].split()): + if time.monotonic() >= deadline: sys.exit(17) + time.sleep(.01) +flags = sys.argv[2:] +assert "-p=" + ("4" if group == "g3" else "1") in flags +assert "-short" in flags and "-count=1" in flags and "20m" in flags +if sys.platform == "linux": + wal = Path(os.environ["TMPDIR"]) / "v1.bin" + with wal.open("w") as descriptor: + assert os.readlink(f"/proc/self/fd/{descriptor.fileno()}") == str(wal), "fixture WAL descriptor not found" +else: + assert Path(os.environ["TMPDIR"]) == Path(os.environ["TMPDIR"]).resolve(), "TMPDIR must identify the canonical directory" +out.write_text(json.dumps({"Action":"pass", "Package":group}) + "\n") +out.with_suffix(".stderr").write_text("fixture stderr") +(root / (group + ".finished")).write_text("finished") +sys.exit(7 if os.environ.get("FAIL_GROUP") == group else 0) +''' + + +class GroupRunnerTests(unittest.TestCase): + def run_groups(self, fail="", empty=False, alias=False): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); plan = root / "plan"; plan.mkdir() + for group in ("g1", "g2", "g3"): + (plan / (group + ".txt")).write_text("" if empty and group != "g3" else "example/" + group + "\n") + fake = root / "fake.py"; fake.write_text(FAKE) + env = dict(os.environ, FIXTURE_ROOT=str(root), EXPECTED_GROUPS="g3" if empty else "g1 g2 g3", FAIL_GROUP=fail) + scratch = root / "tmp" + if alias: + scratch.mkdir() + link = root / "runner-temp" + link.symlink_to(scratch, target_is_directory=True) + scratch = link + result = subprocess.run([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(scratch), sys.executable, str(fake)], env=env, text=True, capture_output=True, timeout=20) + self.assertEqual(result.returncode, 1 if fail else 0, result.stdout + result.stderr) + expected = ["g3"] if empty else ["g1", "g2", "g3"] + for group in expected: + self.assertTrue((root / (group + ".finished")).exists(), result.stdout + result.stderr) + self.assertTrue((root / "evidence" / group / "go-test.stderr").exists()) + self.assertTrue((root / "tmp" / group).is_dir()) + events = [json.loads(line) for line in (root / "evidence" / "go-test.json").read_text().splitlines()] + self.assertCountEqual([e["Package"] for e in events], expected) + statuses = json.loads((root / "evidence" / "unit-groups.json").read_text()) + self.assertEqual(statuses["groups"]["g2"]["status"], 7 if fail == "g2" else 0) + + @unittest.skipUnless(os.name == "posix", "Linux runner temp symlink control") + def test_runner_temp_symlink_passes_canonical_scratch_paths(self): self.run_groups(alias=True) + + def test_all_groups_overlap_and_keep_separate_events(self): self.run_groups() + def test_failure_fails_job_after_every_group_finishes(self): self.run_groups(fail="g2") + def test_scope_empty_groups_launch_no_recorder(self): self.run_groups(empty=True) + + + def test_cancel_escalates_even_after_group_leader_exits(self): + spec = importlib.util.spec_from_file_location("unit_groups", SCRIPT) + module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module) + leader = Mock(pid=12345) + leader.wait.return_value = 0 + with patch.object(module.signal, "SIGKILL", 9, create=True), patch.object(module.os, "name", "posix"), patch.object(module.os, "killpg", create=True) as killpg, patch.object(module.time, "monotonic", side_effect=[0, 6]): + module.terminate([leader]) + self.assertIn(unittest.mock.call(12345, signal.SIGTERM), killpg.call_args_list) + self.assertIn(unittest.mock.call(12345, 9), killpg.call_args_list) + leader.wait.assert_called() + + @unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control") + def test_cancel_kills_resistant_child_after_recorder_exits(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); plan = root / "plan"; plan.mkdir() + for group in ("g1", "g2", "g3"): + (plan / (group + ".txt")).write_text("example/g1\n" if group == "g1" else "") + child = root / "child.py" + child.write_text("import os,signal,sys,time\nfrom pathlib import Path\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\np=Path(sys.argv[1])\np.with_suffix('.tmp').write_text(str(os.getpid()))\np.with_suffix('.tmp').replace(p)\nwhile True: time.sleep(.1)\n") + fake = root / "recorder.py" + fake.write_text("import subprocess,sys,time\nsubprocess.Popen([sys.executable,sys.argv[1],sys.argv[2]])\nwhile True: time.sleep(.1)\n") + marker = root / "child" + runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake), str(child), str(marker)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + pid = None + try: + deadline = time.monotonic() + 5 + while not marker.exists(): + if time.monotonic() >= deadline: self.fail("resistant child did not start") + time.sleep(.01) + pid = int(marker.read_text()) + runner.terminate() + self.assertEqual(runner.wait(timeout=12), 130) + deadline = time.monotonic() + 2 + while True: + stat = Path(f"/proc/{pid}/stat") + if not stat.exists() or stat.read_text().split(") ", 1)[1].startswith("Z"): break + if time.monotonic() >= deadline: self.fail("resistant child survived cancellation") + time.sleep(.01) + finally: + if pid is not None: + try: os.kill(pid, signal.SIGKILL) + except ProcessLookupError: pass + if runner.poll() is None: runner.kill() + runner.communicate(timeout=5) + + @unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control") + def test_cancel_joins_every_started_group(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); plan = root / "plan"; plan.mkdir() + for group in ("g1", "g2", "g3"): + (plan / (group + ".txt")).write_text("example/" + group + "\n") + fake = root / "held.py" + fake.write_text("import os,sys,time\nfrom pathlib import Path\np=Path(sys.argv[1]).parent\n(p/'process.tmp').write_text(str(os.getpid()))\n(p/'process.tmp').replace(p/'process')\nwhile True: time.sleep(.1)\n") + runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + try: + deadline = time.monotonic() + 5 + markers = [root / "evidence" / g / "process" for g in ("g1", "g2", "g3")] + while not all(p.exists() for p in markers): + if time.monotonic() >= deadline: self.fail("groups did not start") + time.sleep(.01) + children = [int(p.read_text()) for p in markers] + runner.terminate() + self.assertEqual(runner.wait(timeout=10), 130) + for child in children: + with self.assertRaises(ProcessLookupError): os.kill(child, 0) + finally: + if runner.poll() is None: runner.terminate() + runner.communicate(timeout=10) + + +if __name__ == "__main__": unittest.main() diff --git a/seaweed-block/.github/scripts/run-unit-groups.py b/seaweed-block/.github/scripts/run-unit-groups.py new file mode 100644 index 0000000000..b02b4b8391 --- /dev/null +++ b/seaweed-block/.github/scripts/run-unit-groups.py @@ -0,0 +1,123 @@ +"""Run the three default unit groups concurrently on the current runner. + +Usage: run-unit-groups.py PLAN_DIR EVIDENCE_DIR TMP_DIR RECORDER [RECORDER_ARG ...] +The recorder accepts OUTPUT followed by go-test flags and packages. Each group +owns its logs/events; they are combined only after all group processes exit. +""" +from contextlib import ExitStack +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + + +def stop(_signum, _frame): + raise KeyboardInterrupt + + +def terminate(processes): + for process in processes: + try: + if os.name == "posix": os.killpg(process.pid, signal.SIGTERM) + elif process.poll() is None: process.terminate() + except ProcessLookupError: + pass + if os.name == "posix": + # The leader may exit on TERM while its descendants remain in the group. + # Bound the grace period by group lifetime, never by leader lifetime. + deadline = time.monotonic() + 5 + remaining = list(processes) + while remaining and time.monotonic() < deadline: + alive = [] + for process in remaining: + process.poll() # Reap an exited leader without forgetting its PGID. + try: + os.killpg(process.pid, 0) + alive.append(process) + except ProcessLookupError: + pass + remaining = alive + if remaining: time.sleep(.05) + for process in remaining: + try: os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: pass + for process in processes: + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + + +def run(plan, evidence, temp, recorder): + groups = {g: (plan / (g + ".txt")).read_text().splitlines() for g in ("g1", "g2", "g3")} + evidence.mkdir(parents=True, exist_ok=True) + started = time.monotonic() + processes, results, times = {}, {}, {} + with ExitStack() as files: + try: + for group, packages in groups.items(): + results[group] = {"packages": len(packages), "status": 0, "elapsed_seconds": 0} + if not packages: + print(f"{group}: no packages selected by scope", flush=True) + continue + out = evidence / group; out.mkdir(parents=True, exist_ok=True) + scratch = temp / group; scratch.mkdir(parents=True, exist_ok=True) + # /proc/self/fd exposes resolved paths; preserve fixture identity even + # when the runner temp directory is a symlink to its data disk. + scratch = scratch.resolve(strict=True) + log = files.enter_context((out / "console.log").open("w", encoding="utf-8")) + command = recorder + [str(out / "go-test.json"), "-p=" + ("4" if group == "g3" else "1"), "-short", "-count=1", "-timeout", "20m", *packages] + times[group] = time.monotonic() + processes[group] = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, + env=dict(os.environ, TMPDIR=str(scratch)), start_new_session=os.name == "posix") + print(f"{group}: started {len(packages)} packages", flush=True) + remaining = set(processes) + while remaining: + for group in tuple(remaining): + status = processes[group].poll() + if status is not None: + results[group]["status"] = status + results[group]["elapsed_seconds"] = round(time.monotonic() - times[group], 3) + remaining.remove(group) + if remaining: time.sleep(.05) + except BaseException: + signal.signal(signal.SIGTERM, signal.SIG_IGN) + signal.signal(signal.SIGINT, signal.SIG_IGN) + terminate(processes.values()) + raise + for group in processes: + print(f"--- {group} ---", flush=True) + print((evidence / group / "console.log").read_text(errors="replace"), flush=True) + summary = {"elapsed_seconds": round(time.monotonic() - started, 3), "groups": results} + try: + (evidence / "unit-groups.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + with (evidence / "go-test.json").open("ab") as combined: + for group in processes: + events = evidence / group / "go-test.json" + if events.exists(): combined.write(events.read_bytes()) + except OSError as error: + print(f"test evidence unavailable: {error}", file=sys.stderr) + print(json.dumps(summary), flush=True) + return int(any(r["status"] != 0 for r in results.values())) + + +def main(argv): + if len(argv) < 5: + print(__doc__.strip(), file=sys.stderr) + return 2 + signal.signal(signal.SIGTERM, stop) + try: + return run(Path(argv[1]), Path(argv[2]), Path(argv[3]), argv[4:]) + except KeyboardInterrupt: + return 130 + except (OSError, ValueError) as error: + print(f"unit groups: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": sys.exit(main(sys.argv)) diff --git a/seaweed-block/.github/scripts/unit-test-shards-test.py b/seaweed-block/.github/scripts/unit-test-shards-test.py new file mode 100644 index 0000000000..df49419e7c --- /dev/null +++ b/seaweed-block/.github/scripts/unit-test-shards-test.py @@ -0,0 +1,52 @@ +"""Exact coverage before scope selection; old heavy-package rules afterward.""" +import importlib.util +from pathlib import Path +import unittest + +spec = importlib.util.spec_from_file_location("planner", Path(__file__).with_name("unit-test-shards.py")) +planner = importlib.util.module_from_spec(spec) +spec.loader.exec_module(planner) +MODULE = "example.invalid/product" +HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority") + + +class UnitShardTests(unittest.TestCase): + def setUp(self): + self.packages = [MODULE + "/" + p for p in (*HEAVY, "cmd/sw-block", "core/frontend/chunkstore", "internal/newpackage", "core/storage/child")] + self.groups = planner.partition(MODULE, self.packages) + + def test_exact_cover_and_stable_order(self): + flat = [p for group in self.groups.values() for p in group] + self.assertCountEqual(flat, self.packages) + self.assertEqual(len(flat), len(set(flat))) + self.assertEqual(self.groups, planner.partition(MODULE, list(reversed(self.packages)))) + self.assertEqual(self.groups["g1"], [MODULE + "/core/storage"]) + self.assertEqual(self.groups["g2"], [MODULE + "/" + p for p in HEAVY[1:]]) + self.assertIn(MODULE + "/internal/newpackage", self.groups["g3"]) + self.assertIn(MODULE + "/core/storage/child", self.groups["g3"]) + + def test_existing_heavy_scope_on_main_train_and_prs(self): + all_changed = [p + "/changed.go" for p in HEAVY] + for event, ref in (("push", ""), ("pull_request", "train/next")): + selected = planner.select(MODULE, self.groups, event, ref, all_changed) + self.assertEqual(selected["g1"], []) + self.assertEqual(selected["g2"], []) + self.assertEqual(selected["g3"], self.groups["g3"]) + self.assertEqual(planner.select(MODULE, self.groups, "pull_request", "fix/x", all_changed), self.groups) + for path in HEAVY: + selected = planner.select(MODULE, self.groups, "pull_request", "fix/x", [path + "/x.go"]) + heavy = selected["g1"] + selected["g2"] + self.assertEqual(heavy, [MODULE + "/" + path]) + nested = planner.select(MODULE, self.groups, "pull_request", "fix/x", ["core/storage/child/x.go", "core/storage/"]) + self.assertEqual(nested["g1"], []) + self.assertEqual(nested["g2"], []) + self.assertEqual(nested["g3"], self.groups["g3"]) + + def test_invalid_inventory_is_refused(self): + for packages in ([], self.packages + [self.packages[0]], self.packages[1:], self.packages + ["other/pkg"]): + with self.subTest(packages=packages), self.assertRaises(ValueError): + planner.partition(MODULE, packages) + + +if __name__ == "__main__": + unittest.main() diff --git a/seaweed-block/.github/scripts/unit-test-shards.py b/seaweed-block/.github/scripts/unit-test-shards.py new file mode 100644 index 0000000000..badb9b8791 --- /dev/null +++ b/seaweed-block/.github/scripts/unit-test-shards.py @@ -0,0 +1,55 @@ +"""Plan the default unit groups from the full go-list inventory. + +Usage: go list ./... | python3 unit-test-shards.py MODULE OUT_DIR EVENT HEAD_REF CHANGED_FILE +The complete partition covers every package exactly once. Existing scope rules +then select heavy packages only on ordinary PRs that touch their direct files. +""" +from pathlib import Path +import sys + +HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority") + + +def partition(module, packages): + if not module or any(c.isspace() for c in module): + raise ValueError("expected one module path") + if not packages or len(packages) != len(set(packages)): + raise ValueError("empty package list or duplicate package") + if any(p != module and not p.startswith(module + "/") for p in packages): + raise ValueError("package outside the selected module") + heavy = [module + "/" + p for p in HEAVY] + if not set(heavy) <= set(packages): + raise ValueError("required heavy packages missing from go list") + return {"g1": heavy[:1], "g2": heavy[1:], "g3": sorted(set(packages) - set(heavy))} + + +def select(module, groups, event, head_ref, changed): + selected = set() + if event != "push" and not head_ref.startswith("train/"): + for p in HEAVY: + if any(f.startswith(p + "/") and f[len(p) + 1:] and "/" not in f[len(p) + 1:] for f in changed): + selected.add(module + "/" + p) + return {name: [p for p in packages if name == "g3" or p in selected] + for name, packages in groups.items()} + + +def main(argv): + if len(argv) != 6: + print(__doc__.strip(), file=sys.stderr) + return 2 + try: + groups = partition(argv[1], sys.stdin.read().split()) + groups = select(argv[1], groups, argv[3], argv[4], Path(argv[5]).read_text().splitlines()) + out = Path(argv[2]) + out.mkdir(parents=True, exist_ok=True) + for name, packages in groups.items(): + (out / (name + ".txt")).write_text("".join(p + "\n" for p in packages), encoding="utf-8") + print(f"{name}: {len(packages)} packages") + except (OSError, ValueError) as error: + print(f"unit-test-shards: {error}", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/seaweed-block/.github/workflows/known-bugs.yml b/seaweed-block/.github/workflows/known-bugs.yml index 0d3e03c6ec..1bed19297e 100644 --- a/seaweed-block/.github/workflows/known-bugs.yml +++ b/seaweed-block/.github/workflows/known-bugs.yml @@ -42,25 +42,12 @@ jobs: go-version-file: go.mod cache: false + - name: Known-bug verdict controls + run: bash .github/scripts/known-bugs-test.sh + - name: Each reproduction still fails run: | - set -u - ok=1 - while read -r issue pkg test; do - [ -n "$issue" ] || continue - if go test -count=1 -run "^${test}\$" "$pkg" > "out-${test}.txt" 2>&1; then - echo "::error::${test} (${pkg}) now PASSES: ${issue} looks fixed, remove its skip" - ok=0 - elif grep -q "^--- FAIL: ${test} " "out-${test}.txt"; then - echo "${test} (${issue}) still fails, as expected" - else - echo "::error::${test} (${pkg}) did not run or failed to build:"; tail -20 "out-${test}.txt" - ok=0 - fi - done <<'LIST' + bash .github/scripts/known-bugs.sh <<'LIST' #186 ./cmd/blockmaster/ TestChartOptInLoopbackFlagIsAcceptedByBlockmaster #187 ./cmd/blockmaster/ TestChartDefaultAuthorityStateSurvivesPodReplacement - #188 ./core/ops/ TestDeleteSafety_UntimedCleanupCannotProveFreshness - #189 ./core/storage/ TestMultiBlockRecordsRequireDistinctOnDiskImplVersion LIST - [ "$ok" = 1 ] diff --git a/seaweed-block/.github/workflows/post-merge-review.yml b/seaweed-block/.github/workflows/post-merge-review.yml index de5bc638ec..85237e42bc 100644 --- a/seaweed-block/.github/workflows/post-merge-review.yml +++ b/seaweed-block/.github/workflows/post-merge-review.yml @@ -4,11 +4,10 @@ name: post-merge-review paths # every changed file is allowed by .github/post-merge-review-allow.txt. # This check fails such a PR otherwise; without the label it passes. # -# pull_request_target: the workflow, the allow list and the script all come -# from the base branch, so a PR cannot change its own check. The PR's code is -# never checked out or run: only its commit is fetched, for the file list. +# A read-only pull_request run executes validators and the allow list from +# a separate base-commit checkout. The PR head is inspected only as objects. on: - pull_request_target: + pull_request: # edited: a retarget changes the base, and with it the diff. types: [opened, synchronize, reopened, labeled, unlabeled, edited] @@ -22,11 +21,7 @@ concurrency: jobs: paths: name: post-merge-review paths - # GitHub-hosted: on the self-hosted runners this job ended in 'Set up - # job' with no log on every runner (2026-11-29), while spec trace, on the - # same runners, passes. Unlabelled PRs only echo here, so the hosted - # queue costs little; the merge gate does not wait for it unless the PR - # is labelled. + # Forks and same-repository PRs use the same disposable runner. runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -39,10 +34,12 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.base.sha }} + path: trusted-base fetch-depth: 0 persist-credentials: false - name: Check changed paths + working-directory: trusted-base if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }} env: BASE: ${{ github.event.pull_request.base.sha }} diff --git a/seaweed-block/.github/workflows/publish-alpha-images.yml b/seaweed-block/.github/workflows/publish-alpha-images.yml index 0a1564e5ca..5ab4462804 100644 --- a/seaweed-block/.github/workflows/publish-alpha-images.yml +++ b/seaweed-block/.github/workflows/publish-alpha-images.yml @@ -7,7 +7,7 @@ on: - "v*" permissions: - contents: read + contents: write packages: write env: @@ -72,11 +72,16 @@ jobs: echo "EOF" } >> "$GITHUB_OUTPUT" + - name: Release asset controls + run: python3 -I .github/scripts/release-binary-assets-test.py + - name: Build and push block image + id: block uses: docker/build-push-action@v6 with: context: . file: deploy/k8s/g15b/Dockerfile.sw-block + platforms: linux/amd64 push: true tags: ${{ steps.tags.outputs.block_tags }} @@ -87,3 +92,13 @@ jobs: file: deploy/k8s/g15b/Dockerfile.blockcsi push: true tags: ${{ steps.tags.outputs.csi_tags }} + + - name: Attach matching Linux binaries to the release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BLOCK_DIGEST: ${{ steps.block.outputs.digest }} + run: | + set -euo pipefail + revision=$(git rev-parse HEAD) + bash .github/scripts/release-binary-assets.sh "${BLOCK_IMAGE}@${BLOCK_DIGEST}" \ + "$revision" "$GITHUB_REF_NAME" "$RUNNER_TEMP/block-release" diff --git a/seaweed-block/.github/workflows/spec-trace.yml b/seaweed-block/.github/workflows/spec-trace.yml index 25fe922ae8..56c0696730 100644 --- a/seaweed-block/.github/workflows/spec-trace.yml +++ b/seaweed-block/.github/workflows/spec-trace.yml @@ -3,12 +3,11 @@ name: spec trace # Every PR description carries the spec trace (see the PR template); this # check fails a PR whose description does not. # -# pull_request_target: the workflow and the script come from the base branch, -# so a PR cannot change its own check. The PR's code is never checked out or -# run: only its commit is fetched, for the file list. The description is read -# from the event through an environment variable, never interpolated. +# A read-only pull_request run checks out the event's base commit into its +# own directory. Validators and data come from that checkout; the PR head +# is fetched only as Git objects. The body is passed as data, not shell code. on: - pull_request_target: + pull_request: # edited: the check reads the description and the base. types: [opened, synchronize, reopened, edited] @@ -22,33 +21,27 @@ concurrency: jobs: trace: name: spec trace - # A PR from a branch of this repository runs on the team's self-hosted - # runners: the GitHub-hosted queue is shared with the whole organization, - # where this five-minute check waited behind other repositories' jobs. - # pull_request_target starts for any PR without approval, so a PR from a - # fork keeps a throw-away GitHub-hosted machine. No PR code is checked - # out or run on either. - runs-on: ${{ github.event.pull_request.head.repo.full_name == github.repository && 'tp04-seaweed-block' || 'ubuntu-latest' }} + # Both same-repository and fork PRs use disposable hosted runners. + runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Checkout base uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - # github.sha is the tip of the base branch when the event fires; the - # PR's base.sha can predate this workflow's own scripts. - ref: ${{ github.sha }} + ref: ${{ github.event.pull_request.base.sha }} + path: trusted-base fetch-depth: 0 persist-credentials: false - # spec-trace-check.sh builds the trusted sametokens.go; a self-hosted - # runner has no Go on its PATH unless the job sets it up. + # The token-comparison helper is built from the base checkout too. - name: Set up Go uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 with: - go-version-file: go.mod + go-version-file: trusted-base/go.mod cache: false - name: Check spec trace + working-directory: trusted-base env: BASE: ${{ github.event.pull_request.base.sha }} HEAD: ${{ github.event.pull_request.head.sha }} @@ -78,6 +71,7 @@ jobs: bash .github/scripts/public-text-check.sh "$mb" "$HEAD" title.txt body.txt - name: Invariants ledger anchors (report only) + working-directory: trusted-base # Every code and test anchor of docs/design/invariants.md must exist at # the PR's commit (git objects only; nothing from the PR is run). It # reports and does not fail the check while the known imprecise diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml index 2fc36d0531..4f5b6a821a 100644 --- a/seaweed-block/.github/workflows/test.yml +++ b/seaweed-block/.github/workflows/test.yml @@ -40,8 +40,11 @@ jobs: # it is the merge gate, and the organization's shared GitHub-hosted queue held # it 30-55 minutes before it started. A PR from a fork never runs there. runs-on: ${{ (github.event_name == 'push' || (github.event.pull_request.head.repo.full_name == github.repository)) && 'tp04-seaweed-block' || 'ubuntu-latest' }} + # unit: a PR touching core/storage and core/frontend/durable adds both packages to the + # default step (measured 32 min on the self-hosted runner) before the v3-tagged step + # (measured 7-8 min), so 40 min cancelled the job; 60 min is about 1.5x that sum. # process: 44 tests in 4 parallel shards of about 13 min each (55 min in sequence). - timeout-minutes: ${{ matrix.suite == 'unit' && 40 || 90 }} + timeout-minutes: ${{ matrix.suite == 'unit' && 60 || 90 }} env: # Pure-Go build: no package in the default build needs cgo, and the # hosted runner should not depend on a C toolchain being present. @@ -140,6 +143,8 @@ jobs: set -euo pipefail bash .github/scripts/lab-tag-check.sh . bash .github/scripts/lab-tag-check-test.sh + python3 -I .github/scripts/release-binary-assets-test.py + python3 -I .github/scripts/pr-gate-base-test.py for tags in swblock_lab_bigvol swblock_v11_format swblock_lab_bigvol,swblock_v11_format; do go vet -tags "$tags" ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/ bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'Lab|Headroom|Revision|LegacyBound' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ @@ -148,29 +153,30 @@ jobs: - name: Test default configuration if: matrix.suite == 'unit' - # The runner disk is shared, so the long, disk-heavy, timing-sensitive - # packages do not run here on main or on train PRs: every train runs the - # whole suite (both configurations) on a separate test VM before it - # merges, and main moves only by those trains. A PR runs the light set - # plus every heavy package its own diff touches. + # Preserve the existing scope: main/train omit the four heavy packages; + # ordinary PRs add each only when its direct package files are touched. + # Three subprocesses share this ONE runner: storage, durable plus touched + # master/authority, and the remaining selected packages at -p=4. env: EVENT: ${{ github.event_name }} HEAD_REF: ${{ github.head_ref }} run: | set -euo pipefail - pkgs=$(go list ./... | grep -vE '/core/(storage|frontend/durable|host/master|authority)$') + python3 -I .github/scripts/unit-test-shards-test.py + python3 -I .github/scripts/run-unit-groups-test.py + plan="$RUNNER_TEMP/unit-groups" + mkdir -p "$plan" + go list ./... >"$plan/all.txt" + mod=$(go list -m) + # Main pushes need no changed-path list; a shallow initial push may + # have no parent. Ordinary PRs use the merge commit's base parent. + : >"$plan/changed.txt" if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then - mod=$(go list -m) - changed=$(git diff --name-only HEAD^1 HEAD) - for p in core/storage core/frontend/durable core/host/master core/authority; do - if printf '%s\n' "$changed" | grep -qE "^$p/[^/]+$"; then - pkgs="$pkgs $mod/$p" - fi - done + git diff --name-only HEAD^1 HEAD >"$plan/changed.txt" fi - # 20m per package: core/storage alone took 602 s on tp04 on main - # (2026-11-22), past the old 10m, so any PR touching it failed. - bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -p=1 -short -count=1 -timeout 20m $pkgs + python3 -I .github/scripts/unit-test-shards.py "$mod" "$plan" "$EVENT" "$HEAD_REF" "$plan/changed.txt" <"$plan/all.txt" + python3 -I .github/scripts/run-unit-groups.py "$plan" "$CI_EVIDENCE_DIR" "$RUNNER_TEMP/unit-group-tmp" \ + bash .github/scripts/record-go-test.sh - name: Format v3 tagged tests if: matrix.suite == 'unit' diff --git a/seaweed-block/README.md b/seaweed-block/README.md index ba25e41857..a5244b3dcd 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -1,308 +1,231 @@ # Seaweed Block -[![tag](https://img.shields.io/github/v/tag/seaweedfs/seaweed-block?sort=semver&label=release)](docs/releases/v1.0.0.md) +[![tag](https://img.shields.io/github/v/tag/seaweedfs/seaweed-block?sort=semver&label=release)](docs/releases/README.md) [![CI](https://github.com/seaweedfs/seaweed-block/actions/workflows/test.yml/badge.svg)](https://github.com/seaweedfs/seaweed-block/actions/workflows/test.yml) [![Go](https://img.shields.io/github/go-mod/go-version/seaweedfs/seaweed-block)](go.mod) [![License](https://img.shields.io/github/license/seaweedfs/seaweed-block)](LICENSE) -**Block storage for AI agent workspaces at local-disk speed, with snapshots, restore and moves backed by your own -[SeaweedFS](https://github.com/seaweedfs/seaweedfs).** Each sandbox or microVM gets a plain virtio block disk. Writes -and `fsync` complete on the host's local disk; cuts copy the changed data to SeaweedFS in the background. Losing the -host loses what was written since the last successful cut: normally about a day with the default schedule (one -snapshot a day), not a guaranteed bound; `--chunk-capture-interval` (5 minutes or more) cuts more often. The same core serves Kubernetes block volumes (alpha). +**Local-first block storage for AI agents.** + +*Run locally. Persist incrementally. Resume anywhere.* + +Seaweed Block gives each agent sandbox or microVM its own block disk on the host's local storage, and checkpoints the +changed data to your own [SeaweedFS](https://github.com/seaweedfs/seaweedfs). Writes and `fsync` complete locally; +checkpoints, named snapshots and restores carry the workspace's state beyond that host. High density per host is a +design goal; see [Vision](#vision). + +**[Quick start](#quick-start)** · [How it works](#how-it-works) · [Project status](#project-status) · +[Documentation](#documentation)

- Seaweed Block. Write path: an agent sandbox or microVM writes over NVMe/TCP or iSCSI to blockvolume, which completes the write and fsync on its local WAL and acknowledges; a write does not wait on SeaweedFS, except that a restored volume fetches each chunk from its snapshot once, on its first read or write. Background path: a cut (by default one scheduled snapshot a day; periodic cuts are optional) uploads only the changed 4 MiB chunks to your SeaweedFS, then updates the HEAD root with a conditional update on generation and epoch. blockmaster issues epochs and leases. Snapshots name a root and share chunks; a restore reads the snapshot's chunks on first use; a move hands the volume to another host at a higher epoch, and a stale holder's update is refused. + The Seaweed Block lifecycle. Run locally: agent VMs on host A write to the host's local disk, where writes and fsync complete with no network round trip. Persist incrementally: checkpoints send only the changed 4 MiB chunks to your SeaweedFS in the background, and named snapshots share those chunks. Resume anywhere: host B restores a snapshot into a new volume, or takes a volume over in a planned move; it serves at once and fetches chunks on first read. Normal I/O to locally available data stays on the host.

-**Branches.** `main` is v1.1 in development: it is not a release, and the store format it writes may change -before v1.1. Do not run it for data you keep. v1.0.x releases ship from the `release-1.0` branch. +## Why not just use... -## Install +| | Local disk | Conventional network block storage | Seaweed Block | +|---|---|---|---| +| Where writes and `fsync` complete | On the host | Typically on a remote storage service | On the host | +| Network in the I/O path | No | Typically, for every read and write | No, for data on the host; a restored or moved volume fetches chunks on first read | +| If the host is lost | The state is lost with it | The volume typically survives | The state survives up to its last confirmed checkpoint | +| Resume on another host | Copy the data yourself | Typically, detach the volume and attach it there | Move the volume there, or restore a snapshot into a new volume there (placed by the cluster spec) | +| What persistence sends | Nothing | Typically every write, as it happens | Only the whole 4 MiB chunks that changed, at each checkpoint | -The binaries are `blockmaster`, `blockvolume` and the `sw-block` CLI. The commands on this page are for v1.0.0. -**Option 1:** copy them from the v1.0.0 image, -`ghcr.io/seaweedfs/seaweed-block:v1.0.0` (index digest -`sha256:648980beb519a086349d44367e9d19ba6ae94b8939456ae3eb7b7bb5e4b3b28b`): +

+ Three ways to give an agent VM a disk. Local disk: all I/O stays on the host, fast, but the state is tied to that host. Network block storage: I/O typically crosses the network to a remote volume, so the state outlives the host, but the network is in the I/O path. Seaweed Block: normal I/O to locally available data stays on the host's local disk, and changed chunks go to your SeaweedFS in the background, so it runs at near-local speed and the state outlives the host up to its last checkpoint. +

-```bash -docker create --name swb-extract ghcr.io/seaweedfs/seaweed-block:v1.0.0 -for b in blockmaster blockvolume sw-block; do docker cp swb-extract:/usr/local/bin/$b .; done -docker rm swb-extract && ./blockvolume --version -``` +## Run, checkpoint, snapshot, restore -**Option 2:** build from the tag `v1.0.0` (the Go version in `go.mod`): -```bash -git clone --branch v1.0.0 https://github.com/seaweedfs/seaweed-block && cd seaweed-block -for b in blockmaster blockvolume sw-block; do go build -o $b ./cmd/$b; done -``` +1. **Run.** Start a volume on the host where the agent runs. The guest attaches it over NVMe/TCP or iSCSI, formats it + with its own file system, and works at near-local speed. +2. **Checkpoint.** The changed chunks go to your SeaweedFS: on demand (`sw-block ops chunk cut`), periodically (the + holder's `--chunk-capture-interval`, 5 minutes or more), with the default daily snapshot, and when you stop the + volume (`sw-block volume stop`). +3. **Snapshot.** `sw-block volume backup --name ` (or `sw-block ops chunk snapshot`) names a point in + time. Snapshots share chunks with each other. +4. **Restore.** A restore makes a new volume from a snapshot, on the host that its placement in the cluster spec + names. It serves at once and fetches chunks on first read. -**Option 3:** Helm, see the [Kubernetes quick start](#quick-start-kubernetes-alpha). -Services: [standalone deployment](docs/standalone-deployment.md). Operator guide (supported setup, sizing, recovery point, host loss, limits): [operator guide](docs/operator-guide.md). +The commands and what each needs: [snapshots, restore and verification](docs/operations-manual.md#5-snapshots-restore-and-verification). -## Try it +## Features -The [first volume check](docs/standalone-deployment.md#first-volume-read-only-check) -starts `blockmaster` and one `blockvolume`, attaches a 256 MiB volume over -NVMe/TCP on loopback, shows the device and its status, and stops. It does -not format or write the attached device; it only creates local backing files -and logs. It needs Linux, bash, `nvme-cli`, `sudo` and the binaries -above. To format and write, use the [write test](docs/standalone-deployment.md#write-test-scratch-host-only) (scratch host only). +- **Near-local speed for agent workloads.** Writes and `fsync` complete on the host's disk, with no network round + trip, and every guest `fsync` reaches it. +- **Any file system, unchanged tools.** The guest sees a plain block device, so `git`, `npm` and builds run as on a + local disk. +- **Incremental checkpoints.** Only the changed 4 MiB chunks upload: on demand, periodically, or with the daily + snapshot. +- **Snapshots and instant restore.** Named snapshots share chunks, and a restored volume serves before its data + arrives. +- **Safe moves between hosts.** Epochs and leases fence the old host, so a stale host cannot publish over the + workspace's state. +- **Self-hosted and open source.** Your data stays in your SeaweedFS. Apache-2.0, written in Go. -### `sw-block mini` +## Use cases -A trial on a scratch host, not for data you keep. One command starts a single-host -trial on loopback, with SeaweedFS's `weed mini` as the chunk store (run against SeaweedFS 4.53). Build all three -binaries from the same checkout and run the one you built, so that `mini` finds its matching `blockmaster` and -`blockvolume` next to it: +- **AI coding agents** whose repositories, dependencies and build caches must outlive the sandbox. +- **Agent sandboxes and microVM platforms** that give each sandbox its own disk. +- **Long-running agents** that stop, resume and move between hosts. +- **Also:** Kubernetes block volumes through the CSI driver (alpha), and replicated volumes for workloads that need + synchronous copies (`sync-quorum`, `sync-all`; preview). -```bash -git clone https://github.com/seaweedfs/seaweed-block && cd seaweed-block -for b in blockmaster blockvolume sw-block; do go build -o $b ./cmd/$b; done -./sw-block mini --dir ./swb-mini --weed /path/to/weed -``` +## One engine, two durability profiles -It starts `weed mini`, `blockmaster` and one `blockvolume` (volume `v1`, 256 MiB, `walstore-chunk` with its chunk -control endpoint). Snapshots of `v1` work at once. A restore into a new volume is not possible inside a `mini` trial -yet: `mini`'s blockmaster is its own child and `mini` stops everything when a child exits, and that blockmaster -refuses a volume that is not in its one-volume cluster spec while its product loop is off. To restore today, use the -standalone setup -([restoring a snapshot](docs/standalone-deployment.md#restoring-a-snapshot-into-a-new-volume)). -It prints every command it runs and never runs `sudo`: it prints the `nvme connect` command that attaches `v1`, and -the status, check and snapshot commands. Before you stop it with Ctrl-C, unmount `v1` and run the -`sudo nvme disconnect` it printed. If no `weed` is found on `PATH` and `--weed` is not given, it starts the local -engine only, with no snapshots and a banner saying so; a `--weed` path that does not exist is refused. More in -[standalone deployment](docs/standalone-deployment.md#quick-start-sw-block-mini). +Agent workspaces are the focus. The same block engine (write-ahead log and extent, NVMe/TCP and iSCSI frontends, +blockmaster's epochs) also runs replicated volumes, for workloads that need copies on other hosts before `fsync` +completes (`sync-quorum`, `sync-all`). -## Why Seaweed Block +| | Checkpointed volume | Replicated volume (preview) | +|---|---|---| +| Built for | Agent workspaces: many independent, portable disks | Workloads that need online copies on other hosts | +| When `fsync` completes | Once the data is on the host's local disk | With `sync-quorum` or `sync-all`, once a quorum or every replica has it (the default `best-effort` waits for none) | +| After a host is lost | An operator's forced move continues from the last checkpoint in SeaweedFS | With `--cluster-spec` and the lifecycle loop enabled (`--lifecycle-product-loop-interval`, off by default), blockmaster fails a `sync-quorum` or `sync-all` volume over to a replica when its fencing round decides; the operator then starts the guest on the new primary's host (no path failover in the guest). `best-effort` is not failed over automatically; the operator's forced failover may lose the last acknowledged writes | +| Snapshots, restore, moves | Yes | Not yet: the two profiles cannot be combined in v1.1.x | +| Status in v1.1.x | Supported | Preview, with [known limits](docs/releases/replicated-volumes-preview.md) | -- **Close to local-disk speed for agent work.** In a pre-release run on the `walstore` engine (the local engine the - released chunk path builds on), `npm ci`, `git clone` and untar ran within 0-4% of a local disk for the operation - itself. With the final file-system flush included on both sides, they were 11-23% slower than the local disk, and - untar of 5,000 small files took about 2.2 times as long. On the released path, `fsync` costs about - 1.3 times local ([measured results](#measured-results), [how each was measured](docs/workspace-measurements.md)). -- **`fsync` is durable on the host that serves the volume.** Every guest `fsync` reaches the host's disk; no write - cache is turned off to get the speed (a gate counts flushes against backend syncs, with an unsafe-cache control). - In fault injection on the release candidate (process kills and a store pause on one host; not a power-loss test), - 0 acknowledged writes were lost across 253 judged; the same runs failed other operation checks, listed with the - record. If the host itself is lost, the volume comes back from its last cut - ([records](docs/workspace-measurements.md)). -- **Snapshots in your object store.** A cut uploads only the changed 4 MiB chunks. A snapshot names a root of about - 2 KB and shares its chunks; a restore makes a new volume that reads them on first use - ([agent workspace design](docs/design/agent-workspace-design.md)). -- **Safe moves between hosts.** One blockmaster issues epochs and leases, and a holder admits I/O only while its own - lease is current; run exactly one blockmaster per cluster. Separately, every HEAD update is conditional on - `{gen, epoch}`, so the store refuses a stale holder's publish even before that holder notices it was replaced - ([volume lifecycle](docs/volume-lifecycle.md), [TLA+ specifications](docs/spec/README.md)). -- **Self-hosted.** Go, Apache-2.0, on your own hosts and your own SeaweedFS. -- **Against an early FUSE prototype on the same host** (host-side, built on the SeaweedFS filer; not a released - product), in the same pre-release run, untar, `npm ci` and `git clone` were 4 to 36 times faster with the final - flush included; `fsync`-bound work took the same time ([record](docs/workspace-measurements.md)). +The two biggest limits of the preview: a replica that falls behind the retained log needs a manual re-add, and a +primary cut off from blockmaster is not stopped by a lease, so it may serve stale reads and, under `best-effort`, +accept writes that are later lost. Do not use replicated volumes for data you cannot lose. -## Measured results +A workload chooses the durability it needs: a checkpointed workspace does not pay for synchronous replicas, and a +replicated volume does not wait for checkpoints. + +## Performance Time on Seaweed Block relative to a local disk, over NVMe/TCP loopback: npm ci 1.00, git clone 1.02, untar 100,000 files 1.04, cold find and stat 0.97, 2,000 create plus write plus fsync 1.52, guest fsync median 1.31. -Lab runs, median of 3; not SLOs. Workloads: Firecracker microVMs (4 vCPU, 4 GiB) on one bare-metal host over -NVMe/TCP loopback, against a local file-backed disk. The first four rows come from a pre-release build on the -`walstore` engine and time the operation itself. With the final `syncfs` flush included on both sides (recorded -separately), the first three are 11-23% slower than the local disk (see the measurements page). The two `fsync` rows come from a later run of the released path -(`walstore-chunk`) on the same host, after the group-commit fix -([#173](https://github.com/seaweedfs/seaweed-block/pull/173)). The chart is drawn from -[measured-results.csv](docs/assets/measured-results.csv) by `docs/assets/readme-chart.py`. +Metadata-heavy agent work runs at local-disk speed, timing the operation itself (with the guest's final `syncfs`, 11-23% +slower); `fsync` latency and `fsync`-bound work are 1.3 to 1.5 times local. These are lab runs of pre-release builds +(the first four rows on the `walstore` engine, the last two on `walstore-chunk`) on Firecracker microVMs over NVMe/TCP +loopback, median of 3: measurements, not SLOs. Every number and how it was measured, with the build where it was +recorded: [workspace measurements](docs/workspace-measurements.md). -| Measurement | Seaweed Block | Local disk | -|---|---|---| -| `npm ci` (617 packages, offline) / `git clone` (Go 1.23, local) | 2.14 s / 7.10 s | 2.14 s / 6.99 s | -| Untar 100,000 files / cold `find` + `stat` over them | 1.10 s / 0.32 s | 1.06 s / 0.33 s | -| 2,000 × create + write + `fsync` | 9.27 s | 6.11 s | -| Guest `fsync` median, fio 4 KiB random write, one at a time | 3.59 ms | 2.74 ms | -| Snapshot of a 10 GiB volume (2,560 chunks) | 0.18 ms | | -| Two-host lifecycle (pre-release): create, snapshot, fork, move, stale holder, delete, GC | 35 of 35 checks | | +## Quick start -The snapshot row is a host-side proxy without network latency, guest `fsync` or the block frontend. The two-host -lifecycle row is a pre-release run that included fork (removed from this release) and the earlier GC. The remaining -cost is `fsync`: a median of 3.59 ms against 2.74 ms local over NVMe/TCP loopback. The ublk frontend measured -3.23 ms in the same run; ublk is not among v1.0.0's supported frontends (NVMe/TCP and iSCSI). -[Workspace measurements](docs/workspace-measurements.md) has every number, the FUSE comparison and how each was -measured. - -## Status and limits - -- **Recovery point:** a lost host loses what was written since the volume's last successful snapshot or cut: - normally about a day with the default schedule (one scheduled snapshot a day, which is attempted, not - guaranteed). `--chunk-capture-interval` - (5 minutes or more) adds periodic cuts and shortens it. -- **v1.0.0 supports** the single-replica volume (`--durable-impl walstore-chunk`), backed up to SeaweedFS with - snapshots, restore, moves and volume delete. New volumes are at most 256 GiB. See the - [release note](docs/releases/v1.0.0.md) and its [known limits](docs/releases/v1.0.0.md#known-limits). -- **Replicated volumes** are a preview ([replicated volumes preview](docs/releases/replicated-volumes-preview.md)). -- **Kubernetes** is an alpha, for supported lab clusters ([Kubernetes status](docs/kubernetes-status.md)). - -## Direction - -Seaweed Block is block storage for AI agent workspaces: one local-speed disk per sandbox or microVM, with its history -(snapshots, restores, moves) in your own SeaweedFS. The same core serves Kubernetes block volumes (alpha). - -- **Works today (v1.0.1):** single-replica volumes up to 256 GiB over NVMe/TCP or iSCSI; scheduled and manual - snapshots; restore into a new volume; a planned hand-over to another machine (run across two machines on the - release candidate); a forced move after a host is lost, from the volume's last cut (tested with two server - identities on one machine); volume delete. Each is a documented sequence of `sw-block ops` commands and systemd - units. v1.0.1 adds `sw-block mini`, a single-host trial; whole-job volume commands (`sw-block volume start`, - `stop`, `backup`, `restore`); `sw-block shell` for inspection, with `cluster.check` and a troubleshooting page; a - log bundle without secrets; and a working `ops chunk verify` (see the [v1.0.1 note](docs/releases/v1.0.1.md)). -- **After that, planned:** volumes up to 1 TiB (v1.1); replicated volumes beyond the preview; export of a snapshot to another object store, and - import from it; `volume fork` and `volume move` commands. - -## Agent workspace disks: chunk lifecycle - -The workspace path runs `blockvolume` with `--durable-impl=walstore-chunk`, -`--chunk-filer ` and `--chunk-control-endpoint`, against a SeaweedFS -cluster. The `sw-block ops chunk` commands drive the lifecycle: +A trial on a disposable Linux host, not for data you keep. You need `nvme-cli`, `sudo`, and SeaweedFS's `weed` +binary, tested with SeaweedFS 4.53 (from its [release page](https://github.com/seaweedfs/seaweedfs/releases/tag/4.53), +asset `linux_amd64.tar.gz`, which holds the one `weed` binary). ```bash -sw-block ops chunk cut --volume v1 --status-addr # publish changed chunks, advance HEAD -sw-block ops chunk snapshot --volume v1 --status-addr --name s1 # name a snapshot -sw-block ops chunk snapshots --master --volume v1 --chunk-filer # list snapshots -sw-block ops chunk restore --master --chunk-filer --source v1 --snapshot s1 --target v3 # new volume from a snapshot -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 v3 --chunk-filer --master --request-id del-v3 +TAG=v1.1.1 +curl -fsSLO https://github.com/seaweedfs/seaweed-block/releases/download/$TAG/sw-block-$TAG-linux-amd64.tar.gz +curl -fsSLO https://github.com/seaweedfs/seaweed-block/releases/download/$TAG/SHA256SUMS +sha256sum -c --ignore-missing SHA256SUMS && tar -xzf sw-block-$TAG-linux-amd64.tar.gz +export PATH="$PWD:$PATH" # so the sw-block commands that mini prints run as shown +./blockvolume --version # must print the tag's commit +# blockvolume keeps one lock per volume here, so only one live process serves a volume on a host: +sudo install -d -m 0755 -o root -g root /run/sw-block +sudo install -d -m 0755 -o "$USER" -g "$(id -gn)" /run/sw-block/locks +./sw-block mini --dir ./swb-mini --weed /path/to/weed ``` -`volume-delete` is refused until the volume's holder has been revoked and its ACK -is recorded, and while the volume has snapshots: see -[Delete a volume](docs/volume-lifecycle.md#delete-a-volume). -Frozen detach and the pre-copy detach are not supported in this release: a -detach with `--frozen` (`frozen:true` on `POST /chunk/detach`) is refused with -409 `frozen_detach_unsupported`, and `blockvolume` refuses to start with -`--chunk-detach-precopy`. -`restore` creates the target from the snapshot; its blockvolume serves at -once and reads every chunk it has not made local from the source's snapshot -(there is no background copy). The source snapshot cannot be deleted while the -target exists. Fork is not supported in this release; the command is removed. -See [Restoring a snapshot](docs/standalone-deployment.md#restoring-a-snapshot-into-a-new-volume). -In v1.0.0 the chunk path (`walstore-chunk`) is the supported single-replica -configuration ([release note](docs/releases/v1.0.0.md), [operator guide](docs/operator-guide.md)); -it is not the `--durable-impl` default. +A failed start leaves `--dir` behind: start again with a new `--dir`, or on the same one with `--reuse`. -## Quick start: Kubernetes (alpha) +**What it shows today:** +- `mini` starts `weed mini`, `blockmaster` and one `blockvolume`: volume `v1`, 256 MiB, on loopback. +- It never runs `sudo` itself. It prints the `nvme connect` command that attaches `v1`, and the status, check and + snapshot commands. After the connect, `sudo nvme list` shows the disk's device (for example `/dev/nvme0n1`). +- Snapshots of `v1` work at once, through the `sw-block ops chunk snapshot` command it prints. A scheduled + `sched-