Merge main: rows recounted with the document check

Main's wording wins where it changed a row; the not-reachable marks, the
two new rows and the note are kept; the count is recomputed from the
tables and the document check passes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Fable 5.2 committed 2026-11-21 10:32:47 -08:00
commit 8b4d357d59
68 files changed
+2804 -268

No files matched your search

+7 -51
View File
@@ -62,18 +62,18 @@ jobs:
run: go vet ./...
- name: Test default configuration
# A PR runs the light set plus every heavy package its own diff touches;
# the long, disk-heavy, timing-sensitive packages run in full on main and
# on train PRs. A green PR check does not cover an untouched heavy package.
# 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.
env:
EVENT: ${{ github.event_name }}
HEAD_REF: ${{ github.head_ref }}
run: |
set -euo pipefail
if [ "$EVENT" = push ] || [[ "$HEAD_REF" == train/* ]]; then
pkgs=$(go list ./...)
else
pkgs=$(go list ./... | grep -vE '/core/(storage|frontend/durable|host/master|authority)$')
pkgs=$(go list ./... | grep -vE '/core/(storage|frontend/durable|host/master|authority)$')
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
@@ -83,47 +83,3 @@ jobs:
done
fi
go test -p=1 -short -count=1 -timeout 10m $pkgs
test-legacy:
name: go test legacy-fixture
# A second full pass (legacy-fixture tag) writes as much again: it runs on
# main and on train PRs, which carry every change that merges.
if: github.event_name == 'push' || startsWith(github.head_ref, 'train/')
# Same routing as the default job: same-repo PRs and pushes use the tp04
# runners (two instances, so both passes run in parallel); fork PRs stay on
# a GitHub-hosted runner, whose shared queue can wait for hours.
runs-on: ${{ (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && 'tp04-seaweed-block' || 'ubuntu-latest' }}
timeout-minutes: 40
env:
CGO_ENABLED: "0"
steps:
- name: Checkout
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
persist-credentials: false
- name: Set up Go
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
with:
go-version-file: go.mod
# The self-hosted runner keeps GOCACHE/GOMODCACHE on its own disk;
# uploading them as an Actions cache (~4 GB) in the post step
# outlasted the job timeout after every test had passed. Only the
# GitHub-hosted (fork PR) runner uses the Actions cache.
cache: ${{ runner.environment == 'github-hosted' }}
cache-dependency-path: go.sum
- name: Go version
run: go version
- name: Build
run: go build ./...
- name: Vet
run: go vet ./...
- name: Test legacy-fixture configuration
# Legacy-input fixtures and native caller controls stay executable after
# their constructors move behind the explicit test-only build tag.
# Bound package concurrency for existing short wall-clock assertions.
run: go test -p=1 -short -tags=swblock_format_v3_test -count=1 -timeout 10m ./...
+14
View File
@@ -128,6 +128,8 @@ sw-block ops chunk cut --volume v1 --status-addr <status> # publish chang
sw-block ops chunk snapshot --volume v1 --status-addr <status> --name s1 # name a snapshot
sw-block ops chunk snapshots --volume v1 --chunk-filer <filer> # list snapshots
sw-block ops chunk fork --chunk-filer <filer> --source v1 --snapshot s1 --target v2 # root copy only
sw-block ops chunk restore --chunk-filer <filer> --source v1 --snapshot s1 --target v3 --status-addr <v3's status> # independent copy
sw-block ops chunk restore --volume v3 --status-addr <status> --status # restore progress
sw-block ops chunk detach --volume v1 --status-addr <status> # final cut and release; resume elsewhere
sw-block ops chunk volume-delete --volume v2 --chunk-filer <filer> --master <blockmaster> --request-id del-v2
sw-block ops chunk gc --chunk-filer <filer> --master <blockmaster> # preview; --apply to reclaim
@@ -139,6 +141,12 @@ 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 and, with `--status-addr` naming
the blockvolume that serves the target, starts the background restore there:
the target serves at once, copies every chunk under its own keys and becomes
independent of the source (snapshots of it are refused until then). Without
`--status-addr` it only creates the target and prints the command that starts
the restore once the target is attached.
The chunk path (`walstore-chunk`) is a proof of concept. It is not yet a
default, a release claim or a production path.
@@ -187,6 +195,12 @@ bash scripts/uninstall-k8s-alpha.sh "$PWD" && bash scripts/verify-helm-cleanup.s
Full table and conditions: [Kubernetes status](docs/kubernetes-status.md);
run evidence: [release notes](docs/releases/README.md).
**Upgrade note:** blockmaster now refuses a non-loopback `--listen` (and a
non-loopback `--frontend-publication-runtime-listen` when that API is on)
unless `--insecure-external-bind` is given, because its control API is
unauthenticated. The Helm chart and the shipped manifests already pass it;
a launcher of your own that binds blockmaster to a node address must add it.
### Not claimed yet
- Production readiness, SLOs, or a published performance, RTO or RPO claim.
@@ -106,6 +106,7 @@ spec:
{{- end }}
- "--launcher-kubernetes-apply"
- "--listen=0.0.0.0:{{ .Values.blockmaster.listenPort }}"
- "--insecure-external-bind"
{{- if .Values.blockmaster.failbackRuntimeRPC }}
- "--failback-runtime-rpc"
{{- end }}
+3 -3
View File
@@ -21,7 +21,7 @@ import (
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/internal/buildinfo"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
type flags struct {
@@ -127,7 +127,7 @@ func run(f flags) int {
registrar blockcsi.VolumeObjectRegistrar
)
if f.masterAddr != "" {
masterConn, err = grpc.NewClient(f.masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
masterConn, err = link.Dial(f.masterAddr)
if err != nil {
fmt.Fprintln(os.Stderr, "blockcsi: master dial:", err)
return 1
@@ -167,7 +167,7 @@ func run(f flags) int {
nodeSrv.StartMountedNVMeReconnectOwner(reconnectCtx, f.nvmeReconnectInterval)
}
srv := grpc.NewServer()
srv := link.NewServer(link.ServerConfig{})
csipb.RegisterIdentityServer(srv, blockcsi.NewIdentityServer())
csipb.RegisterControllerServer(srv, blockcsi.NewControllerServerWithProvisionerMetadataAndRegistrar(lookup, provisioner, resolver, registrar))
csipb.RegisterNodeServer(srv, nodeSrv)
@@ -0,0 +1,53 @@
package main
import (
"os"
"strings"
"testing"
)
// The unauthenticated control listeners bind loopback unless
// --insecure-external-bind is given: --listen always, and the runtime HTTP
// listener when its API is enabled.
func TestParseFlags_ControlListenersNeedInsecureExternalBind(t *testing.T) {
base := func(extra ...string) []string { return append([]string{"--authority-store", t.TempDir()}, extra...) }
for _, ok := range []string{"127.0.0.1:9333", "localhost:9333", "[::1]:9333", "127.0.0.1:0"} {
if _, err := parseFlags(base("--listen", ok)); err != nil {
t.Fatalf("--listen %s: %v", ok, err)
}
}
for _, bad := range []string{"0.0.0.0:9333", ":9333", "10.0.0.5:9333", "[::]:9333"} {
_, err := parseFlags(base("--listen", bad))
if err == nil || !strings.Contains(err.Error(), "--insecure-external-bind") {
t.Fatalf("--listen %s without the opt-in: %v, want a refusal naming --insecure-external-bind", bad, err)
}
if _, err := parseFlags(base("--listen", bad, "--insecure-external-bind")); err != nil {
t.Fatalf("--listen %s with --insecure-external-bind: %v", bad, err)
}
}
if _, err := parseFlags(base("--frontend-publication-runtime-listen", "0.0.0.0:9334")); err != nil {
t.Fatalf("runtime listener disabled: its address is not checked: %v", err)
}
_, err := parseFlags(base("--frontend-publication-runtime-http", "--frontend-publication-runtime-listen", "0.0.0.0:9334"))
if err == nil || !strings.Contains(err.Error(), "frontend-publication-runtime-listen") {
t.Fatalf("enabled runtime listener on 0.0.0.0 without the opt-in: %v", err)
}
if _, err := parseFlags(base("--frontend-publication-runtime-http", "--frontend-publication-runtime-listen", "0.0.0.0:9334", "--insecure-external-bind")); err != nil {
t.Fatalf("with the opt-in: %v", err)
}
}
// Every shipped manifest that binds blockmaster to 0.0.0.0 carries the
// explicit opt-in, so the change refuses nothing that ships.
func TestManifests_ExternalBlockmasterBindCarriesTheOptIn(t *testing.T) {
for _, p := range []string{"../../charts/seaweed-block/templates/blockmaster.yaml", "../../deploy/k8s/alpha/block-stack.yaml", "../../deploy/k8s/g15b/block-stack.yaml", "../../deploy/k8s/g15d/block-stack.yaml"} {
b, err := os.ReadFile(p)
if err != nil {
t.Fatal(err)
}
s := string(b)
if strings.Contains(s, "--listen=0.0.0.0") && !strings.Contains(s, "--insecure-external-bind") {
t.Fatalf("%s binds blockmaster to 0.0.0.0 without --insecure-external-bind", p)
}
}
}
+11 -1
View File
@@ -21,6 +21,7 @@ import (
)
type flags struct {
insecureExternalBind bool
authorityStore string
lifecycleStore string
lifecyclePlacementSeed string
@@ -77,7 +78,8 @@ func parseFlags(args []string) (flags, error) {
fs.StringVar(&f.lifecycleStore, "lifecycle-store", "", "optional G9D product lifecycle registration store directory (desired volumes, node inventory, placement intents); read-only with respect to assignment publication")
fs.StringVar(&f.lifecyclePlacementSeed, "lifecycle-placement-seed", "", "placement-only seed JSON; lifecycle volumes must already be registered (CreateVolume)")
fs.StringVar(&f.clusterSpec, "cluster-spec", "", "cluster spec YAML; positive size_bytes imports desired volumes before topology/placement publication")
fs.StringVar(&f.listen, "listen", "127.0.0.1:0", "gRPC listen address (e.g. 127.0.0.1:9180)")
fs.StringVar(&f.listen, "listen", "127.0.0.1:0", "gRPC listen address (e.g. 127.0.0.1:9180); non-loopback requires --insecure-external-bind")
fs.BoolVar(&f.insecureExternalBind, "insecure-external-bind", false, "allow the unauthenticated control listeners (--listen, --frontend-publication-runtime-listen) on non-loopback addresses")
fs.StringVar(&f.topology, "topology", "", "path to accepted-topology YAML (required for assignment to mint)")
fs.IntVar(&f.expectedSlotsPerVol, "expected-slots-per-volume", 3, "RF/expected slot count per volume; the controller rejects observation snapshots whose slot count differs (default 3, set to 2 for 2-node smoke clusters)")
fs.DurationVar(&f.freshnessWindow, "freshness-window", 30*time.Second, "observation freshness window before a server's heartbeat expires")
@@ -138,6 +140,14 @@ func parseFlags(args []string) (flags, error) {
if err := master.ValidateStatusListen(f.statusListen); err != nil {
return flags{}, err
}
if err := master.ValidateControlListen("listen", f.listen, f.insecureExternalBind); err != nil {
return flags{}, err
}
if f.frontendPublicationRuntimeHTTP {
if err := master.ValidateControlListen("frontend-publication-runtime-listen", f.frontendPublicationRuntimeListen, f.insecureExternalBind); err != nil {
return flags{}, err
}
}
if f.launcherExternalISCSI && f.launcherCHAPSecretName == "" {
return flags{}, fmt.Errorf("cannot enable --launcher-external-iscsi without --launcher-iscsi-chap-secret-name")
}
@@ -87,6 +87,7 @@ func TestParseFlags_FrontendPublicationRuntimeHTTPDisabledByDefault(t *testing.T
"--authority-store", "authority-dir",
"--frontend-publication-runtime-http",
"--frontend-publication-runtime-listen", "0.0.0.0:9334",
"--insecure-external-bind", // a non-loopback control listener is an explicit choice
})
if err != nil {
t.Fatalf("parseFlags with frontend publication runtime HTTP: %v", err)
@@ -8,8 +8,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// Automatic GC stays default-off until restart-safe unknown-CAS settlement and
@@ -27,7 +26,7 @@ func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter,
if defaultChunkGCGrace <= max(defaultChunkCutTimeout, chunkstore.DefaultOpDeadline)+defaultChunkMaintenanceTimeout {
return nil, closeFn, errors.New("automatic GC grace does not cover cut/copy and mark bounds")
}
conn, err := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(master)
if err != nil {
return nil, closeFn, err
}
+42 -3
View File
@@ -10,6 +10,7 @@ import (
"errors"
"fmt"
"path"
"strconv"
"strings"
"time"
@@ -21,8 +22,8 @@ import (
const (
defaultChunkPath = "/swblock/chunks"
// Periodic HEAD publication bounds the host-loss recovery point. Automatic
// named snapshots remain explicit catalog operations.
// Periodic HEAD publication bounds the host-loss recovery point. Scheduled
// named snapshots are set by --chunk-snapshot-schedule.
defaultChunkCaptureInterval = 0
defaultChunkMaintenanceInterval = time.Hour
defaultChunkCutTimeout = 5 * time.Minute
@@ -40,6 +41,7 @@ type chunkFlags struct {
replication string
captureInterval time.Duration
maintenanceInterval time.Duration
snapshotSchedule snapshotSchedule
automaticGC bool
uploadConcurrency int
hydrationWorkers int
@@ -62,7 +64,7 @@ func validateChunkFlags(f flags) error {
}
if f.durableImpl != "walstore-chunk" {
if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath ||
c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.automaticGC ||
c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.snapshotSchedule != defaultSnapshotSchedule || c.automaticGC ||
c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy || c.hostLimit.Directory != "" {
return errors.New("--chunk-* flags require --durable-impl=walstore-chunk")
}
@@ -114,6 +116,43 @@ const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, whi
// chunkWiring is what --durable-impl=walstore-chunk dials once: the
// provider's per-volume remotes, the catalog under the same base (VOLUME
// entries, snapshots) and the client's closer.
// snapshotSchedule is --chunk-snapshot-schedule: "daily:N", "weekly:N"
// (one scheduled snapshot per period at a per-volume offset, the newest N
// kept) or "off".
type snapshotSchedule struct {
period time.Duration
keep int
}
var defaultSnapshotSchedule = snapshotSchedule{period: 24 * time.Hour, keep: 7}
func (s *snapshotSchedule) String() string {
switch s.period {
case 0:
return "off"
case 24 * time.Hour:
return fmt.Sprintf("daily:%d", s.keep)
case 7 * 24 * time.Hour:
return fmt.Sprintf("weekly:%d", s.keep)
}
return fmt.Sprintf("%s:%d", s.period, s.keep)
}
func (s *snapshotSchedule) Set(v string) error {
if v == "off" {
*s = snapshotSchedule{}
return nil
}
name, count, ok := strings.Cut(v, ":")
periods := map[string]time.Duration{"daily": 24 * time.Hour, "weekly": 7 * 24 * time.Hour}
keep, err := strconv.Atoi(count)
if !ok || periods[name] == 0 || err != nil || keep < 1 || keep > 1000 {
return fmt.Errorf("%q: want daily:N, weekly:N (N from 1 to 1000) or off", v)
}
*s = snapshotSchedule{period: periods[name], keep: keep}
return nil
}
type chunkWiring struct {
remoteFor func(volumeID string) (storage.ChunkRemote, error)
catalog *chunkstore.Catalog
@@ -163,3 +163,40 @@ func TestChunkDirtyThresholdFlagIsGone(t *testing.T) {
t.Fatalf("--chunk-dirty-threshold: %v; want flag provided but not defined", err)
}
}
// --chunk-snapshot-schedule: daily:7 by default; daily:N, weekly:N and off
// are accepted; anything else is refused; setting it without walstore-chunk
// is refused like the other chunk flags.
func TestChunkSnapshotScheduleFlag(t *testing.T) {
base := func(extra ...string) []string {
return append(phase150RequiredBlockvolumeArgs(), extra...)
}
chunk := func(extra ...string) []string {
return base(append([]string{"--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1"}, extra...)...)
}
d, err := parseFlags(chunk())
if err != nil || d.chunk.snapshotSchedule != (snapshotSchedule{period: 24 * time.Hour, keep: 7}) {
t.Fatalf("default schedule %+v %v; want daily, keep 7", d.chunk.snapshotSchedule, err)
}
for v, want := range map[string]snapshotSchedule{
"daily:3": {period: 24 * time.Hour, keep: 3},
"weekly:4": {period: 7 * 24 * time.Hour, keep: 4},
"off": {},
} {
f, err := parseFlags(chunk("--chunk-snapshot-schedule=" + v))
if err != nil || f.chunk.snapshotSchedule != want {
t.Fatalf("%s: %+v %v; want %+v", v, f.chunk.snapshotSchedule, err, want)
}
if got := f.chunk.snapshotSchedule.String(); got != v {
t.Fatalf("%s prints as %q", v, got)
}
}
for _, v := range []string{"hourly:7", "daily", "daily:0", "daily:x", "weekly:-1", "daily:1001", ""} {
if _, err := parseFlags(chunk("--chunk-snapshot-schedule=" + v)); err == nil {
t.Fatalf("%q accepted", v)
}
}
if _, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-snapshot-schedule=weekly:4")); err == nil {
t.Fatal("--chunk-snapshot-schedule accepted without walstore-chunk")
}
}
+6
View File
@@ -204,6 +204,8 @@ func parseFlags(args []string) (flags, error) {
fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)")
fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: not supported in this release; blockvolume refuses to start when it is set")
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least 5m)")
f.chunk.snapshotSchedule = defaultSnapshotSchedule
fs.Var(&f.chunk.snapshotSchedule, "chunk-snapshot-schedule", "walstore-chunk: scheduled snapshots, daily:N or weekly:N (once per period at a per-volume offset, the newest N kept) or off")
fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables")
fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: enable scoped automatic GC; off pending restart-safe unknown-CAS settlement and density qualification")
fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)")
@@ -665,6 +667,10 @@ func run(f flags) int {
cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval
cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout
cfg.ChunkMaintenance = chunk.maintenance
if chunk.catalog != nil && f.chunk.snapshotSchedule.period > 0 {
cfg.ChunkSnapshotPeriod = f.chunk.snapshotSchedule.period
cfg.ChunkScheduledSnapshot = volume.ScheduledSnapshot(chunk.catalog, f.chunk.snapshotSchedule.keep)
}
cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy
cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency
cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers
+2 -3
View File
@@ -10,8 +10,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// Same clock seam as GCConfig; production always uses wall time. Tests can
@@ -78,7 +77,7 @@ func chunkGC(args []string, stdout, stderr io.Writer) int {
// masterEvidence dials the blockmaster's evidence service (gc and
// volume-delete read volume status from it).
func masterEvidence(master string) (control.EvidenceServiceClient, func() error, error) {
conn, e := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, e := link.Dial(master)
if e != nil {
return nil, nil, e
}
+73 -11
View File
@@ -1,30 +1,92 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/ops"
)
// chunkRestore starts (or joins) the independent-restore driver of a volume
// restored from a snapshot and prints its status; with --status it only
// prints the status. The driver runs in blockvolume and outlives this call.
// chunkRestore restores a snapshot into a new independent volume, or drives
// an existing restore.
//
// With --source, --snapshot and --target it creates the target volume from
// the snapshot (Catalog.Restore, idempotent by --request-id) and, when
// --status-addr names the blockvolume serving the target, starts the restore
// driver there and prints its status (the create result goes to stderr). With --volume and --status-addr it
// starts (or joins) the driver of an existing restore and prints its status;
// --status only prints the status. The driver runs in blockvolume and
// outlives this call.
func chunkRestore(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("restore", stderr)
var (
volumeID, statusAddr string
statusOnly bool
volumeID, statusAddr string
filer, base, source, snapshot, target, requestID string
statusOnly bool
timeout time.Duration
)
fs.StringVar(&volumeID, "volume", "", "restored volume id")
fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)")
fs.StringVar(&volumeID, "volume", "", "restored volume id (drive an existing restore)")
fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL serving the restored volume (with --chunk-control-endpoint)")
fs.BoolVar(&statusOnly, "status", false, "print the restore status without starting a run")
fs.StringVar(&source, "source", "", "source volume id (create a restore)")
fs.StringVar(&snapshot, "snapshot", "", "source snapshot name (create a restore)")
fs.StringVar(&target, "target", "", "new volume id (create a restore)")
fs.StringVar(&requestID, "request-id", "", "idempotency id for the create; generated and printed when empty (reuse it to retry)")
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port (create a restore)")
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
fs.DurationVar(&timeout, "timeout", 6*time.Minute, "filer timeout for the create")
if err := fs.Parse(args); err != nil {
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
if volumeID == "" || statusAddr == "" {
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false)
create := source != "" || snapshot != "" || target != ""
switch {
case create && volumeID != "":
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "use --source/--snapshot/--target to create a restore, or --volume to drive one, not both", false)
case create && (source == "" || snapshot == "" || target == ""):
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--source, --snapshot and --target are required to create a restore", false)
case create && statusOnly:
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--status reads an existing restore: use it with --volume", false)
case !create && (volumeID == "" || statusAddr == ""):
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required (or --source, --snapshot and --target to create a restore)", false)
}
body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly}
return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr)
if !create {
body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly}
return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr)
}
if requestID == "" {
requestID = newRequestID()
fmt.Fprintf(stderr, "sw-block ops chunk restore: request id %s (reuse it to retry)\n", requestID)
}
cat, closeFn, exit := chunkCatalog("restore", filer, base, true, timeout, stdout, stderr)
if exit >= 0 {
return exit
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
res, err := cat.Restore(ctx, chunkstore.ForkRequest{Source: source, Snapshot: snapshot, Target: target, RequestID: requestID})
if err != nil || statusAddr == "" {
if err == nil {
fmt.Fprintf(stderr, "sw-block ops chunk restore: %s created; attach it, then run: sw-block ops chunk restore --volume %s --status-addr <its blockvolume>\n", target, target)
}
return chunkResult("restore", res, err, stdout, stderr)
}
created, err := json.Marshal(res)
if err != nil {
return chunkFail("restore", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
}
// stdout stays one JSON document (the driver status); the create result
// goes to stderr.
fmt.Fprintf(stderr, "sw-block ops chunk restore: created %s\n", created)
body := map[string]any{"volumeID": target}
code := chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr)
if code != ops.VolumeStatusExitOK {
fmt.Fprintf(stderr, "sw-block ops chunk restore: %s was created, but the restore did not start at %s (is the target attached there?); once it is, run: sw-block ops chunk restore --volume %s --status-addr <its blockvolume>\n", target, statusAddr, target)
}
return code
}
@@ -2,11 +2,16 @@ package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) {
@@ -37,3 +42,123 @@ func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) {
t.Fatal("restore without --volume must be refused")
}
}
// restoreSource publishes volume src with one chunk and snapshot s1 in a
// fresh store, and routes the CLI's filer dial to it.
func restoreSource(t *testing.T, base string) (*gcCLIStore, *chunkstore.Catalog) {
t.Helper()
ctx := context.Background()
store := &gcCLIStore{MemFiler: chunkstore.NewMemFiler()}
old := dialChunkFiler
t.Cleanup(func() { dialChunkFiler = old })
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil }
cat, err := chunkstore.NewCatalog(store, base)
if err != nil {
t.Fatal(err)
}
geo := chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}
if _, err := cat.EnsureVolume(ctx, "src", geo); err != nil {
t.Fatal(err)
}
r, err := chunkstore.NewChunkRemote(store, store, base+"/src")
if err != nil {
t.Fatal(err)
}
cur, err := r.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
data := make([]byte, 8*4096)
data[0] = 0x7
if err := r.Put(ctx, "chunks/e1/c0/k", data); err != nil {
t.Fatal(err)
}
h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k", SHA256: sha256.Sum256(data)}}}
h, ids, err := r.PrepareManifest(ctx, cur, h, 8*4096)
if err != nil {
t.Fatal(err)
}
if h.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil {
t.Fatal(err)
}
for _, id := range ids {
_ = r.DeleteIntent(ctx, id)
}
if _, err := cat.CreateSnapshot(ctx, "src", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
return store, cat
}
// --source/--snapshot/--target creates the restore volume (idempotent by
// request id); without --status-addr it says how to start the driver.
func TestOpsChunk_RestoreCreatesTheTarget(t *testing.T) {
_, cat := restoreSource(t, "/rs")
args := []string{"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs"}
code, out, errs := runChunk(args...)
if code != 0 || !strings.Contains(out, `"dst"`) || !strings.Contains(errs, "--volume dst") {
t.Fatalf("create: exit %d out %s err %s", code, out, errs)
}
v, ok, err := cat.ReadVolume(context.Background(), "dst")
if err != nil || !ok || v.Origin != chunkstore.OriginRestore {
t.Fatalf("target: %+v ok=%v %v, want a restore volume", v, ok, err)
}
if code, out, errs := runChunk(args...); code != 0 {
t.Fatalf("retry with the same request id: exit %d out %s err %s", code, out, errs)
}
for _, bad := range [][]string{
{"restore", "--source", "src", "--target", "dst", "--chunk-filer", "x"},
{"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--volume", "dst", "--chunk-filer", "x"},
{"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--status", "--chunk-filer", "x"},
} {
if code, _, _ := runChunk(bad...); code == 0 {
t.Fatalf("%v accepted", bad)
}
}
}
// With --status-addr the create then starts the driver for the target on
// that blockvolume, in one command.
func TestOpsChunk_RestoreCreatesAndStartsTheDriver(t *testing.T) {
_, cat := restoreSource(t, "/rs2")
var got map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewDecoder(r.Body).Decode(&got)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"volumeID":"dst","phase":"hydrating","running":true}`))
}))
defer srv.Close()
code, out, errs := runChunk("restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs2", "--status-addr", srv.URL)
if code != 0 || !strings.Contains(out, `"phase":"hydrating"`) || !strings.Contains(errs, "created ") {
t.Fatalf("create and start: exit %d out %s err %s", code, out, errs)
}
var one map[string]any
if err := json.Unmarshal([]byte(out), &one); err != nil {
t.Fatalf("stdout is not one JSON document: %v (%s)", err, out)
}
if got["volumeID"] != "dst" || got["statusOnly"] != nil {
t.Fatalf("driver request %v, want a start for dst", got)
}
if _, ok, _ := cat.ReadVolume(context.Background(), "dst"); !ok {
t.Fatal("the target was not created before the driver start")
}
}
// A start that fails after the create (the target not attached there yet)
// says the target exists and how to start the restore later.
func TestOpsChunk_RestoreCreateThenStartRefusedSaysHowToResume(t *testing.T) {
_, cat := restoreSource(t, "/rs3")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"code":"not_chunk_volume","message":"volume dst not open","retryable":false}`))
}))
defer srv.Close()
code, _, errs := runChunk("restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs3", "--status-addr", srv.URL)
if code == 0 || !strings.Contains(errs, "dst was created") || !strings.Contains(errs, "--volume dst") {
t.Fatalf("refused start: exit %d err %s", code, errs)
}
if _, ok, _ := cat.ReadVolume(context.Background(), "dst"); !ok {
t.Fatal("the target must exist after the create")
}
}
@@ -8,14 +8,13 @@ import (
"io"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// chunkVolumeDelete: sw-block ops chunk volume-delete <vol> --chunk-filer
@@ -51,7 +50,7 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int {
return exit
}
defer closeFn()
conn, err := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(master)
if err != nil {
return chunkResult("volume-delete", nil, err, stdout, stderr)
}
+2 -3
View File
@@ -17,9 +17,8 @@ import (
"github.com/seaweedfs/seaweed-block/core/ops"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"github.com/seaweedfs/seaweed-block/internal/buildinfo"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"gopkg.in/yaml.v3"
)
@@ -1158,7 +1157,7 @@ func liveNodeEvidenceNamespace(namespace string) string {
}
func readMasterClusterEvidence(ctx context.Context, masterAddr string) (ops.ClusterEvidence, error) {
conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(masterAddr)
if err != nil {
return ops.ClusterEvidence{}, err
}
+22 -1
View File
@@ -199,7 +199,28 @@ func (p *Publisher) IssuedWorkspaceMove(req WorkspaceMoveRequest) bool {
return replay && err == nil
}
func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (WorkspaceMoveRecord, error) {
// WorkspaceMoveOutcomeError classifies a failed move at the reply boundary.
// M2 Uncertain / INV-AUTH-UNCERTAIN-001: admission cannot promise no effect
// while an earlier workspace write may have landed. Actual request cancellation
// stays typed; dependency errors do not bypass uncertainty.
func (p *Publisher) WorkspaceMoveOutcomeError(ctx context.Context, volume string, err error) error {
if err == nil {
return nil
}
if callerErr := ctx.Err(); callerErr != nil {
return callerErr
}
p.mu.Lock()
uncertain := p.workspaceUncertain[volume]
p.mu.Unlock()
if uncertain {
return errors.Join(ErrWorkspaceOutcomeUncertain, err)
}
return err
}
func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (_ WorkspaceMoveRecord, resultErr error) {
defer func() { resultErr = p.WorkspaceMoveOutcomeError(ctx, req.VolumeID, resultErr) }()
if err := ctx.Err(); err != nil {
return WorkspaceMoveRecord{}, err
}
@@ -3,6 +3,7 @@ package authority
import (
"context"
"errors"
"reflect"
"testing"
"time"
)
@@ -67,3 +68,71 @@ func TestWorkspaceUncertainIssueWriteIsTyped(t *testing.T) {
t.Fatalf("readout after reload: %+v %v", got, err)
}
}
func TestWorkspaceUncertaintyPrecedesRequestRefusal(t *testing.T) {
ctx := context.Background()
disk, _ := newTempStore(t)
p, _, _ := forcedLostRangeFixture(t, disk, false)
t.Cleanup(p.CloseWorkspaceExtenders)
bad := forcedLostRangeReq
bad.TargetReplicaID = "other-slot"
if _, err := p.MoveWorkspace(ctx, bad, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) {
t.Fatalf("healthy refusal changed: %v", err)
}
faults := 0
SetPutAfterRenameFaultForTest(func(r DurableRecord) error {
if r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking {
faults++
return errInjected
}
return nil
})
t.Cleanup(func() { SetPutAfterRenameFaultForTest(nil) })
if err := p.BeginWorkspaceRevocation(ctx, "v", "old", 1); !errors.Is(err, errInjected) {
t.Fatalf("failed persistence not witnessed: %v", err)
}
SetPutAfterRenameFaultForTest(nil)
if faults != 1 || p.WorkspaceState("v").Lease.Revoking {
t.Fatal("fixture did not retain pre-write memory")
}
records, err := disk.Load()
if err != nil {
t.Fatal(err)
}
landed := false
for _, r := range records {
if r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking {
landed = true
}
}
if !landed {
t.Fatal("faulted write did not land on disk")
}
before := p.WorkspaceState("v")
for _, req := range []WorkspaceMoveRequest{bad, forcedLostRangeReq} {
if _, err := p.MoveWorkspace(ctx, req, forcedLostRangeHead); !errors.Is(err, ErrWorkspaceOutcomeUncertain) {
t.Errorf("uncertain volume answered a definite admission refusal: %v", err)
}
}
for _, dependencyErr := range []error{context.Canceled, context.DeadlineExceeded} {
if ctx.Err() != nil {
t.Fatal("request parent unexpectedly ended")
}
if err := p.WorkspaceMoveOutcomeError(ctx, "v", dependencyErr); !errors.Is(err, ErrWorkspaceOutcomeUncertain) {
t.Errorf("live caller dependency error bypassed UNKNOWN: %v", err)
}
}
canceled, cancel := context.WithCancel(ctx)
cancel()
if _, err := p.MoveWorkspace(canceled, bad, forcedLostRangeHead); err != context.Canceled {
t.Errorf("caller cancellation changed: %v", err)
}
other := bad
other.VolumeID = "other"
if _, err := p.MoveWorkspace(ctx, other, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) {
t.Errorf("uncertainty leaked across volumes: %v", err)
}
if !reflect.DeepEqual(before, p.WorkspaceState("v")) {
t.Fatal("refused requests changed authority memory")
}
}
@@ -23,6 +23,11 @@ import (
// - "pinned": an explicit keep. It is never expired by count or age,
// only by its own ExpiresAtNs or an explicit delete. A snapshot with
// ExpiresAtNs set is pinned whatever its class.
// - "scheduled": a scheduled snapshot. Retention keeps the newest K of
// this class, where K is the LabelScheduleKeep of the newest one
// (DefaultScheduleKeep when absent).
// They are not counted against KeepNewest, and the age and log-spaced
// keeps do not apply to them, so other snapshots are unaffected.
// - "" (snapshots made before classes existed): treated as unpinned.
//
// The policy is stored on the VOLUME entry. Retain keeps
@@ -61,8 +66,16 @@ import (
// it and frees the name.
const (
SnapshotClassSemantic = "semantic"
SnapshotClassPinned = "pinned"
SnapshotClassSemantic = "semantic"
SnapshotClassPinned = "pinned"
SnapshotClassScheduled = "scheduled"
// LabelScheduleKeep, on a scheduled snapshot, is how many scheduled
// snapshots its schedule keeps (a decimal count).
LabelScheduleKeep = "swb.schedule.keep"
// DefaultScheduleKeep is the count kept when the newest scheduled
// snapshot carries no valid LabelScheduleKeep.
DefaultScheduleKeep = 7
CodeInvalidClass = "invalid_class"
CodeInvalidPolicy = "invalid_policy"
@@ -74,14 +87,14 @@ const (
extRetentionRev = "retention_rev"
)
// ValidateSnapshotClass refuses a class other than "", "semantic" and
// "pinned" (invalid_class).
// ValidateSnapshotClass refuses a class other than "", "semantic",
// "pinned" and "scheduled" (invalid_class).
func ValidateSnapshotClass(class string) error {
switch class {
case "", SnapshotClassSemantic, SnapshotClassPinned:
case "", SnapshotClassSemantic, SnapshotClassPinned, SnapshotClassScheduled:
return nil
}
return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q or %q", class, SnapshotClassSemantic, SnapshotClassPinned)
return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q, %q or %q", class, SnapshotClassSemantic, SnapshotClassPinned, SnapshotClassScheduled)
}
// Pinned reports whether the snapshot is an explicit keep.
@@ -198,6 +211,7 @@ const (
keepHourly = "hourly"
keepDaily = "daily"
keepWeekly = "weekly"
keepScheduled = "scheduled_newest"
reasonExpired = "expired"
)
@@ -215,11 +229,32 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []Ret
})
nowNs := now.UnixNano()
out := make([]RetentionDecision, len(ordered))
unpinned := 0
unpinned, scheduled := 0, 0
scheduleKeep := -1 // read from the newest scheduled snapshot
windows := map[string]bool{}
for i, s := range ordered {
pinned := s.Pinned() && (s.ExpiresAtNs == 0 || nowNs < s.ExpiresAtNs)
d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: pinned}
if s.Class == SnapshotClassScheduled {
// Every scheduled snapshot, pinned or not, is planned here and
// ranked among its class; a pinned one is also kept by its pin.
if scheduleKeep < 0 {
scheduleKeep = scheduleKeepOf(s)
}
if pinned {
d.Reasons = append(d.Reasons, keepPinned)
}
if scheduled < scheduleKeep {
d.Reasons = append(d.Reasons, keepScheduled)
}
scheduled++
d.Keep = len(d.Reasons) > 0
if !d.Keep {
d.Reasons = []string{reasonExpired}
}
out[i] = d
continue
}
if pinned {
d.Reasons = append(d.Reasons, keepPinned)
} else {
@@ -263,6 +298,14 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []Ret
return out
}
// scheduleKeepOf is the count a scheduled snapshot's schedule keeps.
func scheduleKeepOf(s SnapshotInfo) int {
if n, err := strconv.Atoi(s.Labels[LabelScheduleKeep]); err == nil && n > 0 {
return n
}
return DefaultScheduleKeep
}
// RetentionFailure is the deletion that stopped a Retain pass.
type RetentionFailure struct {
Name string `json:"name"`
@@ -381,3 +381,51 @@ func TestChunkSizeClipsLastChunk(t *testing.T) {
}
}
}
// Scheduled snapshots form their own class: retention keeps the newest K
// of them, K from the newest one's LabelScheduleKeep, and they neither
// count against KeepNewest nor get the age keeps; other snapshots are
// planned as before.
func TestPlanRetention_ScheduledClassKeepsItsOwnNewest(t *testing.T) {
now := retBase.Add(30 * 24 * time.Hour)
keep3 := map[string]string{LabelScheduleKeep: "3"}
var snaps []SnapshotInfo
for d := 0; d < 6; d++ { // one scheduled snapshot a day, the newest first at now-1h
snaps = append(snaps, snapAt(fmt.Sprintf("sched-%d", d), now.Add(-time.Hour-time.Duration(d)*24*time.Hour), SnapshotClassScheduled, time.Time{}, keep3))
}
snaps = append(snaps,
snapAt("manual-new", now.Add(-2*time.Hour), "", time.Time{}, nil),
snapAt("manual-old", now.Add(-20*24*time.Hour), "", time.Time{}, nil))
k := kept(planRetention(RetentionPolicy{KeepNewest: 2, KeepYoungerNs: int64(30 * 24 * time.Hour)}, snaps, now))
for _, name := range []string{"sched-0", "sched-1", "sched-2", "manual-new", "manual-old"} {
if k[name] == nil {
t.Fatalf("kept %v; %s missing", k, name)
}
}
if len(k) != 5 {
t.Fatalf("kept %v; want the 3 newest scheduled and both manual (KeepNewest 2 is theirs alone)", k)
}
// Without a valid label the default count applies.
snaps[0].Labels = nil
if k := kept(planRetention(RetentionPolicy{}, snaps[:6], now)); len(k) != 6 {
t.Fatalf("kept %v with no label on the newest; want min(6, DefaultScheduleKeep)", k)
}
}
// A pinned scheduled snapshot stays in its class: it is kept by its pin,
// ranks among the scheduled ones (its label sets K when it is the newest),
// and takes no log-spaced window from a manual snapshot.
func TestPlanRetention_PinnedScheduledStaysInItsClass(t *testing.T) {
now := retBase.Add(30 * 24 * time.Hour)
newest := snapAt("sched-pinned", now.Add(-10*time.Minute), SnapshotClassScheduled, now.Add(24*time.Hour), map[string]string{LabelScheduleKeep: "2"})
snaps := []SnapshotInfo{
newest,
snapAt("sched-1", now.Add(-24*time.Hour), SnapshotClassScheduled, time.Time{}, map[string]string{LabelScheduleKeep: "9"}),
snapAt("sched-2", now.Add(-48*time.Hour), SnapshotClassScheduled, time.Time{}, map[string]string{LabelScheduleKeep: "9"}),
snapAt("manual", now.Add(-20*time.Minute), "", time.Time{}, nil), // same hourly window as the pinned scheduled one
}
k := kept(planRetention(RetentionPolicy{KeepHourly: 1}, snaps, now))
if len(k) != 3 || k["sched-pinned"] == nil || k["sched-1"] == nil || k["manual"] == nil {
t.Fatalf("kept %v; want sched-pinned (pin, K=2 from its label), sched-1 (second newest scheduled) and manual (its hourly window)", k)
}
}
@@ -11,10 +11,10 @@ import (
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// ErrNotSingleFiler: block metadata needs exactly one filer behind the
@@ -147,7 +147,7 @@ func (c *SWFS) isTarget(ctx context.Context, listed string) bool {
}
func listFilers(ctx context.Context, addr, group string) ([]string, error) {
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(addr)
if err != nil {
return nil, err
}
@@ -12,10 +12,10 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// SWFSConfig configures the minimal SeaweedFS client.
@@ -56,8 +56,7 @@ func DialSWFS(cfg SWFSConfig) (*SWFS, error) {
if cfg.HTTPTimeout == 0 {
cfg.HTTPTimeout = 60 * time.Second
}
conn, err := grpc.NewClient(cfg.FilerGRPC,
grpc.WithTransportCredentials(insecure.NewCredentials()),
conn, err := link.Dial(cfg.FilerGRPC,
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(64<<20), grpc.MaxCallSendMsgSize(64<<20)))
if err != nil {
return nil, fmt.Errorf("chunkstore: dial filer %s: %w", cfg.FilerGRPC, err)
@@ -0,0 +1,222 @@
package durable
// The scheduled-snapshot loop on virtual time (testing/synctest): the
// bubble's clock is the monotonic clock the schedule runs on.
import (
"context"
"errors"
"sync/atomic"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// snapStubLayer is an attached, unfenced layer with no absent chunks.
type snapStubLayer struct{ storage.ChunkLayer }
func (snapStubLayer) Fenced() bool { return false }
func (snapStubLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{} }
// snapLoop sets up volume v1's scheduled-snapshot loop (period one day) in
// the current bubble; take runs each attempt. start arms the loop; stop
// stops it and reports whether it was joined within an hour of virtual
// time.
func snapLoop(take func(context.Context) error) (h *volHandle, start func(), stop func() bool) {
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1}
layer := &snapStubLayer{}
h = &volHandle{chunk: layer, chunkLineage: chunkLineage{"v1", "r1", 3, 1}}
p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id},
cfg: ProviderConfig{ChunkSnapshotPeriod: 24 * time.Hour,
ChunkScheduledSnapshot: func(ctx context.Context, _ string, _ time.Time, _ func(context.Context) (storage.ChunkHead, error)) error {
return take(ctx)
}}}
start = func() {
p.mu.Lock()
p.startChunkLoop("v1", h, layer)
p.mu.Unlock()
}
stop = func() bool {
done := make(chan struct{})
go func() { p.stopChunkLoop(h); close(done) }()
select {
case <-done:
return true
case <-time.After(time.Hour):
return false
}
}
return h, start, stop
}
// recv waits for ch for at most an hour of virtual time.
func recv(t *testing.T, ch <-chan struct{}, what string) {
t.Helper()
select {
case <-ch:
case <-time.After(time.Hour):
t.Fatalf("%s did not happen", what)
}
}
// The first attempt is at the start plus the volume's offset and the next
// one a period later, both on the monotonic clock.
func TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
var calls atomic.Int64
h, start, stop := snapLoop(func(context.Context) error { calls.Add(1); return nil })
begin := time.Now()
start()
defer func() {
if !stop() {
t.Error("the loop was not joined")
}
}()
first := h.snapshots.due()
if off := first.Sub(begin); off < 0 || off >= 24*time.Hour {
t.Fatalf("first slot %v after the start; want within one period", off)
}
time.Sleep(time.Until(first) - time.Second)
synctest.Wait()
if calls.Load() != 0 {
t.Fatal("an attempt ran before its slot")
}
time.Sleep(2 * time.Second)
synctest.Wait()
if calls.Load() != 1 {
t.Fatalf("%d attempts at the first slot; want 1", calls.Load())
}
if next := h.snapshots.due(); next.Sub(first) != 24*time.Hour {
t.Fatalf("next slot %v after the first; want one period", next.Sub(first))
}
time.Sleep(24 * time.Hour)
synctest.Wait()
if calls.Load() != 2 {
t.Fatalf("%d attempts after one period; want 2", calls.Load())
}
})
}
// A re-armed loop (stopped and started again on the same handle, as after
// a refused detach) keeps the volume's schedule: the failure, its count and
// its retry time survive, and the retry runs at that time.
func TestScheduledSnapshotLoop_RearmKeepsTheSchedule(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
var calls atomic.Int64
h, start, stop := snapLoop(func(context.Context) error {
calls.Add(1)
return &SnapshotFailure{Code: "remote_unavailable"}
})
start()
running := true
defer func() { // registered before any check: whichever loop runs is joined
if running && !stop() {
t.Error("the loop was not joined")
}
}()
time.Sleep(time.Until(h.snapshots.due()) + time.Second)
synctest.Wait()
slot, retry := h.snapshots, h.snapshots.due()
if st := slot.status(time.Now()); st.Attempts != 1 || st.LastFailure == nil {
t.Fatalf("after the first attempt: %+v; want one failure", st)
}
running = false
if !stop() {
t.Fatal("the loop was not joined")
}
start()
running = true
if h.snapshots != slot || h.snapshots.due() != retry || slot.status(time.Now()).Attempts != 1 {
t.Fatalf("after re-arm: same schedule %v, due %v (want %v), %+v", h.snapshots == slot, h.snapshots.due(), retry, slot.status(time.Now()))
}
time.Sleep(time.Until(retry) + time.Second)
synctest.Wait()
if calls.Load() != 2 || slot.status(time.Now()).Attempts != 2 {
t.Fatalf("%d attempts after the retry time; want the re-armed loop to retry once", calls.Load())
}
})
}
// INV-MAINT-JOIN for the scheduled-snapshot worker: stopping the loop
// cancels an attempt in flight (the attempt observes the cancellation) and
// returns only after the attempt has returned. The attempt is released
// before the loop is joined, whatever the outcome.
func TestScheduledSnapshotLoop_StopJoinsTheAttempt(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
entered, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{})
h, start, stop := snapLoop(func(ctx context.Context) error {
close(entered)
<-ctx.Done()
close(cancelled)
<-release // returns only when the test allows it
return errors.New("stopped")
})
start()
joined := make(chan bool, 1)
stopStarted := false
var released atomic.Bool
free := func() {
if released.CompareAndSwap(false, true) {
close(release)
}
}
// Registered before any check, run last: release the attempt, then
// join the stop (bounded), starting it if the test never did.
defer func() {
free()
if !stopStarted {
joined <- stop()
}
select {
case ok := <-joined:
if !ok {
t.Error("stop was not joined after the attempt returned")
}
case <-time.After(2 * time.Hour):
t.Error("stop did not return")
}
}()
time.Sleep(time.Until(h.snapshots.due()) + time.Second)
recv(t, entered, "the attempt")
stopStarted = true
go func() { joined <- stop() }()
recv(t, cancelled, "the attempt seeing the cancellation")
synctest.Wait()
select {
case ok := <-joined:
joined <- ok // leave it for the deferred join
t.Fatal("stop returned while the attempt was still running")
default:
}
free()
})
}
// With every attempt failing, the schedule is overdue once no success
// came within one period plus the retry cap from the start; never before.
func TestScheduledSnapshotLoop_OverdueWithNoSuccess(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
h, start, stop := snapLoop(func(context.Context) error { return &SnapshotFailure{Code: "remote_unavailable"} })
begin := time.Now()
start()
defer func() {
if !stop() {
t.Error("the loop was not joined")
}
}()
limit := 24*time.Hour + snapshotRetryMax
time.Sleep(time.Until(begin.Add(limit)))
synctest.Wait()
if st := h.snapshots.status(time.Now()); st.Overdue || st.LastOkNs != 0 {
t.Fatalf("at one period plus the retry cap: %+v; want not yet overdue", st)
}
time.Sleep(time.Minute)
synctest.Wait()
if st := h.snapshots.status(time.Now()); !st.Overdue || st.LastFailure == nil {
t.Fatalf("past one period plus the retry cap with only failures: %+v; want overdue with the failure", st)
}
})
}
@@ -0,0 +1,248 @@
package durable
import (
"context"
"errors"
"log"
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/hostlimit"
"github.com/seaweedfs/seaweed-block/core/storage"
)
const (
// snapshotRetryMin and snapshotRetryMax bound the backoff after a
// failed scheduled snapshot: it doubles from the minimum up to the cap.
snapshotRetryMin = time.Minute
snapshotRetryMax = time.Hour
)
// SnapshotSkipRestoring is the skip reason of a volume still fetching the
// chunks its HEAD names (a restore's hydration).
const SnapshotSkipRestoring = "restoring"
// SnapshotSkip is returned by a scheduled snapshot that was not attempted
// (for example, the volume is restoring). It is counted by Reason and not
// treated as a failure.
type SnapshotSkip struct{ Reason string }
func (s *SnapshotSkip) Error() string { return "durable: scheduled snapshot skipped: " + s.Reason }
// SnapshotFailure is a failed scheduled snapshot with its typed code.
type SnapshotFailure struct {
Code string
Err error
}
func (f *SnapshotFailure) Error() string {
if f.Err != nil {
return "durable: scheduled snapshot failed: " + f.Code + ": " + f.Err.Error()
}
return "durable: scheduled snapshot failed: " + f.Code
}
func (f *SnapshotFailure) Unwrap() error { return f.Err }
// ScheduledSnapshotFailure is the last failed attempt.
type ScheduledSnapshotFailure struct {
// Code is the failure's code, as the control endpoint reports it.
Code string `json:"code"`
// AtNs is when the attempt failed.
AtNs int64 `json:"atNs"`
}
// ScheduledSnapshotStatus is one volume's scheduled-snapshot state.
type ScheduledSnapshotStatus struct {
// PeriodNs is the schedule period; zero means off.
PeriodNs int64 `json:"periodNs"`
// LastOkNs is when the last scheduled snapshot succeeded; zero: none
// since the schedule started.
LastOkNs int64 `json:"lastOkNs"`
// NextDueNs is when the next attempt is due.
NextDueNs int64 `json:"nextDueNs"`
// LastFailure is the last failed attempt since the last success.
LastFailure *ScheduledSnapshotFailure `json:"lastFailure,omitempty"`
// Attempts counts the failed attempts since the last success.
Attempts int `json:"attempts"`
// Skipped counts attempts not made, by reason.
Skipped map[string]int64 `json:"skipped,omitempty"`
// Overdue reports that no scheduled snapshot succeeded within one
// period plus the retry cap, counted from the last success or, before
// any, from the start of the schedule.
Overdue bool `json:"snapshot_overdue"`
}
// snapshotSchedule decides when one volume's scheduled snapshot is due and
// records the outcome of each attempt, on this process's monotonic time
// (every time in it is a time.Now() reading or derived from one), so
// wall-clock steps move nothing. Slots are the start plus the volume's
// offset (spread over the whole period) plus whole periods: "daily" is
// once per 24 h at a per-volume offset, not at a wall-clock hour. A
// restart starts a fresh schedule. It is not safe for concurrent use.
type snapshotSchedule struct {
period time.Duration
origin time.Time // the first slot: the start plus the volume's offset
started time.Time
lastOK time.Time
next time.Time
failure *ScheduledSnapshotFailure
attempts int
skipped map[string]int64
}
// newSnapshotSchedule starts vol's schedule at now, a time.Now() reading.
func newSnapshotSchedule(vol string, period time.Duration, now time.Time) *snapshotSchedule {
s := &snapshotSchedule{period: period, origin: now.Add(hostlimit.Phase(vol+":snapshot", period)), started: now, skipped: map[string]int64{}}
s.next = s.origin
return s
}
// slotAfter returns the first slot strictly after t: the origin plus a
// whole number of periods.
func (s *snapshotSchedule) slotAfter(t time.Time) time.Time {
if t.Before(s.origin) {
return s.origin
}
return s.origin.Add((t.Sub(s.origin)/s.period + 1) * s.period)
}
// due returns when the next attempt is due.
func (s *snapshotSchedule) due() time.Time { return s.next }
// record records the outcome of an attempt made at now: nil is a
// success (the next attempt is the next slot); a *SnapshotSkip is counted
// by reason and retried after the backoff cap; any other error is a
// failure, recorded with its code, and retried with a doubling backoff.
func (s *snapshotSchedule) record(now time.Time, err error) {
var skip *SnapshotSkip
switch {
case err == nil:
s.lastOK, s.failure, s.attempts = now, nil, 0
s.next = s.slotAfter(now)
case errors.As(err, &skip):
s.skipped[skip.Reason]++
s.next = earlier(now.Add(snapshotRetryMax), s.slotAfter(now))
default:
s.attempts++
s.failure = &ScheduledSnapshotFailure{Code: snapshotFailureCode(err), AtNs: now.UnixNano()}
backoff := snapshotRetryMin << min(s.attempts-1, 30)
if backoff > snapshotRetryMax || backoff <= 0 {
backoff = snapshotRetryMax
}
s.next = now.Add(backoff)
}
}
// status returns the schedule's state at now.
func (s *snapshotSchedule) status(now time.Time) ScheduledSnapshotStatus {
from := s.started
if !s.lastOK.IsZero() {
from = s.lastOK
}
st := ScheduledSnapshotStatus{PeriodNs: int64(s.period), NextDueNs: s.next.UnixNano(), Attempts: s.attempts,
Overdue: now.Sub(from) > s.period+snapshotRetryMax}
if !s.lastOK.IsZero() {
st.LastOkNs = s.lastOK.UnixNano()
}
if s.failure != nil {
f := *s.failure
st.LastFailure = &f
}
if len(s.skipped) > 0 {
st.Skipped = make(map[string]int64, len(s.skipped))
for k, v := range s.skipped {
st.Skipped[k] = v
}
}
return st
}
// snapshotFailureCode is a failure's typed code: a SnapshotFailure's own
// code, else "unknown".
func snapshotFailureCode(err error) string {
var f *SnapshotFailure
if errors.As(err, &f) && f.Code != "" {
return f.Code
}
return "unknown"
}
func earlier(a, b time.Time) time.Time {
if a.Before(b) {
return a
}
return b
}
// snapshotSlot guards one running loop's schedule: the loop records
// outcomes, status readers read it.
type snapshotSlot struct {
mu sync.Mutex
s *snapshotSchedule
}
func (sl *snapshotSlot) status(now time.Time) ScheduledSnapshotStatus {
sl.mu.Lock()
defer sl.mu.Unlock()
return sl.s.status(now)
}
func (sl *snapshotSlot) due() time.Time {
sl.mu.Lock()
defer sl.mu.Unlock()
return sl.s.due()
}
func (sl *snapshotSlot) record(now time.Time, err error) {
sl.mu.Lock()
defer sl.mu.Unlock()
sl.s.record(now, err)
}
// chunkSnapshotLoop takes volumeID's scheduled snapshots while the
// attachment is current, on this process's monotonic time. A restoring
// volume is skipped. Each attempt is one bounded pass: one urgent cut and
// the snapshot record. An attempt cut short by the loop's own end is not
// recorded. chunkBackground joins it with its other workers
// (INV-MAINT-JOIN).
func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, slot *snapshotSlot) {
timer := time.NewTimer(time.Until(slot.due()))
defer timer.Stop()
timeout := 2 * p.cfg.ChunkCutTimeout
if timeout <= 0 {
timeout = 10 * time.Minute
}
cut := func(ctx context.Context) (storage.ChunkHead, error) {
r, err := p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0)
return r.Head, err
}
for {
select {
case <-ctx.Done():
return
case <-timer.C:
}
if ctx.Err() != nil || layer.Fenced() || !current() {
return
}
at := time.Now()
var err error
if layer.Stats().AbsentChunks > 0 {
// Restoring: HEAD names chunks this volume has not fetched yet.
err = &SnapshotSkip{Reason: SnapshotSkipRestoring}
} else {
err = boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error {
return p.cfg.ChunkScheduledSnapshot(passCtx, volumeID, at, cut)
})
}
if ctx.Err() != nil {
return
}
slot.record(time.Now(), err)
if err != nil {
log.Printf("durable: scheduled snapshot volume=%s: %v (next attempt in %s)", volumeID, err, time.Until(slot.due()).Round(time.Second))
}
timer.Reset(time.Until(slot.due()))
}
}
@@ -0,0 +1,109 @@
package durable
import (
"errors"
"testing"
"time"
)
var schedT0 = time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC)
// The first slot is the start plus the volume's offset, which lies within
// one period and differs between volumes; after a success the next slot is
// one period later, and a slot is never in the past.
func TestSnapshotSchedule_SlotsAreOffsetPerVolume(t *testing.T) {
day := 24 * time.Hour
offsets := map[time.Duration]bool{}
for _, vol := range []string{"v1", "v2", "v3", "a-much-longer-volume-name"} {
s := newSnapshotSchedule(vol, day, schedT0)
due := s.due()
off := due.Sub(schedT0)
if off < 0 || off >= day {
t.Fatalf("%s: first slot %v after the start, want within one period", vol, off)
}
offsets[off] = true
s.record(due, nil)
if s.due().Sub(due) != day {
t.Fatalf("%s: after a success the next slot is %v later; want one period", vol, s.due().Sub(due))
}
late := due.Add(3*day + time.Hour) // an attempt that ran very late
s.record(late, nil)
if next := s.due(); !next.After(late) || next.Sub(late) > day || next.Sub(due)%day != 0 {
t.Fatalf("%s: after a late success the next slot is %v; want the first slot after it", vol, next)
}
}
if len(offsets) < 2 {
t.Fatalf("every volume got the same offset %v", offsets)
}
}
// A restoring volume is skipped, counted by reason, and not treated as a
// failure; it is retried within the backoff cap, not a whole period later.
func TestSnapshotSchedule_RestoringIsSkippedAndCounted(t *testing.T) {
s := newSnapshotSchedule("v1", 24*time.Hour, schedT0)
at := s.due()
s.record(at, &SnapshotSkip{Reason: "restoring"})
s.record(s.due(), &SnapshotSkip{Reason: "restoring"})
st := s.status(s.due())
if st.Skipped["restoring"] != 2 || st.Attempts != 0 || st.LastFailure != nil {
t.Fatalf("status %+v; want 2 restoring skips, no failure", st)
}
if gap := s.due().Sub(at); gap > 2*snapshotRetryMax {
t.Fatalf("after two skips the next attempt is %v later; want within the backoff cap", gap)
}
}
// A failure is recorded with its typed code and retried after a backoff
// that doubles from one minute up to one hour; a success clears it and
// schedules the next slot.
func TestSnapshotSchedule_FailureIsTypedAndBacksOff(t *testing.T) {
s := newSnapshotSchedule("v1", 24*time.Hour, schedT0)
now := s.due()
want := []time.Duration{time.Minute, 2 * time.Minute, 4 * time.Minute, 8 * time.Minute, 16 * time.Minute, 32 * time.Minute, time.Hour, time.Hour}
for i, w := range want {
s.record(now, &SnapshotFailure{Code: "remote_unavailable", Err: errors.New("filer down")})
if got := s.due().Sub(now); got != w {
t.Fatalf("after failure %d the retry is %v later; want %v", i+1, got, w)
}
now = s.due()
}
st := s.status(now)
if st.Attempts != len(want) || st.LastFailure == nil || st.LastFailure.Code != "remote_unavailable" {
t.Fatalf("status %+v; want %d attempts and code remote_unavailable", st, len(want))
}
s.record(now, errors.New("untyped"))
if st := s.status(now); st.LastFailure.Code != "unknown" {
t.Fatalf("untyped failure code %q; want unknown", st.LastFailure.Code)
}
s.record(now, nil)
st = s.status(now)
if st.Attempts != 0 || st.LastFailure != nil || st.LastOkNs != now.UnixNano() {
t.Fatalf("after a success: %+v; want the failure cleared and lastOk set", st)
}
if next := s.due(); !next.After(now) || next.Sub(now) > 24*time.Hour || next.Sub(s.origin)%(24*time.Hour) != 0 {
t.Fatalf("after a success the next attempt is %v; want the next slot", next)
}
}
// The schedule is overdue once no scheduled snapshot succeeded within one
// period plus the retry cap: counted from the start before any success,
// then from the last success; the failure stays visible.
func TestSnapshotSchedule_OverdueAfterPeriodPlusRetryCap(t *testing.T) {
day, grace := 24*time.Hour, snapshotRetryMax
s := newSnapshotSchedule("v1", day, schedT0)
if s.status(schedT0.Add(day + grace)).Overdue {
t.Fatal("overdue at exactly one period plus the retry cap")
}
if !s.status(schedT0.Add(day + grace + time.Second)).Overdue {
t.Fatal("not overdue past one period plus the retry cap with no success")
}
ok := schedT0.Add(day)
s.record(ok, nil)
if s.status(ok.Add(day + grace)).Overdue {
t.Fatal("overdue within one period plus the retry cap of a success")
}
s.record(ok.Add(day), &SnapshotFailure{Code: "outcome_unknown"})
if st := s.status(ok.Add(day + grace + time.Second)); !st.Overdue || st.LastFailure.Code != "outcome_unknown" {
t.Fatalf("status %+v; want overdue with the failure visible", st)
}
}
@@ -37,21 +37,21 @@ func TestCutPolicy_OnlyTheTimerTriggers(t *testing.T) {
func TestCutPolicy_AnySuccessfulCutResetsTheTimer(t *testing.T) {
pol := testPolicy()
s := cutSchedule{lastSuccess: t0}
// An explicit Cut, Snapshot or Detach succeeded at 20 s: the layer
// reports it and the timer restarts from there.
s = s.observe(at(20 * time.Second).UnixNano())
// An explicit Cut, Snapshot or Detach succeeded; the loop sees the
// layer's new LastCutNs at 20 s and the timer restarts from there.
s = s.observe(101, at(20*time.Second))
if r, ok := pol.dueNR(s, at(45*time.Second)); ok {
t.Fatalf("due (%s) 25 s after an explicit cut", r)
}
if _, ok := pol.dueNR(s, at(50*time.Second)); !ok {
t.Fatal("not due 30 s after the explicit cut")
}
// An older report never moves the timer back.
if got := s.observe(at(5 * time.Second).UnixNano()); !got.lastSuccess.Equal(at(20 * time.Second)) {
t.Fatalf("older report moved the timer to %v", got.lastSuccess)
// The same report seen again does not move the timer.
if got := s.observe(101, at(40*time.Second)); !got.lastSuccess.Equal(at(20 * time.Second)) {
t.Fatalf("a repeated report moved the timer to %v", got.lastSuccess)
}
// An automatic success restarts it too.
s = pol.after(s, at(50*time.Second), at(50*time.Second+200*time.Millisecond), nil)
s = pol.after(s, at(50*time.Second), at(50*time.Second+200*time.Millisecond), nil, 102)
if _, ok := pol.dueNR(s, at(79*time.Second)); ok {
t.Fatal("due less than 30 s after an automatic success")
}
@@ -61,7 +61,7 @@ func TestCutPolicy_MinimumSpacingBetweenAutomaticCuts(t *testing.T) {
pol := testPolicy()
pol.interval = 500 * time.Millisecond
s := cutSchedule{lastSuccess: t0}
s = pol.after(s, at(10*time.Second), at(10*time.Second+50*time.Millisecond), nil)
s = pol.after(s, at(10*time.Second), at(10*time.Second+50*time.Millisecond), nil, 101)
if r, ok := pol.dueNR(s, at(10*time.Second+900*time.Millisecond)); ok {
t.Fatalf("automatic cut again after 0.9 s (%s)", r)
}
@@ -77,7 +77,7 @@ func TestCutPolicy_FailureBacksOffAndResetsNothing(t *testing.T) {
now := at(30 * time.Second)
var waits []time.Duration
for i := 0; i < 7; i++ {
s = pol.after(s, now, now, fail)
s = pol.after(s, now, now, fail, 0)
waits = append(waits, s.backoff)
if _, ok := pol.dueNR(s, now.Add(s.backoff-time.Millisecond)); ok {
t.Fatalf("retry %d due before its backoff %s", i, s.backoff)
@@ -96,7 +96,7 @@ func TestCutPolicy_FailureBacksOffAndResetsNothing(t *testing.T) {
if !s.lastSuccess.Equal(t0) {
t.Fatalf("a failure moved the last success to %v", s.lastSuccess)
}
s = pol.after(s, now, now, nil)
s = pol.after(s, now, now, nil, 101)
if s.backoff != 0 || !s.retryAt.IsZero() || !s.lastSuccess.Equal(now) {
t.Fatalf("success did not clear the backoff: %+v", s)
}
@@ -112,12 +112,12 @@ func TestCutPolicy_ExplicitSuccessClearsFailedAutoBackoff(t *testing.T) {
fail := errors.New("remote unavailable")
now := at(time.Second)
for s.backoff < pol.backoffMax {
s = pol.after(s, now, now, fail)
s = pol.after(s, now, now, fail, 100)
now = now.Add(time.Millisecond)
}
retryAt := s.retryAt
explicit := now.Add(2 * time.Second) // well before retryAt (30 s away)
s = s.observe(explicit.UnixNano())
s = s.observe(200, explicit)
next := explicit.Add(pol.interval)
if !next.Before(retryAt) {
t.Fatalf("test setup: next timer cut %v not before the old retry %v", next, retryAt)
@@ -128,12 +128,13 @@ func TestCutPolicy_ExplicitSuccessClearsFailedAutoBackoff(t *testing.T) {
if r, ok := pol.dueNR(s, next); !ok || r != "periodic" {
t.Fatalf("one interval after the explicit success: %q %v; want periodic (backoff %s, retry at %v)", r, ok, s.backoff, s.retryAt)
}
// A success older than the failure leaves the backoff in force.
s2 := cutSchedule{lastSuccess: t0}
s2 = pol.after(s2, at(10*time.Second), at(10*time.Second), fail)
s2 = s2.observe(at(5 * time.Second).UnixNano())
// The cut the failure already saw (it completed before the failure)
// leaves the backoff in force.
s2 := cutSchedule{lastSuccess: t0, seenSeq: 90}
s2 = pol.after(s2, at(10*time.Second), at(10*time.Second), fail, 100)
s2 = s2.observe(100, at(11*time.Second))
if s2.retryAt.IsZero() {
t.Fatal("a success older than the failure cleared its backoff")
t.Fatal("a success the failure already saw cleared its backoff")
}
}
@@ -159,7 +160,7 @@ func TestCutPolicy_NothingDueWhileReconciling(t *testing.T) {
func TestCutPolicy_StaggerPreservesExplicitTimerReset(t *testing.T) {
pol := testPolicy()
s := initialCutSchedule("v1", pol.interval, t0, true)
s := initialCutSchedule("v1", pol.interval, t0, true, 0)
if !s.lastSuccess.Equal(t0) || !s.firstDue.After(t0) || s.firstDue.After(t0.Add(pol.interval)) {
t.Fatal("phase fabricated success or exceeded first period", s)
}
@@ -170,7 +171,7 @@ func TestCutPolicy_StaggerPreservesExplicitTimerReset(t *testing.T) {
t.Fatal("first phased cut not due")
}
explicit := t0.Add(s.firstDue.Sub(t0) / 2)
s = s.observe(explicit.UnixNano())
s = s.observe(5, explicit)
if !s.lastSuccess.Equal(explicit) || !s.firstDue.IsZero() {
t.Fatal("stagger hid explicit success", s)
}
@@ -181,3 +182,27 @@ func TestCutPolicy_StaggerPreservesExplicitTimerReset(t *testing.T) {
t.Fatal("explicit success did not restart timer")
}
}
// The timer runs on this process's monotonic time and keys on the layer's
// CutSeq, never on a cut's wall stamp: a cut seen for the first time is a
// success at the moment it is observed, so the next timer cut is one
// interval after the observation; at start the layer's existing CutSeq is
// not new, so the startup phase stands.
func TestCutPolicy_TimerRunsOnObservationTime(t *testing.T) {
pol := testPolicy()
seen := at(20 * time.Second)
s := cutSchedule{lastSuccess: t0}.observe(1, seen)
if !s.lastSuccess.Equal(seen) {
t.Fatalf("last success %v; want the observation time %v", s.lastSuccess, seen)
}
if _, ok := pol.dueNR(s, seen.Add(pol.interval-time.Nanosecond)); ok {
t.Fatal("due before one interval after the observation")
}
if _, ok := pol.dueNR(s, seen.Add(pol.interval)); !ok {
t.Fatal("not due one interval after the observation")
}
restart := initialCutSchedule("v1", pol.interval, t0, true, 7)
if got := restart.observe(7, at(time.Second)); got.firstDue.IsZero() || !got.lastSuccess.Equal(t0) {
t.Fatalf("the cut existing at start was taken in as new: %+v", got)
}
}
@@ -13,7 +13,7 @@ func TestMaintenanceVolumePhasesDoNotAlign(t *testing.T) {
interval := 15 * time.Minute
seen := map[time.Duration]bool{}
for i := 0; i < 200; i++ {
s := initialCutSchedule(fmt.Sprintf("volume-%d", i), interval, t0, true)
s := initialCutSchedule(fmt.Sprintf("volume-%d", i), interval, t0, true, 0)
offset := s.firstDue.Sub(t0)
if offset <= 0 || offset >= interval {
t.Fatalf("phase outside interval: %s", offset)
@@ -7,14 +7,17 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend"
)
// TestPlainDetachStopRefusesClosedBackend pins that the plain-detach stop of a
// closed backend returns ErrBackendClosed instead of reporting a clean stop.
func TestPlainDetachStopRefusesClosedBackend(t *testing.T) {
// M5 PlainStop -> Quiesce permits a closed idle handle to seal, while the
// frontend remains closed to guest I/O even if the offline attempt aborts.
func TestPlainDetachStopAcceptsClosedIdleBackend(t *testing.T) {
b := precopyTestBackend(newHeldReadStore())
if err := b.Close(); err != nil {
t.Fatal(err)
}
if err := b.stopPlainDetachIfIdle(); !errors.Is(err, frontend.ErrBackendClosed) {
t.Fatalf("plain-detach stop of a closed backend: %v", err)
if err := b.stopPlainDetachIfIdle(); err != nil {
t.Fatalf("closed idle backend cannot seal: %v", err)
}
if err := b.readyCheck(); !errors.Is(err, frontend.ErrBackendClosed) {
t.Fatalf("offline admission reopened frontend: %v", err)
}
}
@@ -179,6 +179,14 @@ type ProviderConfig struct {
ChunkMaintenanceInterval time.Duration
ChunkMaintenanceTimeout time.Duration
ChunkMaintenance func(context.Context, string) error
// ChunkSnapshotPeriod schedules a named snapshot of each attached
// healthy volume once per period, at a per-volume offset (zero
// disables it). ChunkScheduledSnapshot takes one: it cuts through cut
// (one urgent cut) and records the snapshot of the HEAD cut returns. A
// *SnapshotSkip skips the attempt, counted by reason; a
// *SnapshotFailure carries the failure's code.
ChunkSnapshotPeriod time.Duration
ChunkScheduledSnapshot func(ctx context.Context, volumeID string, at time.Time, cut func(context.Context) (storage.ChunkHead, error)) error
// DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest
// I/O stopped before it resumes or settles: the drain and final cut get
// three quarters of it, the settlement of a failed cut the rest (the
@@ -288,6 +296,9 @@ type volHandle struct {
chunkDetach bool
chunkStop context.CancelFunc
chunkDone chan struct{}
// snapshots is the scheduled-snapshot state of the running loop, nil
// when the schedule is off.
snapshots *snapshotSlot
}
// VolumeStatus is a read-only diagnostic snapshot of one durable volume
@@ -325,12 +336,13 @@ type VolumeStatus struct {
// AwaitingAuthority: recovered, the layer waits for master authority to
// attach. Stats is zero until the layer is attached.
type ChunkStatus struct {
Attached bool // the chunk layer is attached to the remote
AwaitingAuthority bool // recovered; the layer waits for master authority to attach
Fenced bool // a newer holder fenced this layer: it publishes nothing
RemoteLSN uint64 // the LSN of the remote HEAD (what the remote holds durably)
Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached
HostBudget any `json:",omitempty"` // the host background-cut budget state, with --host-limit-dir
Attached bool // the chunk layer is attached to the remote
AwaitingAuthority bool // recovered; the layer waits for master authority to attach
Fenced bool // a newer holder fenced this layer: it publishes nothing
RemoteLSN uint64 // the LSN of the remote HEAD (what the remote holds durably)
Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached
HostBudget any `json:",omitempty"` // the host background-cut budget state, with --host-limit-dir
ScheduledSnapshot *ScheduledSnapshotStatus `json:",omitempty"` // the scheduled-snapshot state; absent when the schedule is off or its loop has not started
}
// NewDurableProvider constructs a provider. view is the ONLY
@@ -353,6 +365,9 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura
if cfg.ChunkMaintenanceInterval > 0 && cfg.ChunkMaintenance == nil {
return nil, fmt.Errorf("durable: chunk maintenance interval requires its callback")
}
if cfg.ChunkSnapshotPeriod < 0 || (cfg.ChunkSnapshotPeriod > 0 && cfg.ChunkScheduledSnapshot == nil) {
return nil, fmt.Errorf("durable: a chunk snapshot period must not be negative and requires its callback")
}
if cfg.ChunkBlocks == 0 {
cfg.ChunkBlocks = defaultChunkBlocks
}
@@ -581,8 +596,9 @@ func durableIdentityConflict(got, want frontend.Identity) error {
// durable lineage latching without scraping logs.
func (p *DurableProvider) DurableStatuses() []VolumeStatus {
type chunkView struct {
layer storage.ChunkLayer
awaiting bool
layer storage.ChunkLayer
awaiting bool
snapshots *snapshotSlot
}
p.mu.Lock()
handles := make(map[string]*volHandle, len(p.volumes))
@@ -590,7 +606,7 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus {
for volumeID, h := range p.volumes {
handles[volumeID] = h
if p.cfg.Impl == ImplWALStoreChunk {
chunks[volumeID] = chunkView{layer: h.chunk, awaiting: h.waitGen != 0}
chunks[volumeID] = chunkView{layer: h.chunk, awaiting: h.waitGen != 0, snapshots: h.snapshots}
}
}
p.mu.Unlock()
@@ -606,6 +622,10 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus {
if budget, ok := p.cfg.ChunkBudget.(interface{ Snapshot() any }); ok {
cs.HostBudget = budget.Snapshot()
}
if cv.snapshots != nil {
ss := cv.snapshots.status(time.Now())
cs.ScheduledSnapshot = &ss
}
st.Chunk = cs
}
out = append(out, st)
@@ -320,14 +320,22 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v
// startChunkLoop starts the periodic cuts of an attached layer, if configured
// and not already running. The caller holds h.attachMu and p.mu.
func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) {
if (p.cfg.ChunkCaptureInterval <= 0 && (p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil)) || h.chunkStop != nil {
snapshotsOn := p.cfg.ChunkSnapshotPeriod > 0 && p.cfg.ChunkScheduledSnapshot != nil
if (p.cfg.ChunkCaptureInterval <= 0 && (p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil) && !snapshotsOn) || h.chunkStop != nil {
return
}
loopCtx, cancel := context.WithCancel(context.Background())
h.chunkStop, h.chunkDone = cancel, make(chan struct{})
// A re-armed loop (for example after a refused detach) keeps the
// volume's schedule: its slots, retries and history.
if !snapshotsOn {
h.snapshots = nil
} else if h.snapshots == nil {
h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, time.Now())}
}
lin := h.chunkLineage
current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) }
go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current)
go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current, h.snapshots)
}
func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) {
@@ -657,28 +665,36 @@ type cutPolicy struct {
interval, minSpacing, backoffMin, backoffMax time.Duration
}
// cutSchedule runs on in-process monotonic time: every time in it is a
// time.Now() reading of this process (or derived from one), never the
// layer's persisted LastCutNs, so wall-clock steps move nothing and a
// restart starts a fresh schedule. The layer's CutSeq identifies the
// latest cut: a value not seen before is a new successful cut.
type cutSchedule struct {
lastSuccess time.Time // last successful cut of any kind
lastAuto time.Time // start of the last automatic cut
failedAt time.Time // end of the last failed automatic cut
retryAt time.Time // a failed automatic cut's backoff ends here
backoff time.Duration
firstDue time.Time // startup phase only; never a fabricated success
lastSuccess time.Time // last successful cut of any kind, as observed here
lastAuto time.Time // start of the last automatic cut
failedAt time.Time // end of the last failed automatic cut
retryAt time.Time // a failed automatic cut's backoff ends here
backoff time.Duration
firstDue time.Time // startup phase only; never a fabricated success
seenSeq uint64 // the layer's CutSeq last taken in
failedSeenSeq uint64 // the layer's CutSeq when the last automatic cut failed
}
// observe takes in a successful cut the layer reports (any trigger). A
// success after the last failed automatic cut makes that failure's
// backoff obsolete.
func (s cutSchedule) observe(lastCutNs int64) cutSchedule {
if lastCutNs > 0 {
c := time.Unix(0, lastCutNs)
if c.After(s.lastSuccess) {
s.lastSuccess = c
s.firstDue = time.Time{}
}
if !s.failedAt.IsZero() && c.After(s.failedAt) {
s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{}
}
// observe takes in, at now, the latest cut the layer reports (any
// trigger): a CutSeq not seen before is a success at now. A cut other
// than the one the last failure saw makes that failure's backoff obsolete.
func (s cutSchedule) observe(seq uint64, now time.Time) cutSchedule {
if seq == 0 || seq == s.seenSeq {
return s
}
s.seenSeq = seq
if now.After(s.lastSuccess) {
s.lastSuccess = now
}
s.firstDue = time.Time{}
if !s.failedAt.IsZero() && seq != s.failedSeenSeq {
s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{}
}
return s
}
@@ -703,10 +719,12 @@ func (pol cutPolicy) due(s cutSchedule, now time.Time, reconciling bool) (string
return "", false
}
// after records the outcome of an automatic cut started at start.
func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error) cutSchedule {
// after records the outcome of an automatic cut started at start, with
// the layer's CutSeq read after it.
func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, seq uint64) cutSchedule {
s.lastAuto = start
if err == nil {
s.seenSeq = seq
s.firstDue = time.Time{}
s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{}
if end.After(s.lastSuccess) {
@@ -722,12 +740,14 @@ func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error) cutSc
default:
s.backoff *= 2
}
s.failedAt, s.retryAt = end, end.Add(s.backoff)
s.failedAt, s.retryAt, s.failedSeenSeq = end, end.Add(s.backoff), seq
return s
}
func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, stagger bool) cutSchedule {
s := cutSchedule{lastSuccess: now}
// initialCutSchedule starts a fresh schedule at now; seq is the layer's
// CutSeq at start, so a cut already made is not taken in as new.
func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, stagger bool, seq uint64) cutSchedule {
s := cutSchedule{lastSuccess: now, seenSeq: seq}
if stagger && interval > 0 {
phase := hostlimit.Phase(volumeID, interval)
startup := hostlimit.Phase(volumeID+":startup", min(interval, 10*time.Second))
@@ -748,7 +768,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
backoffMin: chunkCutBackoffMin,
backoffMax: chunkCutBackoffMax,
}
s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger)
s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger, layer.Stats().CutSeq)
t := time.NewTicker(chunkSchedulePoll)
defer t.Stop()
for {
@@ -761,8 +781,8 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
return
}
ls := layer.Stats()
s = s.observe(ls.LastCutNs)
start := time.Now()
s = s.observe(ls.CutSeq, start)
reason, ok := pol.due(s, start, ls.Reconciling)
if !ok {
continue
@@ -777,7 +797,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
// A cut that completed after this decision (an explicit one
// running meanwhile) restarted the timer: no cut now.
var skipped bool
_, skipped, err = pc.CutUnlessCutSince(cutCtx, ls.LastCutNs)
_, skipped, err = pc.CutUnlessCutSince(cutCtx, ls.CutSeq)
if trace != nil {
trace("cut", ls.LastCutNs, skipped)
}
@@ -792,7 +812,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
}
}
cancel()
s = pol.after(s, start, time.Now(), err)
s = pol.after(s, start, time.Now(), err, layer.Stats().CutSeq)
if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil {
log.Printf("durable: %s chunk cut for volume=%s: %v (retry in %s)", reason, volumeID, err, s.backoff)
}
@@ -802,7 +822,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
// chunkBackground owns both workers and their cancellation. A fence is observed
// even while either worker is waiting on a cooperative remote call. INV-MAINT-JOIN:
// done closes only after every admitted worker has returned.
func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool) {
func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool, snapshots *snapshotSlot) {
defer close(done)
defer cancel()
var workers sync.WaitGroup
@@ -818,6 +838,10 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca
workers.Add(1)
go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer, current) }()
}
if snapshots != nil {
workers.Add(1)
go func() { defer workers.Done(); p.chunkSnapshotLoop(ctx, volumeID, layer, current, snapshots) }()
}
timer := time.NewTicker(chunkSchedulePoll)
defer timer.Stop()
for ctx.Err() == nil {
@@ -866,29 +890,9 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str
if timeout <= 0 {
timeout = time.Minute
}
passCtx, cancel := context.WithTimeout(ctx, timeout)
// The projection has no change channel. One bounded watcher belongs to
// this pass, never to an individual tick; cancellation is joined below.
watchDone := make(chan struct{})
go func() {
defer close(watchDone)
tick := time.NewTicker(chunkSchedulePoll)
defer tick.Stop()
for {
select {
case <-passCtx.Done():
return
case <-tick.C:
if layer.Fenced() || !current() {
cancel()
return
}
}
}
}()
err := p.cfg.ChunkMaintenance(passCtx, volumeID)
cancel()
<-watchDone
err := boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error {
return p.cfg.ChunkMaintenance(passCtx, volumeID)
})
if err != nil && ctx.Err() == nil {
log.Printf("durable: maintenance volume=%s: %v", volumeID, err)
}
@@ -897,6 +901,35 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str
}
}
// boundedPass runs fn with a context that ends after timeout, or as soon
// as the layer is fenced or the attachment is no longer current. The
// projection has no change channel: one bounded watcher belongs to the
// pass, never to an individual tick, and is joined before return.
func boundedPass(ctx context.Context, layer storage.ChunkLayer, current func() bool, timeout time.Duration, fn func(context.Context) error) error {
passCtx, cancel := context.WithTimeout(ctx, timeout)
watchDone := make(chan struct{})
go func() {
defer close(watchDone)
tick := time.NewTicker(chunkSchedulePoll)
defer tick.Stop()
for {
select {
case <-passCtx.Done():
return
case <-tick.C:
if layer.Fenced() || !current() {
cancel()
return
}
}
}
}()
err := fn(passCtx)
cancel()
<-watchDone
return err
}
func (p *DurableProvider) stopChunkLoop(h *volHandle) {
p.mu.Lock()
stop, done := h.chunkStop, h.chunkDone
@@ -1051,7 +1084,8 @@ func (p *DurableProvider) DetachVolumeFrozen(ctx context.Context, volumeID strin
var ErrPlainDetachBusy = errors.New("durable: plain detach requires idle frontend I/O")
// DetachVolumePlain bypasses pre-copy cost admission only after atomically
// closing an idle frontend. Publication and failure settlement are unchanged.
// closing an idle frontend (including a closed handle). M5 PlainStop -> Quiesce uses
// only the caller context, not the live-serving freeze timer.
func (p *DurableProvider) DetachVolumePlain(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) {
return p.detachVolume(ctx, volumeID, true)
}
@@ -1109,6 +1143,10 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
start = guestFreeze.StartedAt
}
casAtFreeze = countCAS()
if plain { // M5 PlainStop -> Quiesce: no live frontend, caller owns the bound.
settleDeadline, _ = ctx.Deadline()
return
}
operationStart := start
if guestFrozen && guestFreeze.AllowOverBudget {
operationStart = time.Now()
@@ -1125,7 +1163,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
if timer != nil {
timer.Stop()
}
if !start.IsZero() {
if !plain && !start.IsZero() {
if d := time.Since(start); d > detachFreezeTarget {
log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze)
}
@@ -1206,7 +1244,11 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
}
}
if trace := p.testDetachTrace; trace != nil {
trace("cut", start.Add(freeze*3/4))
deadline := start.Add(freeze * 3 / 4)
if plain {
deadline, _ = cutCtx.Deadline()
}
trace("cut", deadline)
}
h.chunkDetach = true
notifyDetach()
@@ -1230,7 +1272,11 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
// resumes: an earlier detach that applied, an unresolved detach CAS or a
// fenced layer must never resume serving. The settlement keeps the rest
// of the freeze budget even when the caller's context is gone.
sctx, scancel := context.WithDeadline(context.WithoutCancel(cutCtx), settleDeadline)
sctx, scancel := context.WithCancel(cutCtx)
if !plain { // Live detach retains its reserved settlement budget.
scancel()
sctx, scancel = context.WithDeadline(context.WithoutCancel(cutCtx), settleDeadline)
}
defer scancel()
if trace := p.testDetachTrace; trace != nil {
dl, _ := sctx.Deadline()
@@ -0,0 +1,188 @@
package durable_test
// The scheduled-snapshot loop through the real provider.
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type snapCalls struct {
mu sync.Mutex
heads []storage.ChunkHead
fail error
}
func (c *snapCalls) take(ctx context.Context, _ string, _ time.Time, cut func(context.Context) (storage.ChunkHead, error)) error {
c.mu.Lock()
fail := c.fail
c.mu.Unlock()
if fail != nil {
return fail
}
h, err := cut(ctx)
if err != nil {
return err
}
c.mu.Lock()
c.heads = append(c.heads, h)
c.mu.Unlock()
return nil
}
func (c *snapCalls) count() int {
c.mu.Lock()
defer c.mu.Unlock()
return len(c.heads)
}
func snapScheduleProvider(t *testing.T, remote storage.ChunkRemote, period time.Duration, calls *snapCalls) *durable.DurableProvider {
t.Helper()
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096,
NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
ChunkSnapshotPeriod: period,
ChunkScheduledSnapshot: calls.take,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
return p
}
func scheduledStatus(t *testing.T, p *durable.DurableProvider) *durable.ScheduledSnapshotStatus {
t.Helper()
for _, st := range p.DurableStatuses() {
if st.VolumeID == "v1" && st.Chunk != nil {
return st.Chunk.ScheduledSnapshot
}
}
return nil
}
func waitFor(t *testing.T, d time.Duration, what string, ok func() bool) {
t.Helper()
deadline := time.Now().Add(d)
for !ok() {
if time.Now().After(deadline) {
t.Fatalf("%s not reached within %v", what, d)
}
time.Sleep(20 * time.Millisecond)
}
}
// With a schedule, the attached volume's snapshot is taken at its slot by
// one cut that publishes the dirty data, the snapshot callback gets that
// cut's HEAD, and the status shows the success and the next slot. A failure
// is visible in the status with its code.
func TestWALStoreChunk_ScheduledSnapshotCutsAndReports(t *testing.T) {
const period = 2 * time.Second
remote := storage.NewMemChunkRemote()
calls := &snapCalls{}
p := snapScheduleProvider(t, remote, period, calls)
s := openRecovered(t, p)
if _, err := s.Write(1, block(0x5A)); err != nil {
t.Fatal(err)
}
waitFor(t, 3*period, "the first scheduled snapshot", func() bool { return calls.count() >= 1 })
calls.mu.Lock()
h := calls.heads[0]
calls.mu.Unlock()
if remoteHead := headGen(t, remote); h.Gen == 0 || h.Gen > remoteHead.Gen || len(h.Chunks) == 0 {
t.Fatalf("snapshot HEAD gen %d with %d chunks (remote gen %d); want the cut that published the write", h.Gen, len(h.Chunks), remoteHead.Gen)
}
waitFor(t, time.Second, "the success in the status", func() bool {
st := scheduledStatus(t, p)
return st != nil && st.LastOkNs > 0
})
st := scheduledStatus(t, p)
if st.PeriodNs != int64(period) || st.NextDueNs <= st.LastOkNs || st.Overdue || st.LastFailure != nil {
t.Fatalf("status %+v; want period %v, next slot after the success, not overdue, no failure", st, period)
}
calls.mu.Lock()
calls.fail = &durable.SnapshotFailure{Code: "remote_unavailable", Err: errors.New("filer down")}
calls.mu.Unlock()
waitFor(t, 3*period, "the failure in the status", func() bool {
st := scheduledStatus(t, p)
return st != nil && st.LastFailure != nil
})
if st := scheduledStatus(t, p); st.LastFailure.Code != "remote_unavailable" || st.Attempts < 1 {
t.Fatalf("status %+v; want the typed failure and its attempt count", st)
}
}
// With the schedule off (period zero), no snapshot is attempted and the
// status has no scheduled-snapshot section.
func TestWALStoreChunk_ScheduledSnapshotOffTakesNone(t *testing.T) {
remote := storage.NewMemChunkRemote()
calls := &snapCalls{}
p := snapScheduleProvider(t, remote, 0, calls)
s := openRecovered(t, p)
if _, err := s.Write(1, block(0x01)); err != nil {
t.Fatal(err)
}
for i := 0; i < 10; i++ {
if calls.count() != 0 || scheduledStatus(t, p) != nil {
t.Fatal("a scheduled snapshot ran with the schedule off")
}
time.Sleep(100 * time.Millisecond)
}
}
// A snapshot period without its callback is refused.
func TestWALStoreChunk_ScheduledSnapshotNeedsItsCallback(t *testing.T) {
_, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096,
NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkSnapshotPeriod: time.Hour,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil },
}, v1View())
if err == nil {
t.Fatal("a snapshot period without its callback was accepted")
}
}
// A volume still fetching the chunks its HEAD names (a fresh host starting
// from the remote HEAD) is restoring: its scheduled attempts are skipped,
// counted by reason, and no snapshot is taken.
func TestWALStoreChunk_ScheduledSnapshotSkipsARestoringVolume(t *testing.T) {
const period = 2 * time.Second
remote := storage.NewMemChunkRemote()
view := v1View()
first := chunkProvider(t, t.TempDir(), remote, view, 0)
s := openRecovered(t, first)
if _, err := s.Write(33, block(0x33)); err != nil {
t.Fatal(err)
}
if err := first.MakeVolumeRemoteDurable(context.Background(), "v1", 1); err != nil {
t.Fatal(err)
}
_ = first.Close()
calls := &snapCalls{}
fresh, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096,
NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
ChunkSnapshotPeriod: period, ChunkScheduledSnapshot: calls.take,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, view)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = fresh.Close() })
openRecovered(t, fresh)
waitFor(t, 3*period, "a restoring skip", func() bool {
st := scheduledStatus(t, fresh)
return st != nil && st.Skipped[durable.SnapshotSkipRestoring] >= 1
})
if st := scheduledStatus(t, fresh); calls.count() != 0 || st.LastFailure != nil || st.Attempts != 0 {
t.Fatalf("restoring volume: %d snapshots, status %+v; want none taken and no failure", calls.count(), st)
}
}
@@ -0,0 +1,117 @@
package durable_test
import (
"bytes"
"context"
"errors"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// M5 PlainStop -> Quiesce: an idle plain detach seals under the caller's deadline,
// including after the frontend handle closes; no live-serving timer applies.
func TestOfflineSealUsesCallerDeadline(t *testing.T) {
for _, closed := range []bool{false, true} {
t.Run(map[bool]string{false: "idle", true: "closed"}[closed], func(t *testing.T) {
remote := storage.NewMemChunkRemote()
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096,
NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, DetachFreezeTimeout: time.Second,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
openRecovered(t, p)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
b, err := p.Open(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if _, err = b.Write(ctx, 4096, block(0x61)); err != nil {
t.Fatal(err)
}
if closed {
if err = b.Close(); err != nil {
t.Fatal(err)
}
}
deadline, _ := ctx.Deadline()
observed := false
durable.SetTestDetachTrace(p, func(stage string, got time.Time) {
if stage == "cut" && !got.Equal(deadline) {
t.Errorf("offline seal inherited live cut deadline: got %v want caller %v", got, deadline)
}
})
durable.SetTestDetachStopIO(p, func(c context.Context) error {
observed = true
got, ok := c.Deadline()
if !ok || !got.Equal(deadline) {
t.Errorf("offline seal inherited live timer: got %v known=%t want caller %v", got, ok, deadline)
}
return b.(*durable.StorageBackend).StopIO(c, "offline seal test")
})
r, last, err := p.DetachVolumePlain(ctx, "v1")
if err != nil || r.Head.State != storage.ChunkHeadDetached || r.H != last {
t.Fatalf("offline seal failed: %+v last=%d err=%v", r, last, err)
}
if !observed {
t.Error("offline seal did not drain")
}
if !bytes.Equal(headBlock(t, remote, 1), block(0x61)) {
t.Fatal("offline seal lost acknowledged bytes")
}
})
}
}
// Caller cancellation ends an offline upload; the closed backend stays closed,
// and a new caller can retry the seal without losing acknowledged bytes.
type cancelSealRemote struct {
*storage.MemChunkRemote
once sync.Once
cancel context.CancelFunc
}
func (r *cancelSealRemote) Put(ctx context.Context, key string, b []byte) error {
r.once.Do(r.cancel)
if err := ctx.Err(); err != nil {
return err
}
return r.MemChunkRemote.Put(ctx, key, b)
}
func TestOfflineSealCallerCancelCanRetry(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
remote := &cancelSealRemote{MemChunkRemote: storage.NewMemChunkRemote(), cancel: cancel}
p := chunkProvider(t, t.TempDir(), remote, v1View(), 0)
openRecovered(t, p)
b, err := p.Open(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
if _, err = b.Write(context.Background(), 4096, block(0x72)); err != nil {
t.Fatal(err)
}
if err = b.Close(); err != nil {
t.Fatal(err)
}
if _, _, err = p.DetachVolumePlain(ctx, "v1"); !errors.Is(err, context.Canceled) {
t.Fatalf("offline caller cancellation lost: %v", err)
}
if _, err = b.Write(context.Background(), 8192, block(0x73)); err == nil {
t.Fatal("failed offline seal reopened closed frontend")
}
retry, end := context.WithTimeout(context.Background(), time.Minute)
defer end()
r, _, err := p.DetachVolumePlain(retry, "v1")
if err != nil || r.Head.State != storage.ChunkHeadDetached || !bytes.Equal(headBlock(t, remote.MemChunkRemote, 1), block(0x72)) {
t.Fatalf("offline retry failed: %+v %v", r, err)
}
}
@@ -554,9 +554,6 @@ func (b *StorageBackend) stopPlainDetachIfIdle() error {
defer b.ioMu.Unlock()
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
return frontend.ErrBackendClosed
}
if b.admittedIO != 0 {
return ErrPlainDetachBusy
}
+2 -1
View File
@@ -31,6 +31,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"github.com/seaweedfs/seaweed-block/core/storeident"
"google.golang.org/grpc"
)
@@ -319,7 +320,7 @@ func New(cfg Config) (*Host, error) {
WriteTimeout: statusWriteTimeout, IdleTimeout: statusIdleTimeout}
}
grpcSrv := grpc.NewServer()
grpcSrv := link.NewServer(link.ServerConfig{})
svc := newServices(h)
control.RegisterObservationServiceServer(grpcSrv, svc)
control.RegisterAssignmentServiceServer(grpcSrv, svc)
@@ -169,6 +169,27 @@ func ValidateStatusListen(addr string) error {
return fmt.Errorf("--status-listen %q must be a loopback address (127.0.0.0/8, ::1 or localhost)", addr)
}
// ValidateControlListen refuses a control listener on a non-loopback address
// unless allowExternal: the gRPC control API and the runtime HTTP API are
// unauthenticated, so binding them to the node network must be an explicit
// choice (--insecure-external-bind). An empty address is off.
func ValidateControlListen(flag, addr string, allowExternal bool) error {
if addr == "" || allowExternal {
return nil
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
return fmt.Errorf("--%s %q: %v", flag, addr, err)
}
if host == "localhost" {
return nil
}
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
return nil
}
return fmt.Errorf("--%s %q is not a loopback address: the control API is unauthenticated; pass --insecure-external-bind to expose it on the node network", flag, addr)
}
// WorkspaceLeaseStatus is the GET /status/workspace-lease body.
type WorkspaceLeaseStatus struct {
ColocatedNodes int `json:"colocated_nodes"`
@@ -180,7 +180,34 @@ func (s *services) logForcedGrant(g *control.WorkspaceGrant, replay bool, postIs
g.GetVolumeId(), g.GetRequestId(), g.GetOldHost(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewHost(), g.GetNewReplicaId(), g.GetNewEpoch(), replay, lost)
}
func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (_ *control.WorkspaceGrant, resultErr error) {
// Remote reads never hold the workspace mutation lock. Re-read every
// local precondition below; Publisher checks the expected epoch atomically.
// A refusal is logged after the lock is released (deferred first, so it
// runs last): a slow log writer never holds workspaceMu.
// An issued forced grant is logged the same way, also after the unlock.
var refusal string
var issued *control.WorkspaceGrant
var replay bool
var postIssue, unknown error
defer func() {
// M2 Uncertain reply precedence applies even to preflight/HEAD errors.
outcome := s.host.Publisher().WorkspaceMoveOutcomeError(ctx, q.GetVolumeId(), resultErr)
if callerErr := ctx.Err(); resultErr != nil && callerErr != nil {
resultErr = workspaceError(callerErr)
} else if errors.Is(outcome, authority.ErrWorkspaceOutcomeUncertain) {
unknown, refusal = outcome, ""
resultErr = status.Errorf(codes.Internal, "workspace move %q of volume %q has an UNKNOWN outcome: %v; the volume's workspace authority stays uncertain until the master restarts; after the restart, rerun with the same request id", q.GetRequestId(), q.GetVolumeId(), outcome)
}
if refusal != "" {
s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal)
}
s.logForcedGrant(issued, replay, postIssue)
if unknown != nil {
s.host.log.Printf("blockmaster: MoveWorkspace outcome unknown volume=%q request=%q kind=%q: %v", q.GetVolumeId(), q.GetRequestId(), q.GetKind(), unknown)
}
}()
if err := s.workspaceVolume(q.GetVolumeId()); err != nil {
return nil, err
}
@@ -201,24 +228,6 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
if err != nil {
return nil, workspaceError(err)
}
// Remote reads never hold the workspace mutation lock. Re-read every
// local precondition below; Publisher checks the expected epoch atomically.
// A refusal is logged after the lock is released (deferred first, so it
// runs last): a slow log writer never holds workspaceMu.
// An issued forced grant is logged the same way, also after the unlock.
var refusal string
var issued *control.WorkspaceGrant
var replay bool
var postIssue, unknown error
defer func() {
if refusal != "" {
s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal)
}
s.logForcedGrant(issued, replay, postIssue)
if unknown != nil {
s.host.log.Printf("blockmaster: MoveWorkspace outcome unknown volume=%q request=%q kind=%q: %v", q.GetVolumeId(), q.GetRequestId(), q.GetKind(), unknown)
}
}()
s.host.workspaceMu.Lock()
defer s.host.workspaceMu.Unlock()
if err := ctx.Err(); err != nil {
@@ -246,11 +255,6 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
issued, postIssue = s.issuedRecord(req), err
return nil, postIssueError(q, err)
}
if errors.Is(err, authority.ErrWorkspaceOutcomeUncertain) {
unknown = err
return nil, status.Errorf(codes.Internal, "workspace move %q of volume %q has an UNKNOWN outcome: %v; the volume's workspace authority stays uncertain until the master restarts; after the restart, rerun with the same request id",
q.GetRequestId(), q.GetVolumeId(), err)
}
return nil, workspaceError(err)
}
// The move is issued from here on: record it for the audit log before
@@ -0,0 +1,142 @@
package master
import (
"context"
"errors"
"github.com/seaweedfs/seaweed-block/core/authority"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestWorkspaceMoveUnknownPrecedesAdmissionRefusals(t *testing.T) {
for _, duringRead := range []bool{false, true} {
t.Run(map[bool]string{false: "already_uncertain", true: "uncertain_during_HEAD"}[duringRead], func(t *testing.T) {
var inject atomic.Bool
var headFailure atomic.Int32
var childDeadlineObserved atomic.Bool
var latch func() error
var cancelRequest context.CancelFunc
h, c, ctx := reviewBindingHostWithReader(t, func(readCtx context.Context, _ string) (authority.WorkspaceHead, error) {
if inject.Swap(false) {
if err := latch(); err != nil {
return authority.WorkspaceHead{}, err
}
}
switch headFailure.Load() {
case 1:
return authority.WorkspaceHead{}, errors.New("test HEAD unavailable")
case 2:
// Expire the service's actual child read context. The
// request parent below stays live indefinitely.
<-readCtx.Done()
childDeadlineObserved.Store(readCtx.Err() == context.DeadlineExceeded)
return authority.WorkspaceHead{}, readCtx.Err()
case 3:
dependency, cancel := context.WithCancel(readCtx)
cancel()
return authority.WorkspaceHead{}, dependency.Err()
case 4:
dependency, cancel := context.WithDeadline(readCtx, time.Unix(0, 1))
defer cancel()
cancelRequest()
return authority.WorkspaceHead{}, dependency.Err()
}
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
})
reviewLegacyBind(t, h, c, ctx, "v")
if _, err := h.Publisher().RenewWorkspaceLease(ctx, "v", "r1", 1); err != nil {
t.Fatal(err)
}
client := control.NewWorkspaceServiceClient(c)
request := func(kind string) *control.WorkspaceMove {
return &control.WorkspaceMove{VolumeId: "v", RequestId: "precedence-" + kind, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "missing-node", TargetDataAddr: "127.0.0.1:29901", TargetCtrlAddr: "127.0.0.1:29902", Kind: kind, Force: kind == "forced"}
}
for _, kind := range []string{"clean", "forced"} {
if _, err := client.MoveWorkspace(ctx, request(kind)); status.Code(err) != codes.FailedPrecondition {
t.Fatalf("healthy admission control: %v", err)
}
}
faults := atomic.Int64{}
injected := errors.New("test persistence reply lost after rename")
authority.SetPutAfterRenameFaultForTest(func(r authority.DurableRecord) error {
if r.Workspace != nil && r.Workspace.Lease != nil && r.Workspace.Lease.Revoking {
faults.Add(1)
return injected
}
return nil
})
t.Cleanup(func() { authority.SetPutAfterRenameFaultForTest(nil) })
latch = func() error {
err := h.Publisher().BeginWorkspaceRevocation(ctx, "v", "r1", 1)
if !errors.Is(err, injected) {
return errors.New("test failed to latch uncertain persistence")
}
return nil
}
if duringRead {
inject.Store(true)
} else if err := latch(); err != nil {
t.Fatal(err)
}
for _, kind := range []string{"clean", "forced"} {
q := request(kind)
if _, err := client.MoveWorkspace(ctx, q); status.Code(err) != codes.Internal || !strings.Contains(status.Convert(err).Message(), "UNKNOWN") || !strings.Contains(status.Convert(err).Message(), q.RequestId) {
t.Errorf("uncertain %s move answered definite refusal: %v", kind, err)
}
}
headFailure.Store(1)
if _, err := client.MoveWorkspace(ctx, request("clean")); status.Code(err) != codes.Internal || !strings.Contains(status.Convert(err).Message(), "UNKNOWN") {
t.Errorf("early HEAD error hid uncertainty: %v", err)
}
liveParent := context.Background()
for _, mode := range []int32{2, 3} {
headFailure.Store(mode)
_, err := (&services{host: h}).MoveWorkspace(liveParent, request("clean"))
if liveParent.Err() != nil || (mode == 2 && !childDeadlineObserved.Load()) {
t.Fatal("dependency-end witness did not preserve live request")
}
if status.Code(err) != codes.Internal || !strings.Contains(status.Convert(err).Message(), "UNKNOWN") || !strings.Contains(status.Convert(err).Message(), "same request id") {
t.Errorf("live-parent HEAD dependency end bypassed UNKNOWN: mode=%d err=%v", mode, err)
}
}
caller, cancelCaller := context.WithCancel(context.Background())
cancelRequest = cancelCaller
headFailure.Store(4)
_, err := (&services{host: h}).MoveWorkspace(caller, request("clean"))
cancelCaller()
if caller.Err() != context.Canceled || status.Code(err) != codes.Canceled {
t.Errorf("actual caller end lost to dependency status: %v", err)
}
// These direct calls inspect the server result, not the client's own
// deadline override, so reply classification must preserve both.
for _, deadline := range []bool{false, true} {
var ended context.Context
var end context.CancelFunc
want := codes.Canceled
if deadline {
ended, end = context.WithDeadline(ctx, time.Unix(0, 1))
want = codes.DeadlineExceeded
} else {
ended, end = context.WithCancel(ctx)
end()
}
_, err := (&services{host: h}).MoveWorkspace(ended, request("forced"))
end()
if status.Code(err) != want {
t.Errorf("server caller-end classification changed: %v want %v", err, want)
}
}
authority.SetPutAfterRenameFaultForTest(nil)
state := h.Publisher().WorkspaceState("v")
line, ok := h.Publisher().VolumeAuthorityLine("v")
if faults.Load() != 1 || state.Lease.Revoking || len(state.Moves) != 0 || !ok || line.Epoch != 1 || line.ReplicaID != "r1" {
t.Fatalf("unknown requests changed authority: faults=%d state=%+v line=%+v", faults.Load(), state, line)
}
})
}
}
@@ -552,11 +552,21 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request)
writeChunkErr(w, http.StatusBadRequest, codeInvalidFreezeBudget, false, "frozen requires a non-future freezeStartedAtNs and cannot combine with plain; allowOverBudget requires frozen")
return
}
// M5 PlainStop -> Quiesce: the offline caller owns a finite wait.
if req.Plain && req.TimeoutMs <= 0 {
writeChunkErr(w, http.StatusBadRequest, codeBadRequest, false, "plain detach requires positive timeoutMs")
return
}
ctl := s.chunkTarget(w, req.VolumeID)
if ctl == nil {
return
}
ctx, cancel := chunkContext(r, req.TimeoutMs)
if req.Plain { // M5 PlainStop -> Quiesce: offline work is bounded by its caller.
cancel()
const maxTimeoutMs = int64((1<<63 - 1) / time.Millisecond)
ctx, cancel = context.WithTimeout(r.Context(), time.Duration(min(req.TimeoutMs, maxTimeoutMs))*time.Millisecond)
}
defer cancel()
var res ChunkDetachResponse
var err error
@@ -633,24 +643,35 @@ func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkS
}
sreq := chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID, Labels: req.Labels,
Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume", Class: req.Class}
if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed {
return sealSnapshot(ctx, c.cat, volumeID, sreq, func(ctx context.Context) (storage.ChunkHead, error) {
// A named seal is urgent even without a minimum LSN.
r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0)
return r.Head, err
})
}
// sealSnapshot resolves sreq against the catalog first: a retry of a
// recorded request returns that snapshot and another request for the name
// fails, both without cutting. Only a free name is cut, and the HEAD that
// cut installed is stored.
func sealSnapshot(ctx context.Context, cat *chunkstore.Catalog, volumeID string, sreq chunkstore.SnapshotRequest, cut func(context.Context) (storage.ChunkHead, error)) (chunkstore.SnapshotInfo, error) {
if info, replayed, err := cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed {
return info, err
}
// The share begins before the cut that produces the sealed HEAD.
if g := c.cat.ShareGuard(); g != nil {
if g := cat.ShareGuard(); g != nil {
token, err := g.Begin(ctx, volumeID)
if err != nil {
return chunkstore.SnapshotInfo{}, err
}
sreq.ShareToken = token
}
// A named seal is urgent even without a minimum LSN.
r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0)
head, err := cut(ctx)
if err != nil {
return chunkstore.SnapshotInfo{}, err
}
sreq.SourceReadAt = time.Now()
return c.cat.CreateSnapshot(ctx, volumeID, sreq, r.Head)
return cat.CreateSnapshot(ctx, volumeID, sreq, head)
}
func (c *chunkControl) ListSnapshots(ctx context.Context, volumeID string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) {
@@ -67,6 +67,14 @@ func (f *fakeChunkProvider) DetachVolume(context.Context, string) (storage.Chunk
}
func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) {
t.Helper()
fp, cat := adapterCatalog(t)
return fp, NewChunkControl(fp, cat)
}
// adapterCatalog is a catalog holding volume v1 and a provider whose cut
// installs a published HEAD of v1.
func adapterCatalog(t *testing.T) (*fakeChunkProvider, *chunkstore.Catalog) {
t.Helper()
head := storage.ChunkHead{Gen: 3, Epoch: 2, Holder: "r1", RemoteLSN: 9, State: storage.ChunkHeadActive,
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e2/c0/k1"}, 5: {Key: "chunks/e2/c5/k2"}}}
@@ -87,7 +95,7 @@ func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) {
if _, err := cat.EnsureVolume(context.Background(), "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
t.Fatal(err)
}
return fp, NewChunkControl(fp, cat)
return fp, cat
}
// Snapshot validates before it cuts, then stores the HEAD its cut
@@ -0,0 +1,61 @@
package volume
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
type offlineSealControl struct {
*plainDetachControl
got context.Context
}
func (c *offlineSealControl) DetachPlain(ctx context.Context, id string) (ChunkDetachResponse, error) {
c.got = ctx
return c.plainDetachControl.DetachPlain(ctx, id)
}
func TestChunkPlainDetachUsesCallerDeadline(t *testing.T) {
for _, limited := range []bool{false, true} {
c := &offlineSealControl{plainDetachControl: &plainDetachControl{fakeChunkControl: &fakeChunkControl{}}}
s := chunkServer(t, c, true)
ctx := context.Background()
cancel := func() {}
if limited {
ctx, cancel = context.WithTimeout(ctx, 5*time.Minute)
}
req := httptest.NewRequest(http.MethodPost, "/chunk/detach", strings.NewReader(`{"volumeID":"v1","plain":true,"timeoutMs":3600000}`)).WithContext(ctx)
req.RemoteAddr = "127.0.0.1:5555"
w := httptest.NewRecorder()
before := time.Now()
s.chunkMux().ServeHTTP(w, req)
after := time.Now()
cancel()
if w.Code != 200 || c.got == nil {
t.Fatalf("plain dispatch failed: %d %s", w.Code, w.Body)
}
got, gok := c.got.Deadline()
if want, ok := ctx.Deadline(); ok {
if !gok || !got.Equal(want) {
t.Errorf("offline HTTP ignored earlier caller: got=%v want=%v", got, want)
}
} else if !gok || got.Before(before.Add(time.Hour)) || got.After(after.Add(time.Hour)) {
t.Errorf("offline HTTP inherited operation cap: got=%v want explicit one-hour bound", got)
}
}
}
func TestChunkPlainDetachRequiresExplicitBound(t *testing.T) {
for _, suffix := range []string{"", `,"timeoutMs":0`, `,"timeoutMs":-1`} {
c := &plainDetachControl{fakeChunkControl: &fakeChunkControl{}}
s := chunkServer(t, c, true)
w := serve(t, s, http.MethodPost, "/chunk/detach", fmt.Sprintf(`{"volumeID":"v1","plain":true%s}`, suffix), "")
if w.Code != http.StatusBadRequest || c.calls != 0 || c.plainCalls != 0 {
t.Errorf("unbounded plain request reached provider: status=%d calls=%d plain=%d", w.Code, c.calls, c.plainCalls)
}
}
}
@@ -28,7 +28,7 @@ func TestChunkDetachPlainFieldDispatch(t *testing.T) {
t.Fatalf("ordinary request changed: %d %s plain=%d", w.Code, w.Body, c.plainCalls)
}
}
w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "")
w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true,"timeoutMs":60000}`, "")
if w.Code != 200 || c.plainCalls != 1 {
t.Fatalf("plain request not dispatched: %d %s plain=%d", w.Code, w.Body, c.plainCalls)
}
@@ -50,12 +50,12 @@ func (p *plainDetachProvider) DetachVolumePlain(ctx context.Context, id string)
func TestChunkDetachPlainAdapterAndBusyResponse(t *testing.T) {
p := &plainDetachProvider{fakeChunkProvider: &fakeChunkProvider{detach: storage.ChunkCutResult{H: 9, Head: storage.ChunkHead{Gen: 3, Epoch: 2, State: storage.ChunkHeadDetached}}, last: 9}}
s := chunkServer(t, NewChunkControl(p, nil), true)
w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "")
w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true,"timeoutMs":60000}`, "")
if w.Code != 200 || p.plainCalls != 1 {
t.Fatalf("plain adapter: %d %s calls=%d", w.Code, w.Body, p.plainCalls)
}
p.err = errors.Join(durable.ErrPlainDetachBusy, errors.New("held I/O"))
w = serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "")
w = serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true,"timeoutMs":60000}`, "")
if w.Code != 409 {
t.Fatalf("busy status: %d %s", w.Code, w.Body)
}
@@ -0,0 +1,38 @@
package volume
import (
"context"
"strconv"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// ScheduledSnapshotName is the name of the scheduled snapshot attempted
// at at (UTC, to the second).
func ScheduledSnapshotName(at time.Time) string {
return "sched-" + at.UTC().Format("20060102T150405Z")
}
// ScheduledSnapshot returns the provider's scheduled-snapshot callback
// (durable.ProviderConfig.ChunkScheduledSnapshot) over cat. Each attempt
// is one named snapshot of class "scheduled", labelled with keep (the
// count retention keeps), sealed through the same path as an explicit
// named snapshot: the request is resolved first, then one cut, then the
// record of that cut's HEAD. A failure carries the code the control
// endpoint would report.
func ScheduledSnapshot(cat *chunkstore.Catalog, keep int) func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error {
labels := map[string]string{chunkstore.LabelScheduleKeep: strconv.Itoa(keep)}
return func(ctx context.Context, volumeID string, at time.Time, cut func(context.Context) (storage.ChunkHead, error)) error {
name := ScheduledSnapshotName(at)
sreq := chunkstore.SnapshotRequest{Name: name, RequestID: name, Labels: labels,
CreatedBy: "blockvolume-schedule", Class: chunkstore.SnapshotClassScheduled}
if _, err := sealSnapshot(ctx, cat, volumeID, sreq, cut); err != nil {
_, code, _ := chunkErrorCode(err)
return &durable.SnapshotFailure{Code: code, Err: err}
}
return nil
}
}
@@ -0,0 +1,69 @@
package volume
import (
"context"
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// A scheduled snapshot is one named snapshot of class "scheduled", named
// for its attempt time and labelled with the schedule's keep, recording
// exactly the HEAD its own cut installed. A retry of the same attempt
// replays without cutting again.
func TestScheduledSnapshot_SealsTheCutHeadAsScheduled(t *testing.T) {
ctx := context.Background()
fp, cat := adapterCatalog(t)
take := ScheduledSnapshot(cat, 7)
at := time.Date(2026, 11, 21, 3, 4, 5, 0, time.UTC)
cuts := 0
cut := func(ctx context.Context) (storage.ChunkHead, error) {
cuts++
r, err := fp.CutVolume(ctx, "v1", 0)
return r.Head, err
}
if err := take(ctx, "v1", at, cut); err != nil {
t.Fatal(err)
}
if err := take(ctx, "v1", at, cut); err != nil || cuts != 1 {
t.Fatalf("retry of the same attempt: %v, %d cuts; want a replay without a second cut", err, cuts)
}
list, _, err := cat.ListSnapshots(ctx, "v1", chunkstore.ListOptions{})
if err != nil || len(list) != 1 {
t.Fatalf("list: %+v %v", list, err)
}
s := list[0]
if s.Name != "sched-20261121T030405Z" || s.Class != chunkstore.SnapshotClassScheduled || s.Labels[chunkstore.LabelScheduleKeep] != "7" ||
s.HeadGen != fp.cut.Head.Gen || s.HeadEpoch != fp.cut.Head.Epoch || s.CutLSN != fp.cut.Head.RemoteLSN {
t.Fatalf("snapshot %+v; want sched-20261121T030405Z, class scheduled, keep 7, the cut's HEAD", s)
}
}
// A failed cut is reported as a durable.SnapshotFailure with the code
// the control endpoint gives the same error, and records nothing.
func TestScheduledSnapshot_FailureCarriesTheEndpointCode(t *testing.T) {
ctx := context.Background()
_, cat := adapterCatalog(t)
take := ScheduledSnapshot(cat, 7)
for _, c := range []struct {
err error
code string
}{
{storage.ErrChunkLayerFenced, codeFenced},
{storage.ErrChunkRemoteUnavailable, chunkstore.CodeRemoteUnavailable},
{context.DeadlineExceeded, chunkstore.CodeDeadlineExceeded},
} {
err := take(ctx, "v1", time.Now(), func(context.Context) (storage.ChunkHead, error) { return storage.ChunkHead{}, c.err })
var f *durable.SnapshotFailure
if !errors.As(err, &f) || f.Code != c.code || !errors.Is(err, c.err) {
t.Fatalf("cut error %v: got %v; want a SnapshotFailure with code %s", c.err, err, c.code)
}
}
if list, _, _ := cat.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}); len(list) != 0 {
t.Fatalf("failed attempts recorded %+v", list)
}
}
+2 -2
View File
@@ -15,9 +15,9 @@ import (
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/replication"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"github.com/seaweedfs/seaweed-block/core/storeident"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
@@ -259,7 +259,7 @@ func New(cfg Config) (*Host, error) {
lg = log.Default()
}
conn, err := grpc.NewClient(cfg.MasterAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(cfg.MasterAddr)
if err != nil {
return nil, fmt.Errorf("volume.New: dial master %q: %w", cfg.MasterAddr, err)
}
@@ -5,8 +5,8 @@ import (
"fmt"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type GRPCFailbackRuntime struct {
@@ -22,11 +22,15 @@ func (r *GRPCFailbackRuntime) ExecuteFailback(ctx context.Context, req FailbackR
if r == nil || r.Addr == "" {
return FailbackRuntimeResult{}, fmt.Errorf("failback runtime gRPC address is required")
}
opts := append([]grpc.DialOption(nil), r.Opts...)
if len(opts) == 0 {
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
// Injected options replace the default link (as before); none means the
// standard link.
var conn *grpc.ClientConn
var err error
if len(r.Opts) > 0 {
conn, err = link.DialWith(r.Addr, r.Opts...)
} else {
conn, err = link.Dial(r.Addr)
}
conn, err := grpc.NewClient(r.Addr, opts...)
if err != nil {
return FailbackRuntimeResult{}, err
}
+2 -3
View File
@@ -18,8 +18,7 @@ import (
hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume"
"github.com/seaweedfs/seaweed-block/core/replication"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
type LiveVolumeStatusConfig struct {
@@ -95,7 +94,7 @@ func NewLiveVolumeStatusReportCollector(cfg LiveVolumeStatusConfig) VolumeStatus
}
func queryLiveMasterStatus(ctx context.Context, masterAddr, volumeID string) (*control.StatusResponse, error) {
conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(masterAddr)
if err != nil {
return nil, fmt.Errorf("dial master: %w", err)
}
+47
View File
@@ -0,0 +1,47 @@
// Package link builds every gRPC link between seaweed-block processes and to
// SeaweedFS: one dial helper and one server builder, so transport security
// and call authorization have a single place to be added. Today a link is
// plaintext, exactly as before this package existed, and a server runs only
// the interceptors its caller passes (none by default).
package link
import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// Dial opens a lazy client connection to target with plaintext transport
// credentials; opts follow (a later option overrides an earlier one).
func Dial(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
all := make([]grpc.DialOption, 0, len(opts)+1)
all = append(all, grpc.WithTransportCredentials(insecure.NewCredentials()))
all = append(all, opts...)
return grpc.NewClient(target, all...)
}
// DialWith opens a lazy client connection to target with exactly opts: the
// caller supplies the transport credentials (no default is added). It is the
// one place a link with caller-chosen options is built.
func DialWith(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
return grpc.NewClient(target, opts...)
}
// ServerConfig is a server's interceptor chain; the zero value has none.
type ServerConfig struct {
Unary []grpc.UnaryServerInterceptor
Stream []grpc.StreamServerInterceptor
}
// NewServer builds a gRPC server whose calls pass through cfg's interceptors,
// in order; opts follow.
func NewServer(cfg ServerConfig, opts ...grpc.ServerOption) *grpc.Server {
all := make([]grpc.ServerOption, 0, len(opts)+2)
if len(cfg.Unary) > 0 {
all = append(all, grpc.ChainUnaryInterceptor(cfg.Unary...))
}
if len(cfg.Stream) > 0 {
all = append(all, grpc.ChainStreamInterceptor(cfg.Stream...))
}
all = append(all, opts...)
return grpc.NewServer(all...)
}
+288
View File
@@ -0,0 +1,288 @@
package link
import (
"context"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/fs"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)
func serve(t *testing.T, cfg ServerConfig) string {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := NewServer(cfg)
healthpb.RegisterHealthServer(srv, health.NewServer())
done := make(chan struct{})
go func() { _ = srv.Serve(lis); close(done) }()
t.Cleanup(func() {
srv.Stop()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("server did not stop")
}
})
return lis.Addr().String()
}
// A link dialed with Dial reaches a server built with NewServer, for a unary
// and a streaming call, as plaintext gRPC did before the seam.
func TestLink_DialReachesNewServerUnaryAndStream(t *testing.T) {
addr := serve(t, ServerConfig{})
conn, err := Dial(addr)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c := healthpb.NewHealthClient(conn)
if r, err := c.Check(ctx, &healthpb.HealthCheckRequest{}); err != nil || r.Status != healthpb.HealthCheckResponse_SERVING {
t.Fatalf("unary call: %v %v", r, err)
}
w, err := c.Watch(ctx, &healthpb.HealthCheckRequest{})
if err != nil {
t.Fatal(err)
}
if r, err := w.Recv(); err != nil || r.Status != healthpb.HealthCheckResponse_SERVING {
t.Fatalf("stream call: %v %v", r, err)
}
}
// The server runs its unary and stream interceptors in the configured order.
func TestLink_ServerRunsInterceptorsInOrder(t *testing.T) {
var mu sync.Mutex
var seen []string
note := func(s string) { mu.Lock(); seen = append(seen, s); mu.Unlock() }
unary := func(name string) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, h grpc.UnaryHandler) (any, error) {
note(name)
return h(ctx, req)
}
}
stream := func(name string) grpc.StreamServerInterceptor {
return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, h grpc.StreamHandler) error {
note(name)
return h(srv, ss)
}
}
addr := serve(t, ServerConfig{Unary: []grpc.UnaryServerInterceptor{unary("u1"), unary("u2")}, Stream: []grpc.StreamServerInterceptor{stream("s1"), stream("s2")}})
conn, err := Dial(addr)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c := healthpb.NewHealthClient(conn)
if _, err := c.Check(ctx, &healthpb.HealthCheckRequest{}); err != nil {
t.Fatal(err)
}
w, err := c.Watch(ctx, &healthpb.HealthCheckRequest{})
if err != nil {
t.Fatal(err)
}
if _, err := w.Recv(); err != nil {
t.Fatal(err)
}
mu.Lock()
defer mu.Unlock()
if got := strings.Join(seen, ","); got != "u1,u2,s1,s2" {
t.Fatalf("interceptors ran as %q, want u1,u2,s1,s2", got)
}
}
// rawLinkCalls lists the uses in one Go source of a gRPC link constructor
// that bypass this package: a client (grpc.NewClient, grpc.Dial,
// grpc.DialContext), a server (grpc.NewServer) or plaintext credentials
// (insecure.NewCredentials), called or taken as a function value, whatever
// local name the import has (aliases and dot imports included).
func rawLinkCalls(name string, src []byte) ([]string, error) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, name, src, parser.SkipObjectResolution)
if err != nil {
return nil, err
}
banned := map[string]map[string]bool{
"google.golang.org/grpc": {"NewClient": true, "Dial": true, "DialContext": true, "NewServer": true},
"google.golang.org/grpc/credentials/insecure": {"NewCredentials": true},
}
local := map[string]map[string]bool{} // import name -> banned functions
dot := map[string]bool{} // banned functions reachable unqualified
for _, im := range f.Imports {
path, _ := strconv.Unquote(im.Path.Value)
fns, ok := banned[path]
if !ok {
continue
}
name := filepath.Base(path)
if im.Name != nil {
name = im.Name.Name
}
switch name {
case "_":
case ".":
for fn := range fns {
dot[fn] = true
}
default:
local[name] = fns
}
}
// Any use counts, not only a call: a function value (f := grpc.NewClient)
// builds a raw link just the same. A selector's own name is not an
// unqualified use.
sels := map[*ast.Ident]bool{}
ast.Inspect(f, func(n ast.Node) bool {
if sel, ok := n.(*ast.SelectorExpr); ok {
sels[sel.Sel] = true
}
return true
})
var found []string
ast.Inspect(f, func(n ast.Node) bool {
switch e := n.(type) {
case *ast.SelectorExpr:
if x, ok := e.X.(*ast.Ident); ok && local[x.Name][e.Sel.Name] {
found = append(found, fmt.Sprintf("%s: %s.%s", fset.Position(e.Pos()), x.Name, e.Sel.Name))
}
case *ast.Ident:
if dot[e.Name] && !sels[e] {
found = append(found, fmt.Sprintf("%s: %s", fset.Position(e.Pos()), e.Name))
}
}
return true
})
return found, nil
}
// The detector finds every form of a raw construction, and nothing in a file
// that only uses this package.
func TestLink_GuardDetectsRawConstructionsAndAliases(t *testing.T) {
cases := map[string]string{
"client": `package p
import "google.golang.org/grpc"
func f() { grpc.NewClient("x") }
`,
"dial": `package p
import "google.golang.org/grpc"
func f() { grpc.Dial("x") }
`,
"dialContext": `package p
import "google.golang.org/grpc"
func f() { grpc.DialContext(nil, "x") }
`,
"server": `package p
import "google.golang.org/grpc"
func f() { grpc.NewServer() }
`,
"aliasClient": `package p
import g "google.golang.org/grpc"
func f() { g.NewClient("x") }
`,
"aliasCreds": `package p
import ins "google.golang.org/grpc/credentials/insecure"
func f() { ins.NewCredentials() }
`,
"dotImport": `package p
import . "google.golang.org/grpc"
func f() { NewServer() }
`,
"funcValue": `package p
import "google.golang.org/grpc"
var dial = grpc.NewClient
`,
"aliasValue": `package p
import g "google.golang.org/grpc"
func f() { mk := g.NewServer; _ = mk }
`,
"dotValue": `package p
import . "google.golang.org/grpc"
var dial = NewClient
`,
"plainCredsFn": `package p
import "google.golang.org/grpc/credentials/insecure"
func f() { insecure.NewCredentials() }
`,
}
for name, src := range cases {
got, err := rawLinkCalls(name+".go", []byte(src))
if err != nil || len(got) != 1 {
t.Errorf("%s: found %v (%v), want exactly one raw construction", name, got, err)
}
}
clean := `package p
import (
"google.golang.org/grpc"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
func f() { link.Dial("x", grpc.WithBlock()) }
`
if got, err := rawLinkCalls("clean.go", []byte(clean)); err != nil || len(got) != 0 {
t.Errorf("clean: found %v (%v), want none", got, err)
}
}
// Every production gRPC link goes through this package: no other non-test Go
// file constructs a gRPC client or server or plaintext credentials directly.
func TestLink_NoProductionSiteBypassesTheSeam(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", "..", ".."))
if err != nil {
t.Fatal(err)
}
self, err := filepath.Abs(".")
if err != nil {
t.Fatal(err)
}
var bad []string
err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if name := d.Name(); name == ".git" || name == "vendor" || name == "testdata" || p == self {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") {
return nil
}
src, err := os.ReadFile(p)
if err != nil {
return err
}
found, err := rawLinkCalls(p, src)
if err != nil {
return err
}
for _, f := range found {
rel, _ := filepath.Rel(root, p)
bad = append(bad, rel+" ("+f[strings.LastIndex(f, ": ")+2:]+")")
}
return nil
})
if err != nil {
t.Fatal(err)
}
if len(bad) > 0 {
t.Fatalf("gRPC links built outside core/rpc/link (use link.Dial, link.DialWith or link.NewServer): %v", bad)
}
}
+2 -2
View File
@@ -17,9 +17,9 @@ import (
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
@@ -124,7 +124,7 @@ func New(rpc control.WorkspaceServiceClient) *Client { return &Client{rpc: rpc}
// Dial connects to the blockmaster gRPC address (plaintext, as the other
// operator commands).
func Dial(addr string) (*Client, error) {
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial(addr)
if err != nil {
return nil, err
}
@@ -1459,6 +1459,7 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error
}
if err == nil {
l.stats.LastCut, l.stats.LastCutH, l.stats.LastCutNs = st, r.H, time.Now().UnixNano()
l.stats.CutSeq++
}
if st.BarrierOverBound {
l.stats.BarrierOverBound++
@@ -8,20 +8,22 @@ import "context"
// complete before this one gets the capture lock. That cut restarted the
// timer, so the due cut is not taken.
type ChunkPeriodicCutter interface {
// CutUnlessCutSince cuts unless a cut succeeded after lastCutNs (the
// LastCutNs the timer decided on); skipped reports that it did not cut.
CutUnlessCutSince(ctx context.Context, lastCutNs int64) (r ChunkCutResult, skipped bool, err error)
// CutUnlessCutSince cuts unless a cut succeeded since the timer decided
// (CutSeq is no longer seq, the CutSeq it decided on); skipped reports
// that it did not cut. Cuts are ordered by CutSeq, never by their wall
// stamps.
CutUnlessCutSince(ctx context.Context, seq uint64) (r ChunkCutResult, skipped bool, err error)
}
var _ ChunkPeriodicCutter = (*chunkLayerImpl)(nil)
func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, lastCutNs int64) (chunkCutResult, bool, error) {
func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, seq uint64) (chunkCutResult, bool, error) {
l.capMu.Lock()
defer l.unlockCap() // delivers the cut's OnPublishSettled report after the lock
l.stMu.Lock()
last := l.stats.LastCutNs
cur := l.stats.CutSeq
l.stMu.Unlock()
if last > lastCutNs {
if cur != seq {
return chunkCutResult{}, true, nil
}
r, err := l.captureLocked(ctx, false)
@@ -1,6 +1,9 @@
package storage
import "testing"
import (
"testing"
"time"
)
// A periodic cut decided before another cut completed is skipped; decided
// after the last cut, it cuts.
@@ -14,7 +17,7 @@ func TestChunkPeriodicCut_SkipsAfterANewerCut(t *testing.T) {
}
w := newWriteLog()
w.write(t, s, 2, 0x22)
decided := layer.Stats().LastCutNs // the timer decides here...
decided := layer.Stats().CutSeq // the timer decides here...
if _, err := layer.Cut(ctTimeout(t)); err != nil { // ...then another cut completes first
t.Fatal(err)
}
@@ -26,7 +29,7 @@ func TestChunkPeriodicCut_SkipsAfterANewerCut(t *testing.T) {
if f.stats().cas != casBefore {
t.Fatal("a skipped periodic cut published")
}
r, skipped, err := pc.CutUnlessCutSince(ctTimeout(t), layer.Stats().LastCutNs)
r, skipped, err := pc.CutUnlessCutSince(ctTimeout(t), layer.Stats().CutSeq)
if err != nil || skipped || r.Noop {
t.Fatalf("periodic cut decided after the last cut: skipped=%v noop=%v err=%v; want a cut", skipped, r.Noop, err)
}
@@ -34,3 +37,35 @@ func TestChunkPeriodicCut_SkipsAfterANewerCut(t *testing.T) {
t.Fatalf("CAS calls %d -> %d; want one", casBefore, f.stats().cas)
}
}
// Cuts are ordered by CutSeq, not by their wall stamps: a newer cut whose
// stamp reads earlier than the one the timer decided on (a backward clock
// step between them) still makes the stale periodic decision skip.
func TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
pc := layer.(ChunkPeriodicCutter)
impl := layer.(*chunkLayerImpl)
w := newWriteLog()
w.write(t, s, 2, 0x22)
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
decided, decidedNs := layer.Stats().CutSeq, layer.Stats().LastCutNs
w.write(t, s, 5, 0x25)
if _, err := layer.Cut(ctTimeout(t)); err != nil { // a newer cut completes...
t.Fatal(err)
}
impl.stMu.Lock()
impl.stats.LastCutNs = decidedNs - int64(time.Hour) // ...stamped by a clock stepped back an hour
impl.stMu.Unlock()
w.write(t, s, 9, 0x29)
casBefore := f.stats().cas
if _, skipped, err := pc.CutUnlessCutSince(ctTimeout(t), decided); err != nil || !skipped {
t.Fatalf("stale periodic decision after a newer cut with an older stamp: skipped=%v err=%v; want skipped", skipped, err)
}
if f.stats().cas != casBefore {
t.Fatal("the stale periodic decision published")
}
}
+4 -1
View File
@@ -495,7 +495,9 @@ type chunkCutStats struct {
// publishes until it is done. ReconcileDone of ReconcileTotal chunks
// are compared.
// - LastCut, LastCutH and LastCutNs (wall clock, Unix ns) describe the
// last successful cut, whatever triggered it.
// last successful cut, whatever triggered it. CutSeq counts the
// successful cuts of this layer (in-process): it identifies the latest
// cut and orders cuts without any clock.
type chunkLayerStats struct {
Hydration ChunkHydrationStats // lazy fetches of absent chunks from the remote
CutsOK uint64 // cuts that installed a HEAD
@@ -513,6 +515,7 @@ type chunkLayerStats struct {
LastCut chunkCutStats // the last successful cut's measurements
LastCutH uint64 // the LSN the last successful cut published
LastCutNs int64 // when it completed (wall clock, Unix ns)
CutSeq uint64 // successful cuts of this layer so far (in-process); the latest cut's identity
// BarrierOverBound counts cuts whose barrier copied more than the
// bound after the staging rounds.
BarrierOverBound uint64
@@ -111,6 +111,10 @@ SWB_CHUNK_REPLICATION=
# --chunk-capture-interval (default 0: no timer). Automatic cut once this long
# has passed since the last successful cut, e.g. 15m as a host-loss safety net.
SWB_CHUNK_CAPTURE_INTERVAL=0
# --chunk-snapshot-schedule (default daily:7). Scheduled named snapshots:
# daily:N or weekly:N takes one snapshot per period at a per-volume offset
# (not at a wall-clock hour) and keeps the newest N; off disables them.
SWB_CHUNK_SNAPSHOT_SCHEDULE=daily:7
# --chunk-upload-concurrency (default 8; 1..64). Parallel dirty-chunk uploads.
SWB_CHUNK_UPLOAD_CONCURRENCY=8
# --chunk-control-endpoint (default false). Expose /chunk/* (cut, snapshot,
@@ -46,6 +46,7 @@ spec:
- "--launcher-iscsi-port-base=3260"
- "--launcher-kubernetes-apply"
- "--listen=0.0.0.0:9333"
- "--insecure-external-bind"
- "--expected-slots-per-volume=__EXPECTED_SLOTS_PER_VOLUME__"
ports:
- name: grpc
@@ -43,6 +43,7 @@ spec:
- "--cluster-spec=/config/cluster-spec.yaml"
- "--lifecycle-product-loop-interval=100ms"
- "--listen=0.0.0.0:9333"
- "--insecure-external-bind"
- "--expected-slots-per-volume=2"
ports:
- name: grpc
@@ -48,6 +48,7 @@ spec:
- "--launcher-durable-root=/var/lib/sw-block"
- "--launcher-iscsi-port-base=3260"
- "--listen=0.0.0.0:9333"
- "--insecure-external-bind"
- "--expected-slots-per-volume=1"
ports:
- name: grpc
@@ -59,6 +59,7 @@ ExecStart=/usr/local/bin/blockvolume \
--chunk-collection=${SWB_CHUNK_COLLECTION} \
--chunk-replication=${SWB_CHUNK_REPLICATION} \
--chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \
--chunk-snapshot-schedule=${SWB_CHUNK_SNAPSHOT_SCHEDULE} \
--chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \
--chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \
--workspace-lease=${SWB_WORKSPACE_LEASE} \
@@ -58,6 +58,7 @@ ExecStart=/usr/local/bin/blockvolume \
--chunk-collection=${SWB_CHUNK_COLLECTION} \
--chunk-replication=${SWB_CHUNK_REPLICATION} \
--chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \
--chunk-snapshot-schedule=${SWB_CHUNK_SNAPSHOT_SCHEDULE} \
--chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \
--chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \
--workspace-lease=${SWB_WORKSPACE_LEASE} \
@@ -257,7 +257,11 @@ Snapshots of the target are refused until `Independent`. The driver (`core/host/
### Attached-volume scheduling
Periodic HEAD capture is off by default (opt-in; when set, at least 5
minutes), and retention runs every hour. Named snapshots remain explicit.
minutes), and retention runs every hour. Named snapshots are explicit, plus scheduled snapshots
(`--chunk-snapshot-schedule`, default `daily:7`): one snapshot per period at a
per-volume offset (not at a wall-clock hour), class `scheduled`, the newest N
kept by retention; a restoring volume is skipped and counted, and a failed
attempt is retried with backoff and visible in status (`snapshot_overdue`).
A five-minute context covers the whole cut; completed immutable uploads survive
an expired attempt only under matching version/HEAD generation. Automatic GC is
opt-in until the 50/200-volume metadata/RSS qualification accepts its full-catalog
@@ -287,6 +291,17 @@ intents remain rooted after restart; elapsed TTL is not a settlement proof.
**Master side of a renewal** (`core/authority/workspace_lease_view.go`): blockmaster answers a renewal of an established lease from memory, under a small leaf lock, with no disk write and without waiting for other authority writes. The grant is min(now + TTL, durable horizon), where the horizon is the lease expiry stored on disk; a background extension, an ordinary authority write, keeps the horizon about 1.5·TTL ahead of the last renewal that triggered it. Only the first grant of a lease is written synchronously. If extensions fall behind, grants shrink and the host fences by the horizon minus half the skew bound; a failed extension write makes the volume uncertain and refuses renewals that would issue a new or extended grant (a Revoking lease still gets its bounded drain reply).
**Uncertain move outcomes** (`INV-AUTH-UNCERTAIN-001`): at a failed move's reply boundary, the publisher's per-volume persistence latch takes precedence over request, forced-admission, HEAD-read and target refusals. Such a reply is UNKNOWN with same-request recovery after reload, without another authority write. Only an ended request context preserves typed cancellation/deadline; dependency context errors with a live request are UNKNOWN. A known successful issued replay remains valid.
```mermaid
flowchart LR
E[Move error] --> C{Request context ended?}
C -->|yes| T[Typed caller error]
C -->|no| U{Persistence uncertain at reply?}
U -->|yes| X[UNKNOWN, never definite admission refusal]
U -->|no| R[Ordinary error classification]
```
**CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS �' revoke �' the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation �' blockmaster checks the detached HEAD and the matching acknowledgement �' new epoch �' the new host claims HEAD.
**FORCED move:** blockmaster waits until both the persisted lease horizon (at least every grant, so at most TTL/2 later than the last grant) and the granted or conservative restart deadline, plus the full skew bound, have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost.
+36 -12
View File
@@ -85,6 +85,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a
| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` |
| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` |
| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` |
| Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` |
| Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` |
**Workspace lease and move, in blockmaster.**
@@ -213,7 +214,7 @@ stateDiagram-v2
[*] --> Refused: valid frozen request; frozen_detach_unsupported; no provider call
Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid
Admit --> PlainStop: plain detach and idle frontend lock acquired
PlainStop --> Quiesce: frontend stopped; ordinary detached cut
PlainStop --> Quiesce: idle frontend closed; caller-bounded offline seal
Admit --> FrozenForecast: guest already frozen with an explicit origin
FrozenForecast --> Refused: unknown or non-fitting remaining budget
FrozenForecast --> Quiesce: plausible estimate or explicit final override; skip staging
@@ -247,7 +248,7 @@ stateDiagram-v2
| Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-WS-LEASE-001` |
| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` |
| Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` |
| Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` |
| Plain detach | plain=true acquires exclusive idle frontend admission (closed handles allowed), then StopIO and caller-bounded seal. Busy requests mutate nothing; publication and settlement retain authority/HEAD checks. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` |
| Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` |
| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` |
| Pre-copy detach | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` |
@@ -297,6 +298,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th
| — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` |
| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` |
| published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| published | deleting (retention, class `scheduled`) | the snapshot is not among the newest K of class `scheduled` (K from the newest one's `swb.schedule.keep`, default 7); other classes are planned without it | `core/frontend/chunkstore/retention.go` `planRetention` | `INV-SNAP-SCHEDULED-KEEP-001` |
| published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, write the target `VOLUME`, then its HEAD only before start + deadline; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| restore (Restoring) | Hydrating | M6.Restore.Restoring>Hydrating: the driver starts the walker, paced at a byte rate under the BackgroundFill class | `core/host/volume/chunk_restore.go` `runRestore`; `core/frontend/durable/provider_restore.go` `HydrateVolume`; `core/storage/chunk_hydrate_all.go` `HydrateAllAt` | `INV-RESTORE-HYDRATE-001`, `INV-RESTORE-DRIVER-001` |
@@ -389,9 +391,19 @@ A pass has one minute for retention and optional GC; retention failure skips GC.
A scoped GC pass traces the whole catalog but mutates only its target volume,
with a separate scope/config-bound mark. Incomplete marks carry no coverage.
The scheduled-snapshot worker runs beside it under the same owner and join, on
in-process monotonic time: `Armed -> Due -> Running -> Armed`. A success sets the
next slot (loop start + the volume's offset + whole periods); a failure keeps
its typed code and retries after a backoff doubling from 1 min to 1 h; a
restoring volume (absent chunks) is skipped, counted, and retried within 1 h.
A re-armed loop on the same handle keeps this state; a restart starts fresh.
Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksOff`,
`_RestoringIsSkippedAndCounted`, `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`,
`_RearmKeepsTheSchedule`.
## Part B. Invariant ledger
162 rows: 140 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 147 new.
165 rows: 143 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 150 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -424,14 +436,14 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-OWNER-001` | v3 read/write open and offline readonly open acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go` | `TestWALStoreV3CreatorKeepsOwnershipThroughPublication` (`core/storage/volume_lock_v3_test.go`); `TestWALStoreV3OwnerExcludesOpenAndReadOnly` (`core/storage/volume_lock_v3_test.go`); `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB |
| `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB |
| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB |
| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB |
| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB |
| `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB |
| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB |
| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshAndSetWModeCloseTheWindow` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeWaitsForAHeldBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3InstallingScanErrorIsTypedNotReady` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision` (`core/storage/recovery_v3_test.go`); `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model | STUB |
| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` | STUB |
| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB |
| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack | STUB |
| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records | STUB |
| `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED |
@@ -441,6 +453,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
Notes:
- `INV-AUTH-UNCERTAIN-001` detail: After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. Move error classification reads the per-volume uncertainty latch under the publisher lock at reply time, covering RPC preflight, HEAD reads and local admission as well as the publisher. Only the actual request context proves caller end; a dependency timeout/cancellation with a live request is UNKNOWN too. The unknown outcome overrides the refusal audit entry. It adds no authority write and does not clear uncertainty.
- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged.
- `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes.
@@ -464,13 +478,14 @@ Notes:
| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE |
| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE |
| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE |
| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE |
| `INV-AUTH-UNCERTAIN-001` | Failed workspace writes latch uncertainty until reload. Authority and lease extensions refuse; revoking leases keep bounded drain replies. A failed move is UNKNOWN before admission refusal; request-context cancellation/deadline stays typed. Known issued replays remain valid. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal` (`core/authority/workspace_outcome_uncertain_test.go`), `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (`core/host/master/workspace_uncertain_precedence_test.go`), `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`) | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped`, `UncertainReplyClass` | ACTIVE |
| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceIssuePublishNeverLowersARenewedDeadline` (`core/authority/workspace_issue_publish_test.go`) | — | ACTIVE |
| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that replaces the lease with the new holder's is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE |
| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE |
| `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE |
| `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners (--listen, and the runtime HTTP listener when enabled) bind only loopback unless --insecure-external-bind is given; a non-loopback address is refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_ControlListenersNeedInsecureExternalBind`, `TestManifests_ExternalBlockmasterBindCarriesTheOptIn` (`cmd/blockmaster/external_bind_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE |
Notes:
@@ -508,7 +523,7 @@ Notes:
|---|---|---|---|---|---|---|
| `INV-WS-HEAD-BELT-001` | A takeover confirms its exact HEAD before serving. The supported single-serialization-point mode has W=0; explicit experimental cooling requires W >= the 2 s HEAD operation deadline plus 100 ms settling. Each CAS and confirmation has its own 2 s deadline. A successful cut CAS requires readback before remoteLSN/map settlement and intent cleanup. Unconfirmed roots remain protected through Close; an observed different publication owner fences without retry, even after epoch regression or when the original HEAD was empty. | M4 Claiming → Cooling → Holder; M5 CAS → Confirmed or Pending/Fenced | `core/storage/chunk_head_belt.go`; `chunk_restore.go` `ClaimChunkHead`; `chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach`, `dropIntents`, `Close` | `TestHeadBeltTakeoverRefusesLateOldCAS`; `TestHeadBeltTakeoverWaitsBeforeConfirmation`; `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`; `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`; `TestHeadBeltEmptyBaseForeignPublicationFences`; `TestHeadBeltSinglePointHasNoCoolingDelay`; `TestHeadBeltOperationsHaveOwnDeadline`; `TestHeadBeltCoolingWindowCoversCASAndSettle` (`core/storage/chunk_head_belt_test.go`) | `WorkspaceTakeover` belt extension pending | ACTIVE |
| `INV-WS-HEAD-CAS-001` | Every HEAD publish is conditional on `{gen, epoch}` at one serialization point. A conflicting observed owner fences the publisher. Multiple independent filer serialization points are not made atomic by readback. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE |
| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE |
| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestMemChunkRemote_RefusesLowerRemoteLSN` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE |
| `INV-WS-HEAD-KEY-PROVENANCE-001` | Every key a HEAD names is named by its predecessor HEAD or was uploaded by this owner under an intent that rooted it until the CAS settled; a key that left every root is never named again. | M5 Manifest → CAS | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | — | — | STUB |
| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE |
| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE |
@@ -539,8 +554,8 @@ Notes:
|---|---|---|---|---|---|---|
| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE |
| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE |
| `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE |
| `INV-WS-FREEZE-ACCOUNTING-001` | (Not reachable in this release; see Notes.) Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE |
| `INV-CUT-PLAIN-DETACH-001` | Plain detach excludes entering/admitted I/O, then seals under the caller context, including a closed idle frontend. Publication and unknown/fenced settlement remain enforced. Closed frontend handles never reopen; absent/false preserves live policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` ; `TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` (`core/frontend/durable/provider_offline_seal_test.go`); `TestChunkPlainDetachUsesCallerDeadline`, `TestChunkPlainDetachRequiresExplicitBound` (`core/host/volume/chunk_offline_seal_test.go`) | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE |
| `INV-WS-FREEZE-ACCOUNTING-001` | (Not reachable in this release; see Notes.) Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRequestRefusalCarriesNoBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE |
| `INV-WS-FREEZE-REFUSAL-001` | HTTP400 `invalid_freeze_budget`, retryable=false, is emitted only for frozen-request validation before any provider admission or mutation. Missing/zero/future origin, override without frozen, and frozen+plain preserve that boundary. Generic `bad_request` is not a clean-refusal proof. Terminal and unknown-publication causes retain precedence; no production path emits this typed code after mutation. | G frozen detach: request → refused before admission (M5) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode`, `TestFrozenValidationPrecedesAnyProviderAccess` | — (wire classification; validation/admission guards unchanged) | ACTIVE |
| `INV-CUT-PRECOPY-001` | (Not reachable in this release; see Notes.) Resume grants waiters FIFO under one lock; gates and completion are independent. Each command keeps its arrival/caller bound. Only pause refusals requeue; stale and terminal errors survive. Detached handoff requires settled publication. See Notes for admission and freeze guards. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyResumeReleasesAllWaiters` (FIFO grants under one lock, concurrent outstanding I/O), `TestPrecopyResumedArrivalDoesNotInheritExpiredPause`, `TestPrecopyQueueBoundStartsAtCommandArrival`, `TestPrecopyResumeGrantVersusExpiry`, `TestPrecopyGrantedWaiterFollowsReplacementPause`, `TestPrecopyNewPauseCannotEraseObservedStalePrimary`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE |
| `INV-CUT-FROZEN-DETACH-REFUSED-001` | A detach request with `frozen` set is refused with HTTP409 `frozen_detach_unsupported`, retryable=false, before any provider call, admission or cut work. | M5 [*] → Refused (valid frozen request) | `core/host/volume/chunk_control.go` `handleChunkDetach` | `TestChunkDetachFrozenRefusedBeforeProvider` (`core/host/volume/chunk_frozen_refused_test.go`), `TestChunkFrozenDetachWireContractAndPrecedence`, `TestChunkFrozenRequestRefusalCarriesNoBudget` (`core/host/volume/chunk_frozen_budget_test.go`) | — (request refusal) | ACTIVE |
@@ -565,12 +580,13 @@ Notes:
| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE |
| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE |
| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE |
| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind (explicit, snapshot, detach, no-op) restarts the periodic timer. A periodic cut the loop decided from an older last cut, while another cut was still running, is skipped under the capture lock once that cut has completed: no automatic cut follows another cut within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`) | — | ACTIVE |
| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`); `TestCutPolicy_TimerRunsOnObservationTime` (`core/frontend/durable/cut_policy_test.go`); `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`) | — | ACTIVE |
A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks.
Notes:
- `INV-CUT-TIMER-RESTART-001`: cuts are identified and ordered by the layer's in-process `CutSeq`, never by the `LastCutNs` wall stamp: a `CutSeq` not seen before is a success at the moment it is observed, and a periodic decision is skipped once `CutSeq` has moved; at start the existing value is not new, so a restart keeps the startup phase. The scheduled-snapshot worker (`INV-SNAP-SCHEDULED-KEEP-001`) runs on the same monotonic time: slots are the loop start plus the volume's offset plus whole periods; a re-armed loop on the same handle keeps its schedule (failures, retry time); a restart starts a fresh one. Tests: `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`, `_OverdueWithNoSuccess`, `TestSnapshotSchedule_SlotsAreOffsetPerVolume`.
- Not reachable in this release: `INV-WS-FREEZE-ACCOUNTING-001` and `INV-CUT-PRECOPY-001`. `/chunk/detach` refuses `frozen` (`INV-CUT-FROZEN-DETACH-REFUSED-001`) and blockvolume refuses `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`), so neither the frozen admission nor the pre-copy admission runs in a released process. Their code is kept and their tests below the HTTP handler still assert them, so their status stays ACTIVE. For the same reason the pre-copy policy that `INV-CUT-PLAIN-DETACH-001` keeps for an absent or false `plain` field is always off. `INV-WS-FREEZE-REFUSAL-001` stays reachable: its HTTP400 validation runs before the refusal.
- `INV-CUT-PRECOPY-001`: Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; on resume every queued waiter is granted in arrival order under one lock hold; each then passes the normal gate; completion is unordered. The ended pause is cleared before those normal gate checks; queue deadlines are measured once from each command arrival and capped by five seconds or its earlier caller deadline, so independent I/O is concurrent and later arrivals cannot inherit an expired pause; host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting.
@@ -587,7 +603,7 @@ Notes:
| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE |
| `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE |
| `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE |
| `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE |
| `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and the scheduled-snapshot worker and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass`, `TestScheduledSnapshotLoop_StopJoinsTheAttempt` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE |
| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. An owner-qualified ref roots the owner's key (load-bearing for forks and restores: a target's HEAD keeps the source's chunks live after the source snapshot and volume are gone). | M6 key: Bound → Tombstoned; M6 snapshot: published → fork \| restore | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`); `TestRestore_GCRootsQualifiedRefsWithSnapshotAndSourceGone` (`core/frontend/chunkstore/restore_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete`; `RestoreIndependence` `NoGap` | ACTIVE |
| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE |
| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE |
@@ -601,6 +617,7 @@ Notes:
| `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after its cut's HEAD CAS is confirmed (every referenced chunk uploaded first) and its attempt entry is confirmed by its exclusive create or a read-back; an unknown outcome of either reports failure, and an unknown create keeps the snapshot's intent. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `createResolved` | `TestCatalog_SnapshotUncertainCreateKeepsIntent`, `TestCatalog_SnapshotAppliedResponseLostIsConfirmed` (`core/frontend/chunkstore/catalog_settle_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE |
| `INV-FORK-FROM-SEALED-001` | A fork reads only a published, active snapshot: a name with no published attempt or an aborted one is `snapshot_not_found`, a deleting one is `snapshot_deleting`, and every attempt of a fork, a retry included, reads the parent again. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `resolveSnap` | `TestFork_RefusalsAndDeadline` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_SweepTombstonesADeadSnapshotAttempt` (`core/frontend/chunkstore/catalog_held_create_test.go`); `TestCatalog_ForkAfterTheMarkRefuses` (`core/frontend/chunkstore/retention_review_test.go`); `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ChunkLifecycleFixed` models the snapshot as a name record plus an attempt path; no fork-from-unpublished property | ACTIVE |
| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE |
| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retention.go` `planRetention`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retention_test.go`) | — | ACTIVE |
| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE |
| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE |
| `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE |
@@ -621,7 +638,7 @@ Notes:
| `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE |
| `INV-RESTORE-DRIVER-001` | The restore driver decides only from the target's VOLUME, HEAD and marker (never the source), writes the marker only after a batch leaves no foreign ref, and a rerun resumes from the target's remote state. | M6.Restore (all transitions) | `core/host/volume/chunk_restore.go` `runRestore`, `chunkControl.Restore` | `TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly`, `TestRestoreDriver_ResumesAfterAFailedBatch`, `TestRestoreDriver_RefusesAVolumeNotMadeByRestore` (`core/host/volume/chunk_restore_test.go`) | `RestoreIndependence` `Independent`, `StateRemote` | ACTIVE |
| `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE |
| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot` | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — | ACTIVE |
| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot`, `sealSnapshot` (explicit and scheduled snapshots) | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — | ACTIVE |
| `INV-PUBLISH-SETTLED-001` | With `OnPublishSettled` set, each confirmed publication (a new HEAD generation) is delivered once, in publication order, one at a time, outside the capture and state locks. After Close begins, no report is dequeued. | M5 CAS → Settled; M6 HEAD: published | `core/storage/chunk_publish_settled.go` `noteSettled`, `unlockCap`, `runPublishSettled`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestChunkPublishSettled_ReportsEachPublication`, `TestChunkPublishSettled_ReportsALatePublication`, `TestChunkPublishSettled_ClosedAndUnset`, `TestChunkPublishSettled_OverlappingPublishersStayOrdered`, `TestChunkPublishSettled_CloseDropsUnstartedReports`, `TestChunkPublishSettled_HookThatPublishes`, `TestChunkPublishSettled_PeriodicCutReports` (`core/storage/chunk_publish_settled_test.go`); `TestWALStoreChunk_PublishSettledHook` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE |
Notes:
@@ -680,6 +697,12 @@ Notes:
|---|---|---|---|---|---|---|
| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE |
### B.9 Security: gRPC links
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|---|---|---|---|---|---|---|
| `INV-SEC-ONE-SEAM-001` | Every production gRPC client and server is built by core/rpc/link; a non-test file outside it that constructs a gRPC client or server or insecure credentials, under any import name, fails the guard test. | AUTHORITY: every gRPC link (client dial, server build) | `core/rpc/link` `Dial`, `DialWith`, `NewServer` | `TestLink_NoProductionSiteBypassesTheSeam`, `TestLink_GuardDetectsRawConstructionsAndAliases`, `TestLink_DialReachesNewServerUnaryAndStream`, `TestLink_ServerRunsInterceptorsInOrder` (`core/rpc/link/link_test.go`) | — (no state machine; the guard test is the proof form) | ACTIVE |
### Experimental data-file synchronization
| ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status |
@@ -728,6 +751,7 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a
| Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work |
|---|---|---|---|---|
| Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; HTTP requires positive timeoutMs before provider dispatch; no live-serving timer | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. |
| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. |
Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes.
+11 -10
View File
@@ -3,17 +3,18 @@
\* remain the existing detach/cut obligations, outside this abstraction.
EXTENDS Naturals, TLC
CONSTANT IdleGuard
VARIABLES phase, readers
vars == <<phase, readers>>
Init == /\ phase = "serving" /\ readers = 0
BeginIO == /\ phase = "serving" /\ readers < 2
/\ readers' = readers + 1 /\ UNCHANGED phase
EndIO == /\ readers > 0 /\ readers' = readers - 1 /\ UNCHANGED phase
VARIABLES phase, readers, closed
vars == <<phase, readers, closed>>
Init == /\ phase = "serving" /\ readers = 0 /\ closed = FALSE
BeginIO == /\ phase = "serving" /\ ~closed /\ readers < 2
/\ readers' = readers + 1 /\ UNCHANGED <<phase, closed>>
EndIO == /\ readers > 0 /\ readers' = readers - 1 /\ UNCHANGED <<phase, closed>>
Plain == /\ phase = "serving" /\ (~IdleGuard \/ readers = 0)
/\ phase' = "stopped" /\ UNCHANGED readers
Publish == /\ phase = "stopped" /\ phase' = "detached" /\ UNCHANGED readers
Abort == /\ phase = "stopped" /\ phase' = "serving" /\ UNCHANGED readers
Next == BeginIO \/ EndIO \/ Plain \/ Publish \/ Abort
/\ phase' = "stopped" /\ UNCHANGED <<readers, closed>>
Publish == /\ phase = "stopped" /\ phase' = "detached" /\ UNCHANGED <<readers, closed>>
Abort == /\ phase = "stopped" /\ phase' = "serving" /\ UNCHANGED <<readers, closed>>
Close == /\ ~closed /\ closed' = TRUE /\ UNCHANGED <<phase, readers>>
Next == Close \/ BeginIO \/ EndIO \/ Plain \/ Publish \/ Abort
Spec == Init /\ [][Next]_vars
IdleAtStop == phase \in {"stopped", "detached"} => readers = 0
=============================================================================
+55
View File
@@ -516,4 +516,59 @@ limit 50, no physical I/O latency. Raw quantities and JSON preservation are
checked by native Go tests; this derived arithmetic model does not model the HTTP
encoder, sampler atomicity, orchestrator timing or an unbounded estimator overrun.
2026-11-21 offline-seal extension: `PlainDetach` now includes frontend Close,
which disables new readers without discarding readers already admitted. An idle
closed frontend may enter PlainStop; abort does not clear its closed bit.
`cfg/PlainDetach.cfg` exhausts 18 generated / 10 distinct states, depth 4, queue
empty (TLC 2.19 with the tools hash above). `PlainDetach_no_idle.cfg` violates
`IdleAtStop` in 8 distinct states. This remains an admission model, not a timing
model. Caller deadline and cancellation are witnessed natively by
`TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` and
`TestChunkPlainDetachUsesCallerDeadline`; live-detach bounds retain their tests.
The HTTP plain caller must supply positive timeoutMs; `TestChunkPlainDetachRequiresExplicitBound` witnesses rejection before provider dispatch.
### Workspace move reply precedence
`WorkspaceMoveOutcome.tla` covers M2's `Uncertain -> Uncertain (move answer)`
transition and `INV-AUTH-UNCERTAIN-001`. One volume can receive one failed
workspace write (landed or not), one error from request validation, forced
preflight, HEAD read, target or endpoint admission, or a caller cancellation /
deadline. The write may fail before or after the error is selected. Reply-time
classification must never report a definite refusal while uncertainty is
observed; caller cancellation/deadline stays typed. No authority changes are
modeled here: journal durability, lease safety, RPC delivery and reload remain
with their existing specs and native controls.
TLC 2.19 (tools SHA256
`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`),
2026-11-21: `cfg/WorkspaceMoveOutcome.cfg` exhausted 59 generated / 45 distinct
states, depth 4, queue empty. Bounds: one volume, seven error causes, one failed
write with Boolean durable outcome, one reply. `NoFalseRefusal` and
`CallerEndTyped` hold. The `BypassUncertainty=TRUE` negative must violate
`NoFalseRefusal`; native controls map to
`TestWorkspaceUncertaintyPrecedesRequestRefusal` (publisher validation),
`TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (real gRPC preflight/HEAD/
target paths, uncertainty before the call or during HEAD read, plus direct
server caller-end classification), and the retained
`TestWorkspaceUncertainIssueWriteIsTyped` (issue failure and replay after reload).
The new tests use a real file-store rename followed by an injected error;
a readout verifies that the failed write actually landed while memory rolled
back. They also check no new authority epoch/move and per-volume scope.
2026-11-21 caller-provenance fold: `cfg/WorkspaceMoveOutcome.cfg` exhausts
223 generated / 135 distinct states, depth 5, queue empty (TLC 2.19 above).
Bounds remain one volume, seven dependency/admission causes, one failed write
and one reply; the actual request independently remains live or ends canceled /
deadline. `NoFalseRefusal`, `CallerEndTyped` and `UncertainReplyClass` hold.
`ConfuseDependencyEnd=TRUE` violates `UncertainReplyClass` (69 distinct states
before the counterexample); `BypassUncertainty=TRUE` violates `NoFalseRefusal`
(54 distinct states). The dependency-confusion negative maps to the live-parent
HEAD-read deadline/cancellation controls in
`TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` and the live-context helper
controls in `TestWorkspaceUncertaintyPrecedesRequestRefusal`. Actual request
cancellation retains its own controls, including a conflicting dependency status.
These are reply-classification claims, not authority-durability or delivery proof.
#344 review qualification: `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation` covers the known observation. (The HTTP-level drain refusal test was removed when `/chunk/detach` stopped admitting frozen requests in this release.) `TestFrozenSaturatedTailRemainsKnownButNonActionable` and the literal 60 s/61 s candidate cases preserve the existing saturation sentinel (zero slack, not a complete duration). These native controls add no model claim or admission guard.
@@ -0,0 +1,33 @@
------------------------- MODULE WorkspaceMoveOutcome -------------------------
EXTENDS Naturals, FiniteSets
CONSTANTS BypassUncertainty, ConfuseDependencyEnd
VARIABLES uncertain, landed, cause, callerEnd, reply, uncertainAtReply
vars == <<uncertain, landed, cause, callerEnd, reply, uncertainAtReply>>
Causes == {"request", "forced_preflight", "head", "target", "endpoint",
"dependency_canceled", "dependency_deadline"}
Init == /\ uncertain = FALSE /\ landed = FALSE /\ cause = "none"
/\ callerEnd = "live" /\ reply = "none" /\ uncertainAtReply = FALSE
FailedWrite == /\ ~uncertain /\ reply = "none"
/\ uncertain' = TRUE /\ landed' \in BOOLEAN
/\ UNCHANGED <<cause, callerEnd, reply, uncertainAtReply>>
AdmissionError == /\ cause = "none" /\ reply = "none"
/\ cause' \in Causes
/\ UNCHANGED <<uncertain, landed, callerEnd, reply, uncertainAtReply>>
CallerEnds == /\ callerEnd = "live" /\ reply = "none"
/\ callerEnd' \in {"canceled", "deadline"}
/\ UNCHANGED <<uncertain, landed, cause, reply, uncertainAtReply>>
DependencyEnd == cause \in {"dependency_canceled", "dependency_deadline"}
Reply == /\ cause # "none" /\ reply = "none"
/\ reply' = IF callerEnd # "live" THEN callerEnd
ELSE IF ConfuseDependencyEnd /\ DependencyEnd
THEN IF cause = "dependency_canceled" THEN "canceled" ELSE "deadline"
ELSE IF uncertain /\ ~BypassUncertainty THEN "unknown"
ELSE "refused"
/\ uncertainAtReply' = uncertain
/\ UNCHANGED <<uncertain, landed, cause, callerEnd>>
Next == FailedWrite \/ AdmissionError \/ CallerEnds \/ Reply
Spec == Init /\ [][Next]_vars
NoFalseRefusal == ~(reply = "refused" /\ uncertainAtReply)
CallerEndTyped == callerEnd # "live" /\ reply # "none" => reply = callerEnd
UncertainReplyClass == uncertainAtReply /\ callerEnd = "live" /\ reply # "none" => reply = "unknown"
=============================================================================
@@ -0,0 +1,3 @@
SPECIFICATION Spec
CONSTANTS BypassUncertainty = FALSE ConfuseDependencyEnd = FALSE
INVARIANTS NoFalseRefusal CallerEndTyped UncertainReplyClass
@@ -123,6 +123,7 @@ the example units, which turn them into flags. blockvolume itself reads only
| `SWB_CHUNK_PATH` | `--chunk-path` | `/swblock/chunks` | Filer directory, one directory per volume |
| `SWB_CHUNK_COLLECTION`, `SWB_CHUNK_REPLICATION` | `--chunk-collection`, `--chunk-replication` | empty (filer default) | Placement of chunk needles |
| `SWB_CHUNK_CAPTURE_INTERVAL` | `--chunk-capture-interval` | `0` (no timer) | Automatic cut interval, e.g. `15m` |
| `SWB_CHUNK_SNAPSHOT_SCHEDULE` | `--chunk-snapshot-schedule` | `daily:7` | Scheduled named snapshots: `daily:N` or `weekly:N` (one per period at a per-volume offset, the newest N kept), or `off` |
| `SWB_CHUNK_UPLOAD_CONCURRENCY` | `--chunk-upload-concurrency` | `8` | Parallel chunk uploads (1..64) |
| `SWB_CHUNK_CONTROL_ENDPOINT` | `--chunk-control-endpoint` | `false` | `/chunk/*` routes on the status listener |
| `SWB_WORKSPACE_LEASE` | `--workspace-lease` | `false` | Require a master lease; fail closed without one |
+11
View File
@@ -273,11 +273,22 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Chunk.Stats.LastCut.BarrierOverBound` | bool | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. |
| `Volumes[].Chunk.Stats.LastCutH` | uint64 | the LSN the last successful cut published |
| `Volumes[].Chunk.Stats.LastCutNs` | int64 | when it completed (wall clock, Unix ns) |
| `Volumes[].Chunk.Stats.CutSeq` | uint64 | successful cuts of this layer so far (in-process); the latest cut's identity |
| `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. |
| `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. |
| `Volumes[].Chunk.Stats.COWSpillCap` | int64 | COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). |
| `Volumes[].Chunk.Stats.COWSpillCapReason` | string | (group of `COWSpillCap`) COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). (omitted when empty) |
| `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) |
| `Volumes[].Chunk.ScheduledSnapshot` | object | the scheduled-snapshot state; absent when the schedule is off or its loop has not started (omitted when empty) |
| `Volumes[].Chunk.ScheduledSnapshot.periodNs` | int64 | PeriodNs is the schedule period; zero means off. |
| `Volumes[].Chunk.ScheduledSnapshot.lastOkNs` | int64 | LastOkNs is when the last scheduled snapshot succeeded; zero: none since the schedule started. |
| `Volumes[].Chunk.ScheduledSnapshot.nextDueNs` | int64 | NextDueNs is when the next attempt is due. |
| `Volumes[].Chunk.ScheduledSnapshot.lastFailure` | object | LastFailure is the last failed attempt since the last success. (omitted when empty) |
| `Volumes[].Chunk.ScheduledSnapshot.lastFailure.code` | string | Code is the failure's code, as the control endpoint reports it. |
| `Volumes[].Chunk.ScheduledSnapshot.lastFailure.atNs` | int64 | AtNs is when the attempt failed. |
| `Volumes[].Chunk.ScheduledSnapshot.attempts` | int | Attempts counts the failed attempts since the last success. |
| `Volumes[].Chunk.ScheduledSnapshot.skipped{}` | int64 | Skipped counts attempts not made, by reason. (omitted when empty) |
| `Volumes[].Chunk.ScheduledSnapshot.snapshot_overdue` | bool | Overdue reports that no scheduled snapshot succeeded within one period plus the retry cap, counted from the last success or, before any, from the start of the schedule. |
| `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |
| `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |
@@ -0,0 +1,185 @@
// Package invcheck checks docs/design/invariants.md against the code: the
// row count it states is the count its tables hold, every Go test a row
// names exists, and an ACTIVE row names at least one test.
package invcheck
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
type invRow struct {
id string
tests []string
status string
line int
}
var (
rowID = regexp.MustCompile("^\\| `(INV-[A-Z0-9-]+)` \\|")
testName = regexp.MustCompile("`(Test[A-Za-z0-9_]+)`")
testFunc = regexp.MustCompile(`(?m)^func (Test[A-Za-z0-9_]+)\(`)
countLine = regexp.MustCompile("(\\d+) (?:`INV-` )?rows: (\\d+) ACTIVE, (\\d+) STUB, (\\d+) ARCHIVED")
)
func repoRoot(t *testing.T) string {
t.Helper()
dir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir
}
parent := filepath.Dir(dir)
if parent == dir {
t.Fatal("go.mod not found above the test directory")
}
dir = parent
}
}
// partB returns the Part B rows of the invariant document and its text.
func partB(t *testing.T, root string) ([]invRow, string) {
t.Helper()
raw, err := os.ReadFile(filepath.Join(root, "docs", "design", "invariants.md"))
if err != nil {
t.Fatal(err)
}
doc := strings.ReplaceAll(string(raw), "\r\n", "\n")
start := strings.Index(doc, "\n## Part B")
end := strings.Index(doc, "\n## Part C")
if start < 0 || end < start {
t.Fatal("invariants.md: Part B or Part C heading not found")
}
firstLine := strings.Count(doc[:start], "\n") + 1
var rows []invRow
for i, line := range strings.Split(doc[start:end], "\n") {
m := rowID.FindStringSubmatch(line)
if m == nil {
continue
}
cells := splitRow(line)
if len(cells) != 7 {
t.Errorf("invariants.md:%d: row %s has %d cells, want 7", firstLine+i, m[1], len(cells))
continue
}
r := invRow{id: m[1], status: strings.TrimSpace(cells[6]), line: firstLine + i}
for _, tm := range testName.FindAllStringSubmatch(cells[4], -1) {
r.tests = append(r.tests, tm[1])
}
rows = append(rows, r)
}
return rows, doc
}
// splitRow splits a table row on unescaped pipes outside code spans.
func splitRow(line string) []string {
line = strings.TrimSpace(line)
line = strings.TrimPrefix(line, "|")
line = strings.TrimSuffix(line, "|")
var cells []string
var cur strings.Builder
inCode := false
for i := 0; i < len(line); i++ {
c := line[i]
switch {
case c == '\\' && i+1 < len(line) && line[i+1] == '|':
cur.WriteString(`\|`)
i++
case c == '`':
inCode = !inCode
cur.WriteByte(c)
case c == '|' && !inCode:
cells = append(cells, cur.String())
cur.Reset()
default:
cur.WriteByte(c)
}
}
return append(cells, cur.String())
}
// goTests returns every top-level Test function name in the repository.
func goTests(t *testing.T, root string) map[string]bool {
t.Helper()
found := map[string]bool{}
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if name := d.Name(); name == ".git" || name == "node_modules" {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, "_test.go") {
return nil
}
src, err := os.ReadFile(path)
if err != nil {
return err
}
for _, m := range testFunc.FindAllSubmatch(src, -1) {
found[string(m[1])] = true
}
return nil
})
if err != nil {
t.Fatal(err)
}
return found
}
func TestInvariantRowsNameExistingTests(t *testing.T) {
root := repoRoot(t)
rows, _ := partB(t, root)
if len(rows) == 0 {
t.Fatal("no INV rows found in Part B")
}
tests := goTests(t, root)
seen := map[string]int{}
for _, r := range rows {
if prev, dup := seen[r.id]; dup {
t.Errorf("invariants.md:%d: %s is also at line %d", r.line, r.id, prev)
}
seen[r.id] = r.line
switch r.status {
case "ACTIVE":
if len(r.tests) == 0 {
t.Errorf("invariants.md:%d: %s is ACTIVE and names no test", r.line, r.id)
}
case "STUB", "ARCHIVED":
default:
t.Errorf("invariants.md:%d: %s has status %q", r.line, r.id, r.status)
}
for _, name := range r.tests {
if !tests[name] {
t.Errorf("invariants.md:%d: %s names %s, which is not a test in this repository", r.line, r.id, name)
}
}
}
}
func TestInvariantRowCountMatchesTables(t *testing.T) {
rows, doc := partB(t, repoRoot(t))
by := map[string]int{}
for _, r := range rows {
by[r.status]++
}
want := fmt.Sprintf("%d rows: %d ACTIVE, %d STUB, %d ARCHIVED", len(rows), by["ACTIVE"], by["STUB"], by["ARCHIVED"])
m := strings.Replace(countLine.FindString(doc), "`INV-` ", "", 1)
if m == "" {
t.Fatalf("invariants.md states no row count; the tables hold: %s", want)
}
if m != want {
t.Fatalf("invariants.md says %q; its tables hold %q", m, want)
}
}