mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Merge branch 'main' into feat/v5-incremental-build
This commit is contained in:
commit
616e9a0a2f
45 files changed
+1045
-1844
No files matched your search
@@ -938,7 +938,11 @@ func runVolume(f flags, exits *processExit) int {
|
||||
shutCancel()
|
||||
}
|
||||
_ = h.Close()
|
||||
return 1
|
||||
code, reason := durableOpenFatalExit(sErr)
|
||||
if reason != "" {
|
||||
return reportWorkspaceExit(workspaceExit{code: code, reason: reason, detail: "the local store was written by a newer version: run a newer binary"})
|
||||
}
|
||||
return code
|
||||
case durableStartupFaulted:
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: durable recovery failed:", evidence)
|
||||
return waitFaultedDurableRecovery(exits.done, h, status, durableProv, evidence)
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//go:build linux && subprocess && chunkstore_integration && systemd_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// Under the shipped unit's restart policy (Restart=on-failure,
|
||||
// RestartPreventExitStatus=78 79), a holder that meets a local store or a
|
||||
// HEAD written by a newer format exits 78 with its reason and systemd does
|
||||
// not start it again: zero restarts after the restart interval, and the
|
||||
// store's bytes and HEAD's record unchanged. The control: a process of the
|
||||
// same unit policy that exits 1 is restarted.
|
||||
func TestSystemdNewerFormatExits78WithoutRestart(t *testing.T) {
|
||||
if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" {
|
||||
t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof")
|
||||
}
|
||||
if os.Geteuid() != 0 {
|
||||
t.Fatal("systemd qualification needs root")
|
||||
}
|
||||
if os.Getenv("CHUNKSTORE_WEED") == "" {
|
||||
t.Fatal("real CHUNKSTORE_WEED binary required")
|
||||
}
|
||||
if err := os.MkdirAll(durable.HostVolumeLockDir, 0o700); err != nil {
|
||||
t.Fatalf("host volume lock directory: %v", err)
|
||||
}
|
||||
fixture := newGAP1Fixture(t)
|
||||
root := fixture.root
|
||||
bin := filepath.Join(root, "bin")
|
||||
if err := os.Mkdir(bin, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"blockvolume", "blockmaster"} {
|
||||
if pre := os.Getenv("SWB_PREBUILT_BIN"); pre != "" { // a host without a Go toolchain: binaries of the same commit
|
||||
raw, err := os.ReadFile(filepath.Join(pre, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(bin, name), raw, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
buildCtx, buildCancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
cmd := exec.CommandContext(buildCtx, "go", "build", "-p", "4", "-o", filepath.Join(bin, name), "../"+name)
|
||||
cmd.WaitDelay = time.Second
|
||||
out, err := cmd.CombinedOutput()
|
||||
buildCancel()
|
||||
if err != nil {
|
||||
t.Fatalf("real binary build: %v %s", err, out)
|
||||
}
|
||||
}
|
||||
shipped := gap1ShippedPolicy(t)
|
||||
stem := fmt.Sprintf("newerfmt-%d", time.Now().UnixNano())
|
||||
|
||||
// Control: the same unit policy restarts a process that exits 1.
|
||||
control1 := stem + "-exit1"
|
||||
fixture.start(t, control1, true, "/bin/sh", "-c", "exit 1")
|
||||
waitGAP1(t, "control: an exit 1 was not restarted under the shipped policy", 30*time.Second, func() bool {
|
||||
return gap1Unit(t, control1)["NRestarts"] != "0"
|
||||
})
|
||||
restarts := gap1Unit(t, control1)["NRestarts"] // read before the stop, which resets it
|
||||
gap1Systemctl(t, "stop", control1)
|
||||
t.Logf("control: exit 1 restarted (NRestarts=%s) under Restart=%s RestartPreventExitStatus=%s", restarts, shipped["Restart"], shipped["RestartPreventExitStatus"])
|
||||
|
||||
cluster := startWorkspaceWeedAt(t, filepath.Join(root, "weed"))
|
||||
gap1PreserveFailure(t, root, cluster.dir)
|
||||
volume := stem
|
||||
base := "/" + stem
|
||||
masterAddr := leaseBinaryAddress(t)
|
||||
target, masterListen := gap1TargetAddresses(t, masterAddr)
|
||||
dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t)
|
||||
cfg := fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\n - server_id: s2\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n - id: %s\n size_bytes: 262144\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r1\n source: existing_replica\n", dataAddr, ctrlAddr, target.dataAddr, target.ctrlAddr, volume)
|
||||
spec := filepath.Join(root, "cluster.yaml")
|
||||
if err := os.WriteFile(spec, []byte(cfg), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tlsDir := gap1WriteTLS(t, root, target)
|
||||
fixture.start(t, stem+"-master", false, filepath.Join(bin, "blockmaster"),
|
||||
"--listen", masterListen, "--tls-cert", filepath.Join(tlsDir, "master.crt"), "--tls-key", filepath.Join(tlsDir, "master.key"),
|
||||
"--tls-client-ca", filepath.Join(tlsDir, "ca.crt"), "--role-file", filepath.Join(tlsDir, "roles"), "--audit-log", filepath.Join(tlsDir, "audit.log"), "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"),
|
||||
"--cluster-spec", spec, "--lifecycle-product-loop-interval", "200ms", "--expected-slots-per-volume", "1",
|
||||
"--workspace-rpc", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base)
|
||||
w4WaitTCP(t, masterAddr, 20*time.Second)
|
||||
admin, err := link.ClientCredentials(link.TLSFiles{Cert: filepath.Join(tlsDir, "admin.crt"), Key: filepath.Join(tlsDir, "admin.key"), CA: filepath.Join(tlsDir, "ca.crt")}, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn, err := grpc.NewClient(masterAddr, admin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
var layoutID layout.VolumeID
|
||||
waitGAP1(t, "master never resolved the volume's layout identity", 20*time.Second, func() bool {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
id, e := lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume)
|
||||
layoutID = id
|
||||
return e == nil
|
||||
})
|
||||
store := filepath.Join(root, "store")
|
||||
args := []string{"--master", masterAddr, "--server-id", "s1",
|
||||
"--master-tls-cert", filepath.Join(tlsDir, "s1.crt"), "--master-tls-key", filepath.Join(tlsDir, "s1.key"), "--master-ca", filepath.Join(tlsDir, "ca.crt"),
|
||||
"--volume-id", volume, "--replica-id", "r1", "--layout-id", layoutID.String(),
|
||||
"--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--heartbeat-interval", "200ms", "--t1-readiness", "--status-addr", statusAddr,
|
||||
"--durable-root", store, "--durable-impl", "walstore-chunk", "--durable-blocks", "64",
|
||||
"--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease",
|
||||
"--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:" + stem}
|
||||
bootstrap := stem + "-bootstrap"
|
||||
fixture.start(t, bootstrap, false, filepath.Join(bin, "blockvolume"), args...)
|
||||
waitGAP1(t, "bootstrap did not attach under a real lease", 60*time.Second, func() bool { return gap1Operational(t, statusAddr, volume) })
|
||||
gap1Systemctl(t, "stop", bootstrap)
|
||||
waitGAP1(t, "bootstrap still running", 30*time.Second, func() bool { return gap1Unit(t, bootstrap)["MainPID"] == "0" })
|
||||
|
||||
// refusedOnce starts a restarting unit and requires it to exit 78 with
|
||||
// reason, then stay down past the restart interval with zero restarts.
|
||||
refusedOnce := func(unit, reason string) {
|
||||
t.Helper()
|
||||
fixture.start(t, unit, true, filepath.Join(bin, "blockvolume"), args...)
|
||||
waitGAP1(t, unit+": never exited 78", 120*time.Second, func() bool {
|
||||
u := gap1Unit(t, unit)
|
||||
return u["MainPID"] == "0" && u["ExecMainStatus"] == "78"
|
||||
})
|
||||
time.Sleep(12 * time.Second) // past RestartSec (shipped 5s), twice
|
||||
u := gap1Unit(t, unit)
|
||||
if u["NRestarts"] != "0" || u["ExecMainStatus"] != "78" || u["MainPID"] != "0" {
|
||||
t.Fatalf("%s: restarted or running after its 78: %+v", unit, u)
|
||||
}
|
||||
out, _ := exec.Command("journalctl", "-u", unit, "--no-pager", "-o", "cat").CombinedOutput()
|
||||
if want := "exiting status=78 reason=" + reason; !strings.Contains(string(out), want) {
|
||||
t.Fatalf("%s: journal lacks %q:\n%s", unit, want, out)
|
||||
}
|
||||
t.Logf("%s: exit 78 %s, NRestarts=0 after %s", unit, reason, shipped["RestartSec"])
|
||||
gap1Systemctl(t, "reset-failed", unit)
|
||||
}
|
||||
|
||||
// 1. The local store written by a newer format: both descriptor slots
|
||||
// carry the chunk-state marker above what this binary reads.
|
||||
var storeFile string // the one file under the durable root that starts with the store's superblock magic
|
||||
if err := filepath.Walk(store, func(p string, fi os.FileInfo, err error) error {
|
||||
if err != nil || !fi.Mode().IsRegular() || fi.Size() < 8192 {
|
||||
return err
|
||||
}
|
||||
head := make([]byte, 4)
|
||||
if f, err := os.Open(p); err == nil {
|
||||
_, _ = f.Read(head)
|
||||
_ = f.Close()
|
||||
}
|
||||
if string(head) == "SWBK" {
|
||||
if storeFile != "" {
|
||||
t.Fatalf("two stores under %s: %s, %s", store, storeFile, p)
|
||||
}
|
||||
storeFile = p
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if storeFile == "" {
|
||||
t.Fatalf("no store under %s", store)
|
||||
}
|
||||
original, err := os.ReadFile(storeFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
marked := append([]byte(nil), original...)
|
||||
for _, off := range []int{0, 4096} { // descriptor slots A and B, 4096 bytes each, CRC32C in the last 4
|
||||
slot := marked[off : off+4096]
|
||||
binary.LittleEndian.PutUint16(slot[306:], 9) // a chunk-state format newer than any this binary reads
|
||||
binary.LittleEndian.PutUint64(slot[312:], 1)
|
||||
binary.LittleEndian.PutUint32(slot[4092:], crc32.Checksum(slot[:4092], crc32.MakeTable(crc32.Castagnoli)))
|
||||
}
|
||||
if err := os.WriteFile(storeFile, marked, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refusedOnce(stem+"-store", "store_format_newer")
|
||||
if after, err := os.ReadFile(storeFile); err != nil || !bytes.Equal(after, marked) {
|
||||
t.Fatalf("the refused open changed the store (%v)", err)
|
||||
}
|
||||
if err := os.WriteFile(storeFile, original, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 2. A HEAD written by a newer version.
|
||||
ref := chunkstore.VolumeRef{Name: volume, ID: layoutID}
|
||||
cl := cluster.client(t, "")
|
||||
dir := path.Join(base, ref.Dir())
|
||||
ctx := context.Background()
|
||||
entry, err := cl.LookupEntry(ctx, dir, "HEAD")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var head map[string]any
|
||||
if err := json.Unmarshal(entry.Content, &head); err != nil {
|
||||
t.Fatalf("HEAD record: %v", err)
|
||||
}
|
||||
head["version"] = 9
|
||||
newer, err := json.Marshal(head)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry.Content = newer
|
||||
if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refusedOnce(stem+"-head", "head_newer_version")
|
||||
if after, err := cl.LookupEntry(ctx, dir, "HEAD"); err != nil || !bytes.Equal(after.Content, newer) {
|
||||
t.Fatalf("the refused start changed HEAD (%v)", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// exitNewerVersion is a startup outcome that ended on a HEAD written by a
|
||||
// newer version.
|
||||
type exitNewerVersion struct{ exitStartupOutcome }
|
||||
|
||||
func (exitNewerVersion) ChunkStartupNewerVersion(string, uint64) bool { return true }
|
||||
|
||||
// A startup ended on a HEAD written by a newer version exits 78
|
||||
// head_newer_version (no restart: a restart reads the same HEAD), where the
|
||||
// same ended startup otherwise exits the restartable 75.
|
||||
func TestANewerHeadVersionExits78NotRestartable(t *testing.T) {
|
||||
h, _ := exitAuthorityHost(t)
|
||||
e := newProcessExit(context.Background())
|
||||
if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitNewerVersion{exitStartupOutcome{expired: true}}) {
|
||||
t.Fatal("the newer-version startup did not end the process")
|
||||
}
|
||||
if out := <-e.decision; out.code != 78 || out.reason != "head_newer_version" {
|
||||
t.Fatalf("newer-version startup exit = %+v, want 78 head_newer_version", out)
|
||||
}
|
||||
h2, _ := exitAuthorityHost(t)
|
||||
e2 := newProcessExit(context.Background())
|
||||
chooseChunkStartupExit(e2, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h2, &exitStartupOutcome{expired: true})
|
||||
if out := <-e2.decision; out.code != 75 {
|
||||
t.Fatalf("control: an ended startup without the refusal exits %+v, want 75", out)
|
||||
}
|
||||
}
|
||||
|
||||
// A fatal durable open of a store written by a newer format exits 78
|
||||
// store_format_newer; any other fatal open exits 1 as before.
|
||||
func TestAStoreOfANewerFormatExits78(t *testing.T) {
|
||||
if code, reason := durableOpenFatalExit(fmt.Errorf("durable: OpenWALStore x: %w", storage.ErrStoreFormatNewer)); code != 78 || reason != "store_format_newer" {
|
||||
t.Fatalf("newer-format store exit = %d %q, want 78 store_format_newer", code, reason)
|
||||
}
|
||||
if code, reason := durableOpenFatalExit(errors.New("durable: OpenWALStore x: invalid superblock")); code != 1 || reason != "" {
|
||||
t.Fatalf("other fatal open exit = %d %q, want 1", code, reason)
|
||||
}
|
||||
}
|
||||
|
||||
// A master's final refusal keeps its exit when the same startup also ended
|
||||
// on a newer HEAD version: MOVED stays 78 moved, FINAL stays 79 revoked.
|
||||
func TestAMasterFinalExitWinsOverANewerHeadVersion(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
kind control.WorkspaceLeaseRefusal_Kind
|
||||
final string
|
||||
code int
|
||||
reason string
|
||||
}{
|
||||
{control.WorkspaceLeaseRefusal_MOVED, "moved", 78, "moved"},
|
||||
{control.WorkspaceLeaseRefusal_FINAL, "revoked", 79, "revoked"},
|
||||
} {
|
||||
t.Run(tc.final, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
refusal, err := status.New(codes.FailedPrecondition, "final refusal").WithDetails(&control.WorkspaceLeaseRefusal{Kind: tc.kind})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, _ := exitAuthorityHost(t, func(s *exitAssignmentStream) { s.streamRefuse = refusal.Err() })
|
||||
for {
|
||||
if _, final := h.MasterWaitState(); final == tc.final {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("the master's %s refusal never reached the host", tc.final)
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
e := newProcessExit(ctx)
|
||||
if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitNewerVersion{exitStartupOutcome{expired: true}}) {
|
||||
t.Fatal("no startup decision")
|
||||
}
|
||||
if out := <-e.decision; out.code != tc.code || out.reason != tc.reason {
|
||||
t.Fatalf("final %s with a newer HEAD version chose %+v; want %d %s", tc.final, out, tc.code, tc.reason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -136,6 +138,16 @@ func reportWorkspaceExit(out workspaceExit) int {
|
||||
|
||||
// INV-WS-STARTUP-RETRY-001: one decision combines a newer other-replica
|
||||
// authority fact and the provider's generation-bound foreign-HEAD proof.
|
||||
// durableOpenFatalExit is the exit of a fatal durable storage open: 78 with
|
||||
// reason store_format_newer for a store written by a newer format (no
|
||||
// restart can open it), else 1 as before.
|
||||
func durableOpenFatalExit(err error) (int, string) {
|
||||
if errors.Is(err, storage.ErrStoreFormatNewer) {
|
||||
return exitWorkspaceSuperseded, "store_format_newer"
|
||||
}
|
||||
return 1, ""
|
||||
}
|
||||
|
||||
func workspaceRetryOutcome(reason string, h *volume.Host, claimSuperseded bool) workspaceExit {
|
||||
if claimSuperseded || h.IsCurrentReplicaSuperseded() {
|
||||
return workspaceExit{code: exitWorkspaceSuperseded, reason: "superseded"}
|
||||
@@ -262,6 +274,12 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar
|
||||
if identity, ok := p.(interface{ ChunkStartupIdentityRefused(string, uint64) bool }); ok && identity.ChunkStartupIdentityRefused(f.volumeID, gen) {
|
||||
out = workspaceExit{code: exitWorkspaceSuperseded, reason: "layout_identity_mismatch", detail: "VOLUME/HEAD disagrees with --layout-id; retry with the layout id from the master's volume record"}
|
||||
}
|
||||
// A HEAD written by a newer version is permanent for this binary: exit 78,
|
||||
// never the restartable 75 (a restart reads the same HEAD again). A master
|
||||
// final reason below (moved, deleted, revoked) still names the exit.
|
||||
if nv, ok := p.(interface{ ChunkStartupNewerVersion(string, uint64) bool }); ok && nv.ChunkStartupNewerVersion(f.volumeID, gen) {
|
||||
out = workspaceExit{code: exitWorkspaceSuperseded, reason: "head_newer_version", detail: "HEAD was written by a newer version: run a newer binary"}
|
||||
}
|
||||
if h != nil {
|
||||
// Typed MOVED/DELETED refusals exit 78 and a recorded revocation
|
||||
// (FINAL) exits 79 at once; both are permanent,
|
||||
|
||||
@@ -182,13 +182,8 @@ type Publisher struct {
|
||||
// Lease renewal state (workspace_lease_view.go). leaseMu is a memory-only
|
||||
// leaf: lock order p.mu -> leaseMu, never the reverse, and nothing is
|
||||
// acquired, waited on or written while it is held.
|
||||
leaseMu sync.Mutex
|
||||
leaseViews map[string]*leaseView
|
||||
leaseClosing bool
|
||||
leaseStats leaseCounters // guarded by leaseMu
|
||||
leaseLog func(string) // renewal-path notes; nil = log.Print (test seam)
|
||||
extWG sync.WaitGroup
|
||||
extendFailures map[string]int // guarded by mu
|
||||
leaseMu sync.Mutex
|
||||
leaseViews map[string]*leaseView
|
||||
|
||||
// testAfterIssuePublish, when set by a test, runs under mu right after
|
||||
// an issued move's lease view is published.
|
||||
@@ -264,7 +259,6 @@ func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher {
|
||||
workspaceNow: time.Now,
|
||||
workspaceTTL: 30 * time.Second,
|
||||
leaseViews: map[string]*leaseView{},
|
||||
extendFailures: map[string]int{},
|
||||
}
|
||||
for _, opt := range opts {
|
||||
if opt != nil {
|
||||
|
||||
@@ -117,7 +117,15 @@ type storeEnvelope struct {
|
||||
Checksum string `json:"checksum"`
|
||||
}
|
||||
|
||||
const storeEnvelopeVersion = 1
|
||||
// storeEnvelopeVersion is the envelope version this master writes. Version 2
|
||||
// (v1.1) no longer keeps the lease horizon current (a restarted master waits
|
||||
// one period plus skew from its own start instead), so a v1.0.x master,
|
||||
// which trusts that horizon, must refuse such a record: it refuses every
|
||||
// version but 1. This master reads both.
|
||||
const (
|
||||
storeEnvelopeVersion = 2
|
||||
storeEnvelopeVersionV100 = 1
|
||||
)
|
||||
|
||||
// ErrCorruptRecord indicates a single record failed integrity
|
||||
// checks. Callers skip the record and continue — per-volume fail
|
||||
@@ -164,7 +172,7 @@ func decodeEnvelope(raw []byte, expectedVolumeID string) (DurableRecord, error)
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
return DurableRecord{}, fmt.Errorf("%w: decode: %v", ErrCorruptRecord, err)
|
||||
}
|
||||
if env.Version != storeEnvelopeVersion {
|
||||
if env.Version != storeEnvelopeVersion && env.Version != storeEnvelopeVersionV100 {
|
||||
return DurableRecord{}, fmt.Errorf("%w: envelope version %d unsupported", ErrCorruptRecord, env.Version)
|
||||
}
|
||||
want := computeChecksum(env.Body)
|
||||
|
||||
@@ -112,7 +112,12 @@ func goldenWorkspace(t *testing.T, dir string) {
|
||||
if r, err := p.MoveWorkspace(ctx, goldenCleanMove("wm"), predecessorHead); err != nil || !r.Issued {
|
||||
t.Fatalf("clean move of wm: %+v %v", r, err)
|
||||
}
|
||||
now = now.Add(grantTTL + grantTTL/2 + goldenWorkspaceSkew)
|
||||
// The master restarts half a lease after the issue, so the forced move's
|
||||
// barrier is the same instant on v1.0.0 (the persisted issue+1.5*TTL) and
|
||||
// today (the restart floor, restart+TTL): wm's lost range is the same file.
|
||||
now = now.Add(grantTTL / 2)
|
||||
p = goldenWorkspacePublisher(store, &now)
|
||||
now = now.Add(grantTTL + goldenWorkspaceSkew)
|
||||
if r, err := p.MoveWorkspace(ctx, goldenForcedMove("wm"), predecessorHead); err != nil || !r.Issued {
|
||||
t.Fatalf("forced move of wm: %+v %v", r, err)
|
||||
}
|
||||
@@ -153,13 +158,13 @@ func goldenAuthorityFiles(t *testing.T, root string) map[string][]byte {
|
||||
// goldenAuthorityAtV100 is each fixture file's git blob hash as written on
|
||||
// the v1.0.0 tag checkout.
|
||||
var goldenAuthorityAtV100 = map[string]string{
|
||||
"workspace/wa.v3auth.json": "954efb2d8afda475ac856c4dc907d7b58cb719eb",
|
||||
"workspace/wl.v3auth.json": "79dc6696143165fef5b749b9ba81757ba50056b1",
|
||||
"workspace/wa.v3auth.json": "954efb2d8afda475ac856c4dc907d7b58cb719eb",
|
||||
"workspace/wl.v3auth.json": "79dc6696143165fef5b749b9ba81757ba50056b1",
|
||||
"workspace/wm.lostrange.json": "a4f9f6a612eba987297def1f40eea5b92214575d",
|
||||
"workspace/wm.v3auth.json": "c9adcceb41095cf4e5d06f12a442ec4f5fbbc725",
|
||||
"v1.lostrange.json": "cb4200c2742a7c784d4eb2d1beed61a212053608",
|
||||
"v1.v3auth.json": "88642d0ed99d19635e1ff3d2bd2082ecc319643e",
|
||||
"v2.v3auth.json": "fb7a6a3cd8d2c81c955fc130566f6ae93c677c91",
|
||||
"workspace/wm.v3auth.json": "c9adcceb41095cf4e5d06f12a442ec4f5fbbc725",
|
||||
"v1.lostrange.json": "cb4200c2742a7c784d4eb2d1beed61a212053608",
|
||||
"v1.v3auth.json": "88642d0ed99d19635e1ff3d2bd2082ecc319643e",
|
||||
"v2.v3auth.json": "fb7a6a3cd8d2c81c955fc130566f6ae93c677c91",
|
||||
}
|
||||
|
||||
func TestAuthorityGoldenFilesAreTheV100Files(t *testing.T) {
|
||||
@@ -188,6 +193,17 @@ func TestAuthorityStoreWritesTheV100Files(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
goldenAuthority(t, dir)
|
||||
got, want := goldenAuthorityFiles(t, dir), goldenAuthorityFiles(t, goldenAuthorityDir)
|
||||
// The one change since v1.0.0, by the format path: an authority record's
|
||||
// envelope version is 2 (a v1.0.x master refuses it; the body and its
|
||||
// checksum are unchanged, and today's master still reads version 1).
|
||||
for n, b := range want {
|
||||
if strings.HasSuffix(n, ".v3auth.json") {
|
||||
if !bytes.HasPrefix(b, []byte(`{"v":1,`)) {
|
||||
t.Fatalf("%s: the v1.0.0 fixture does not start with envelope version 1", n)
|
||||
}
|
||||
want[n] = append([]byte(`{"v":2,`), b[len(`{"v":1,`):]...)
|
||||
}
|
||||
}
|
||||
var names []string
|
||||
for n := range want {
|
||||
names = append(names, n)
|
||||
|
||||
@@ -336,9 +336,7 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a
|
||||
if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.Holder == "" || s == nil || s.Lease == nil || !s.Lease.Revoking {
|
||||
return fmt.Errorf("workspace revoke ACK: stale or unsolicited")
|
||||
}
|
||||
lease := *s.Lease
|
||||
lease.ExpiresAtNS = min(lease.ExpiresAtNS, p.leaseDeadlineLocked(volume).UnixNano())
|
||||
if p.WorkspaceLeaseValidity(lease) == 0 {
|
||||
if p.deadlineValidity(p.leaseDeadlineLocked(volume), s.Lease.MaxClockSkewNS, p.workspaceNow()) == 0 {
|
||||
return fmt.Errorf("workspace revoke ACK: lease expired; forced move required")
|
||||
}
|
||||
s.Ack = &ack
|
||||
@@ -473,21 +471,18 @@ func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLea
|
||||
}
|
||||
|
||||
// forcedMoveBarrierLocked evaluates forced admission at master time now. It
|
||||
// returns the barrier (the audit bound of the lost range, wall time: the
|
||||
// later of lease expiry and the granted or restart deadline, each plus
|
||||
// skew) whether or not it has passed, and an error while it has not.
|
||||
// Caller holds p.mu.
|
||||
// returns the barrier (the audit bound of the lost range: the granted or
|
||||
// restart deadline plus skew) whether or not it has passed, and an error
|
||||
// while it has not. The deadline is this process's own (the latest grant it
|
||||
// made, or after a restart the restart floor, restart + TTL); the barrier is
|
||||
// that deadline plus the skew bound. No value written by an earlier process
|
||||
// is read. Caller holds p.mu.
|
||||
func (p *Publisher) forcedMoveBarrierLocked(volume string, lease *WorkspaceLease) (lostUntil int64, now time.Time, err error) {
|
||||
now = p.workspaceNow()
|
||||
skew := p.workspaceSkew(lease)
|
||||
deadline := p.leaseDeadlineLocked(volume)
|
||||
// The audit bound only, in wall time: the admission below keeps both
|
||||
// predicates (the deadline's monotonic reading included).
|
||||
lostUntil = time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano()
|
||||
if d := deadline.Add(skew).UnixNano(); d > lostUntil {
|
||||
lostUntil = d
|
||||
}
|
||||
if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) {
|
||||
lostUntil = deadline.Add(skew).UnixNano()
|
||||
if now.Before(deadline.Add(skew)) {
|
||||
return lostUntil, now, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed")
|
||||
}
|
||||
return lostUntil, now, nil
|
||||
|
||||
@@ -16,15 +16,14 @@ func TestDeletionReservationGuardSites(t *testing.T) {
|
||||
"reserveWorkspaceDeletion": true, "NoLiveWorkspaceLease": true,
|
||||
"applyWithWorkspaceMove": true, "MoveWorkspace": true,
|
||||
"RenewWorkspaceLease": true, "firstWorkspaceGrant": true,
|
||||
"regrantWorkspaceLease": true, "extendWorkspaceLease": true,
|
||||
"regrantWorkspaceLease": true,
|
||||
}
|
||||
boundSites := map[string]bool{
|
||||
"publishIssuedLeaseLocked": true, "setLeaseDeadlineLocked": true,
|
||||
"RenewWorkspaceLease": true, "regrantWorkspaceLease": true,
|
||||
"extendWorkspaceLease": true,
|
||||
// Reply-only copies never increase published validity.
|
||||
"WorkspaceLeaseReply": true, "AckWorkspaceRevocation": true,
|
||||
// Copies the published horizon into the leaf view under mu -> leaseMu.
|
||||
"WorkspaceLeaseReply": true,
|
||||
// Copies the persisted lease into the leaf view under mu -> leaseMu.
|
||||
"deriveLeaseLocked": true,
|
||||
// Positive lease construction and publication, or a plain clone.
|
||||
"newWorkspaceLease": true, "firstWorkspaceGrant": true,
|
||||
|
||||
@@ -67,13 +67,15 @@ func TestCommittedDeleteStopsGrantsAndWaitsForTheWholeLease(t *testing.T) {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil {
|
||||
t.Fatal("committed delete extended a holder lease")
|
||||
}
|
||||
// First horizon is 45 s, plus the default skew of 20 s. Host validity
|
||||
// expiring earlier is insufficient evidence for deleting remote data.
|
||||
c.at(64)
|
||||
// The grant is 30 s, plus the default skew of 20 s: no grant this master
|
||||
// made can be valid after 50 s (a restarted master waits for its restart
|
||||
// floor instead). Host validity expiring earlier (30 s minus half the
|
||||
// skew) is insufficient evidence for deleting remote data.
|
||||
c.at(49)
|
||||
if err := p.NoLiveWorkspaceLease(ctx, "v"); err == nil || !strings.Contains(err.Error(), "live until") {
|
||||
t.Fatalf("before durable horizon + skew: %v", err)
|
||||
t.Fatalf("before the grant + skew: %v", err)
|
||||
}
|
||||
c.at(65)
|
||||
c.at(50)
|
||||
if err := p.NoLiveWorkspaceLease(ctx, "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -129,7 +131,7 @@ func TestDeleteReservationPersistenceDoesNotBlockLiveRenewal(t *testing.T) {
|
||||
|
||||
func TestDeleteReservationClosesPausedGrantWriters(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for _, site := range []string{"publication", "first grant", "regrant", "renewal", "extension", "move"} {
|
||||
for _, site := range []string{"publication", "first grant", "regrant", "renewal", "move"} {
|
||||
t.Run(site, func(t *testing.T) {
|
||||
c := newTestClock()
|
||||
store := &deleteGrantStore{}
|
||||
@@ -159,10 +161,6 @@ func TestDeleteReservationClosesPausedGrantWriters(t *testing.T) {
|
||||
switch site {
|
||||
case "publication":
|
||||
done <- p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind})
|
||||
case "extension":
|
||||
p.extWG.Add(1)
|
||||
p.extendWorkspaceLease("v", "r", 1, c.sec(100))
|
||||
done <- nil
|
||||
case "move":
|
||||
_, err := p.MoveWorkspace(ctx, WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "a", TargetHost: "b", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}, WorkspaceHead{Gen: 1, Epoch: 1, Holder: "a/r"})
|
||||
done <- err
|
||||
@@ -189,7 +187,7 @@ func TestDeleteReservationClosesPausedGrantWriters(t *testing.T) {
|
||||
writes := len(store.records)
|
||||
close(resume)
|
||||
err := <-done
|
||||
if site != "extension" && !errors.Is(err, ErrWorkspaceDeleteReserved) {
|
||||
if !errors.Is(err, ErrWorkspaceDeleteReserved) {
|
||||
t.Fatalf("paused %s: %v", site, err)
|
||||
}
|
||||
if len(store.records) != writes {
|
||||
|
||||
@@ -15,7 +15,7 @@ func TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
now := time.Unix(1000, 0)
|
||||
p, issued := cleanMoveToGrantee(t, disk, &now)
|
||||
barrier := issued.Add(grantTTL + grantTTL/2 + p.workspaceSkew(p.WorkspaceState("v").Lease))
|
||||
barrier := issued.Add(grantTTL + p.workspaceSkew(p.WorkspaceState("v").Lease))
|
||||
now = barrier.Add(-time.Nanosecond)
|
||||
if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 2); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") {
|
||||
t.Fatalf("admitted before expiry+skew: %v", err)
|
||||
|
||||
@@ -58,5 +58,4 @@ func TestWorkspaceIssuePublishNeverLowersARenewedDeadline(t *testing.T) {
|
||||
t.Fatal("renewal inside the outstanding grant:", err)
|
||||
}
|
||||
assertLeaseViewMatches(t, p, "after issue and renewal")
|
||||
p.CloseWorkspaceExtenders()
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -40,12 +39,6 @@ func (s *hookStore) Put(r DurableRecord) error {
|
||||
func (s *hookStore) setBefore(f func(DurableRecord) error) { s.before.Store(&f) }
|
||||
func (s *hookStore) setAfter(f func(DurableRecord) error) { s.after.Store(&f) }
|
||||
|
||||
// isExtension reports a lease write that raises the horizon above firstH and
|
||||
// is not a revocation: the extender's write.
|
||||
func isExtension(r DurableRecord, volume string, firstH int64) bool {
|
||||
return r.VolumeID == volume && r.Workspace != nil && r.Workspace.Lease != nil && !r.Workspace.Lease.Revoking && r.Workspace.Lease.ExpiresAtNS > firstH
|
||||
}
|
||||
|
||||
type testClock struct{ ns atomic.Int64 }
|
||||
|
||||
func newTestClock() *testClock {
|
||||
@@ -66,7 +59,6 @@ func (c *testClock) sec(sec float64) time.Time {
|
||||
func newLeasePublisher(t *testing.T, store AuthorityStore, ttl time.Duration, c *testClock) *Publisher {
|
||||
t.Helper()
|
||||
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(ttl, c.now))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders)
|
||||
return p
|
||||
}
|
||||
|
||||
@@ -82,16 +74,6 @@ func bindAndGrant(t *testing.T, p *Publisher, volume, replica string) WorkspaceL
|
||||
return l
|
||||
}
|
||||
|
||||
// waitExtenders joins every admitted extender (tests only; no concurrent
|
||||
// admission while waiting).
|
||||
// waitExtenders joins every admitted extender. No wall-clock bound (#227):
|
||||
// extenders are finite (each makes at most one store write), so the join is
|
||||
// the progress condition; a hang is reported by the go test timeout.
|
||||
func waitExtenders(t *testing.T, p *Publisher) {
|
||||
t.Helper()
|
||||
p.extWG.Wait()
|
||||
}
|
||||
|
||||
// assertLeaseViewMatches checks INV-LEASE-VIEW-001: with p.mu held, every
|
||||
// volume's view equals derive(published state).
|
||||
func assertLeaseViewMatches(t *testing.T, p *Publisher, what string) {
|
||||
@@ -133,9 +115,9 @@ func forcedMove(volume, id string) (WorkspaceMoveRequest, WorkspaceHead) {
|
||||
}
|
||||
|
||||
// The view equals derive(published) after every writer kind: bind, first
|
||||
// grant, extension, endpoint refresh, revocation, ACK, clean move issue, a
|
||||
// move reservation whose issue write fails (uncertain via apply), a failed
|
||||
// extension (uncertain via persistWorkspaceLocked), reload and close.
|
||||
// grant, renewal, endpoint refresh, revocation, ACK, clean move issue, a
|
||||
// move reservation whose issue write fails (uncertain via apply), reload and
|
||||
// close.
|
||||
func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
hs := &hookStore{AuthorityStore: disk}
|
||||
@@ -165,11 +147,10 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != c.sec(55).UnixNano() || got <= firstH {
|
||||
t.Fatalf("extension did not publish trigger+1.5*TTL: %d", got)
|
||||
if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != firstH {
|
||||
t.Fatalf("a renewal changed the persisted lease: %d, was %d", got, firstH)
|
||||
}
|
||||
check("extension")
|
||||
check("renewal")
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d2", CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -193,7 +174,7 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) {
|
||||
t.Fatalf("move issue deadline %s; want the new holder's issue+TTL %s", got, c.sec(40))
|
||||
}
|
||||
// w: forced move whose issue write fails after the reservation persisted.
|
||||
c.at(30 + 15 + 20 + 1) // past w's horizon (45) + skew (20)
|
||||
c.at(30 + 20 + 1) // past w's deadline (30) + skew (20)
|
||||
hs.setBefore(func(r DurableRecord) error {
|
||||
if r.VolumeID == "w" && r.Workspace != nil && len(r.Workspace.Moves) > 0 && r.Workspace.Moves[len(r.Workspace.Moves)-1].Issued {
|
||||
return errors.New("injected issue write failure")
|
||||
@@ -208,29 +189,6 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) {
|
||||
if st := p.WorkspaceState("w"); len(st.Moves) != 1 || st.Moves[0].Issued {
|
||||
t.Fatalf("reservation not published: %+v", st)
|
||||
}
|
||||
// x: a failed extension latches uncertainty.
|
||||
c.at(0)
|
||||
p2Disk, _ := newTempStore(t)
|
||||
hs2 := &hookStore{AuthorityStore: p2Disk}
|
||||
p2 := newLeasePublisher(t, hs2, 30*time.Second, c)
|
||||
bindAndGrant(t, p2, "x", "r")
|
||||
firstX := p2.WorkspaceState("x").Lease.ExpiresAtNS
|
||||
hs2.setBefore(func(r DurableRecord) error {
|
||||
if isExtension(r, "x", firstX) {
|
||||
return errors.New("injected extension write failure")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
c.at(10)
|
||||
if _, err := p2.RenewWorkspaceLease(ctx, "x", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitExtenders(t, p2)
|
||||
assertLeaseViewMatches(t, p2, "failed extension (uncertain via persistWorkspaceLocked)")
|
||||
if !p2.workspaceUncertainForTest("x") {
|
||||
t.Fatal("failed extension did not latch uncertainty")
|
||||
}
|
||||
p.CloseWorkspaceExtenders()
|
||||
check("close")
|
||||
reloaded := newLeasePublisher(t, disk, 30*time.Second, c)
|
||||
assertLeaseViewMatches(t, reloaded, "reload")
|
||||
@@ -248,237 +206,6 @@ func (p *Publisher) workspaceUncertainForTest(v string) bool {
|
||||
return p.workspaceUncertain[v]
|
||||
}
|
||||
|
||||
// Control 1: with the store stalled for good, grants shrink to the durable
|
||||
// horizon, a renewal that would leave no host validity is refused, and a
|
||||
// renewal at the horizon is refused. The stall is exercised by the extender
|
||||
// (puts > 0), so a green cannot bypass it.
|
||||
func TestWorkspaceLeaseClampsToHorizonUnderStalledStore(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
hs := &hookStore{AuthorityStore: disk}
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, hs, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
horizon := p.WorkspaceState("v").Lease.ExpiresAtNS // 1045
|
||||
var puts atomic.Int64
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
var enterOnce, releaseOnce sync.Once
|
||||
hs.setBefore(func(r DurableRecord) error {
|
||||
if isExtension(r, "v", horizon) {
|
||||
puts.Add(1)
|
||||
enterOnce.Do(func() { close(entered) })
|
||||
<-release
|
||||
}
|
||||
return nil
|
||||
})
|
||||
t.Cleanup(func() { releaseOnce.Do(func() { close(release) }) }) // before Close joins
|
||||
ctx := context.Background()
|
||||
c.at(10)
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("extender never reached the store")
|
||||
}
|
||||
c.at(20)
|
||||
start := time.Now()
|
||||
l, err := p.RenewWorkspaceLease(ctx, "v", "r", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if took := time.Since(start); took > time.Second {
|
||||
t.Fatalf("renewal waited %s behind the stalled extender", took)
|
||||
}
|
||||
if l.ExpiresAtNS > horizon {
|
||||
t.Fatalf("grant %s beyond the durable horizon %s", time.Unix(0, l.ExpiresAtNS), time.Unix(0, horizon))
|
||||
}
|
||||
if l.ExpiresAtNS != horizon {
|
||||
t.Fatalf("grant not clamped to the horizon: %s", time.Unix(0, l.ExpiresAtNS))
|
||||
}
|
||||
c.at(35) // horizon - skew/2 = 1035: no positive host validity
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil || !strings.Contains(err.Error(), "no host validity") {
|
||||
t.Fatalf("renewal without host validity: %v", err)
|
||||
}
|
||||
c.at(45)
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil {
|
||||
t.Fatal("renewal at the durable horizon accepted")
|
||||
}
|
||||
if puts.Load() == 0 {
|
||||
t.Fatal("the stall was never exercised by an extender write")
|
||||
}
|
||||
}
|
||||
|
||||
// Control 2: a restarted master honours the persisted (extended) horizon in
|
||||
// the forced barrier: max(horizon, restart+TTL) + skew.
|
||||
func TestWorkspaceRestartForcedBarrierHonoursHorizon(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, disk, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
c.at(10)
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != c.sec(55).UnixNano() {
|
||||
t.Fatalf("extension not durable: %s", time.Unix(0, got))
|
||||
}
|
||||
p.CloseWorkspaceExtenders()
|
||||
c.at(12)
|
||||
r := newLeasePublisher(t, disk, 30*time.Second, c) // reload deadline 1042 < horizon 1055
|
||||
q, h := forcedMove("v", "forced")
|
||||
c.ns.Store(c.sec(75).UnixNano() - 1)
|
||||
if _, err := r.MoveWorkspace(context.Background(), q, h); err == nil {
|
||||
t.Fatal("forced move before persisted horizon + skew after restart")
|
||||
}
|
||||
c.at(75)
|
||||
if _, err := r.MoveWorkspace(context.Background(), q, h); err != nil {
|
||||
t.Fatal("forced move at horizon + skew refused:", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Control 3: an extension whose rename landed but whose directory sync
|
||||
// failed is an unknown write: the volume is uncertain, the next renewal is
|
||||
// refused (INV-AUTH-UNCERTAIN-001), and a reload finds the landed horizon and
|
||||
// bars a forced move until that horizon + skew.
|
||||
func TestWorkspaceAmbiguousExtensionLatchesUncertainty(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
hs := &hookStore{AuthorityStore: disk}
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, hs, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
first := p.WorkspaceState("v").Lease.ExpiresAtNS
|
||||
hs.setAfter(func(r DurableRecord) error {
|
||||
if isExtension(r, "v", first) {
|
||||
return errors.New("injected: failure after the rename")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
c.at(10)
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != first {
|
||||
t.Fatalf("an unknown write was published: %s", time.Unix(0, got))
|
||||
}
|
||||
c.at(11)
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil || !strings.Contains(err.Error(), "uncertain") {
|
||||
t.Fatalf("renewal after an unknown write: %v; want refused as uncertain", err)
|
||||
}
|
||||
// INV-AUTH-UNCERTAIN-001: every further authority change of the volume
|
||||
// is refused until a restart.
|
||||
if err := p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1); err == nil {
|
||||
t.Fatal("revocation accepted on an uncertain volume")
|
||||
}
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d2", CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err == nil {
|
||||
t.Fatal("authority change accepted on an uncertain volume")
|
||||
}
|
||||
p.CloseWorkspaceExtenders()
|
||||
c.at(12)
|
||||
r := newLeasePublisher(t, disk, 30*time.Second, c)
|
||||
landed := r.WorkspaceState("v").Lease.ExpiresAtNS
|
||||
if landed != c.sec(55).UnixNano() {
|
||||
t.Fatalf("reload did not find the landed horizon: %s", time.Unix(0, landed))
|
||||
}
|
||||
q, h := forcedMove("v", "forced")
|
||||
c.ns.Store(time.Unix(0, landed).Add(20*time.Second).UnixNano() - 1)
|
||||
if _, err := r.MoveWorkspace(context.Background(), q, h); err == nil {
|
||||
t.Fatal("forced move before the landed horizon + skew")
|
||||
}
|
||||
c.ns.Store(time.Unix(0, landed).Add(20 * time.Second).UnixNano())
|
||||
if _, err := r.MoveWorkspace(context.Background(), q, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Control 4: an extender held inside its Put holds p.mu; a revocation or a
|
||||
// forced move of the same volume waits, then runs after the extension is
|
||||
// published, so its record carries the extended horizon (ordered).
|
||||
func TestWorkspaceExtenderHeldOrdersSameVolumeWriters(t *testing.T) {
|
||||
for _, op := range []string{"revocation", "forced-move"} {
|
||||
t.Run(op, func(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
hs := &hookStore{AuthorityStore: disk}
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, hs, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
first := p.WorkspaceState("v").Lease.ExpiresAtNS
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
var enterOnce, releaseOnce sync.Once
|
||||
releaseFn := func() { releaseOnce.Do(func() { close(release) }) }
|
||||
hs.setBefore(func(r DurableRecord) error {
|
||||
if isExtension(r, "v", first) {
|
||||
enterOnce.Do(func() { close(entered) })
|
||||
<-release
|
||||
}
|
||||
return nil
|
||||
})
|
||||
done := make(chan error, 1)
|
||||
started := false
|
||||
// Installed before the extender is triggered: on any failure the
|
||||
// held write is released and the writer settled (bounded) before
|
||||
// the publisher joins its extenders and the store closes.
|
||||
t.Cleanup(func() {
|
||||
releaseFn()
|
||||
if started {
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("writer did not settle")
|
||||
}
|
||||
}
|
||||
})
|
||||
c.at(10)
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("extender never reached the store")
|
||||
}
|
||||
started = true
|
||||
if op == "revocation" {
|
||||
go func() { done <- p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1) }()
|
||||
} else {
|
||||
c.at(66) // past the OLD barrier max(1045, 1040) + 20
|
||||
q, h := forcedMove("v", "forced")
|
||||
go func() { _, err := p.MoveWorkspace(context.Background(), q, h); done <- err }()
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
done <- err // keep it for the cleanup join
|
||||
t.Fatalf("%s ran while the extender held p.mu: %v", op, err)
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
releaseFn()
|
||||
var err error
|
||||
select {
|
||||
case err = <-done:
|
||||
done <- err
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s did not finish after the extender", op)
|
||||
}
|
||||
want := c.sec(55).UnixNano()
|
||||
st := p.WorkspaceState("v")
|
||||
if op == "revocation" {
|
||||
if err != nil || st.Lease == nil || !st.Lease.Revoking || st.Lease.ExpiresAtNS != want {
|
||||
t.Fatalf("revocation not ordered after the extension: %v %+v", err, st.Lease)
|
||||
}
|
||||
} else if err == nil || len(st.Moves) != 0 || st.Lease.ExpiresAtNS != want {
|
||||
t.Fatalf("forced move did not see the extended horizon: %v %+v", err, st)
|
||||
}
|
||||
p.CloseWorkspaceExtenders()
|
||||
r := newLeasePublisher(t, disk, 30*time.Second, c)
|
||||
if got := r.WorkspaceState("v").Lease; got.ExpiresAtNS != want || got.Revoking != (op == "revocation") {
|
||||
t.Fatalf("reload: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Control 5: a renewal of the same volume during a held revocation write sees
|
||||
// the last published state (a grant under the horizon), then the revoking
|
||||
// lease with the granted expiry and no extension. During a held forced-move
|
||||
@@ -595,509 +322,6 @@ func TestWorkspaceSameVolumeRenewalDuringHeldWrite(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// Control 7 (run with -race): N volumes renew while apply, revocation, ACK,
|
||||
// a clean move, a forced move, extenders and Close run. A bounded handshake
|
||||
// holds the first horizon-extension write inside the store while renewals
|
||||
// keep succeeding and the writers and Close are in flight (queued on the
|
||||
// publisher lock behind it); then it is released. Required afterwards: every
|
||||
// eligible volume had successful grants, at least one extension write was
|
||||
// observed (classified by content: a raised horizon at the same epoch, not
|
||||
// an ordinary writer's record), no renewal waited 2 s, nothing deadlocked,
|
||||
// every live lease keeps disk >= published horizon >= every grant (S1), and
|
||||
// the view equals derive.
|
||||
func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
const n = 8
|
||||
vol := func(i int) string { return fmt.Sprintf("v%d", i) }
|
||||
const forcedVol, cleanVol = 2, 1
|
||||
eligible := []int{0, 3, 4, 5, 6, 7} // stay leased throughout; v0 also takes endpoint refreshes
|
||||
disk, _ := newTempStore(t)
|
||||
hs := &hookStore{AuthorityStore: disk}
|
||||
|
||||
// Extension classification and the overlap hold.
|
||||
var classMu sync.Mutex
|
||||
lastH := map[string]int64{}
|
||||
lastEpoch := map[string]uint64{}
|
||||
var extensions atomic.Int64
|
||||
heldEntered, heldRelease := make(chan struct{}), make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
// The publisher clock is frozen while the extension write is held (#247
|
||||
// hang): the held write holds p.mu, so every other volume's extender queues
|
||||
// and no horizon can move. With a running clock a late test goroutine could
|
||||
// let horizons expire before each volume got a grant under the hold (the
|
||||
// progress condition never holds), or before the writers run after the
|
||||
// release (a revoke ACK finds the lease expired). This test is about lock
|
||||
// and store ordering, not about lease expiry.
|
||||
// The clock stays frozen after the release until the clean volume's revoke
|
||||
// ACK: the endpoint refreshes, the revocation and the ACK queue on p.mu
|
||||
// behind every volume's extension write (fsync), which on a loaded machine
|
||||
// can outlast the clean volume's grant, and a revoking lease is never
|
||||
// extended (in-time ACK has its own tests). The writer then resumes the
|
||||
// clock from the frozen instant, so it neither jumps over a horizon nor runs
|
||||
// backwards; extensions run in real time alongside the moves and Close.
|
||||
// Now/Freeze/Resume are one transaction each.
|
||||
clock := &leaseTestClock{}
|
||||
releaseHold := func() {
|
||||
releaseOnce.Do(func() { close(heldRelease) })
|
||||
}
|
||||
var classifying atomic.Bool
|
||||
var holding atomic.Bool // set when the extension write is held, before it blocks
|
||||
var heldVol atomic.Value // string: the volume whose extension write is held
|
||||
var holdTaken atomic.Bool
|
||||
var holdMu sync.Mutex
|
||||
var skippedHolds atomic.Int64 // extension writes not held: some eligible volume lacked headroom
|
||||
var p *Publisher
|
||||
// headroom witnesses, at the frozen instant and from each volume's own
|
||||
// renewal view (the fields RenewWorkspaceLease reads, under the leaf
|
||||
// leaseMu), that a renewal of every eligible volume and of the clean volume
|
||||
// grants positive host validity: lease present and live, durable horizon
|
||||
// minus half the skew after now, and now before the granted deadline. The
|
||||
// frozen clock and the queued extenders keep it so for the whole hold and,
|
||||
// for the clean volume, through its revocation and ACK.
|
||||
var noHeadroom atomic.Value // string: the last volume found without headroom, and why
|
||||
headroom := func() bool {
|
||||
now := clock.Now().UnixNano()
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
for _, i := range append(append([]int{}, eligible...), cleanVol) { // the clean volume is revoked and ACKed frozen
|
||||
lv := p.leaseViews[vol(i)]
|
||||
if lv == nil || !lv.d.bound || !lv.d.leasePresent || lv.d.revoking || lv.d.movePending ||
|
||||
lv.d.uncertain || lv.d.storeless || lv.d.horizon-lv.d.maxSkewNS/2 <= now || now >= lv.deadline.UnixNano() {
|
||||
why := "no view"
|
||||
if lv != nil {
|
||||
why = fmt.Sprintf("bound=%v present=%v revoking=%v pending=%v uncertain=%v validity=%v deadline-now=%v",
|
||||
lv.d.bound, lv.d.leasePresent, lv.d.revoking, lv.d.movePending, lv.d.uncertain,
|
||||
time.Duration(lv.d.horizon-lv.d.maxSkewNS/2-now), time.Duration(lv.deadline.UnixNano()-now))
|
||||
}
|
||||
noHeadroom.Store(vol(i) + ": " + why)
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
hs.setBefore(func(r DurableRecord) error {
|
||||
time.Sleep(5 * time.Millisecond) // a slow store
|
||||
if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil {
|
||||
return nil
|
||||
}
|
||||
l := r.Workspace.Lease
|
||||
pending := len(r.Workspace.Moves) > 0 && !r.Workspace.Moves[len(r.Workspace.Moves)-1].Issued
|
||||
classMu.Lock()
|
||||
ext := !l.Revoking && !pending && l.Epoch == lastEpoch[r.VolumeID] && l.ExpiresAtNS > lastH[r.VolumeID]
|
||||
if ext {
|
||||
lastH[r.VolumeID] = l.ExpiresAtNS
|
||||
}
|
||||
classMu.Unlock()
|
||||
if ext {
|
||||
extensions.Add(1)
|
||||
first := false
|
||||
if !holdTaken.Load() {
|
||||
holdMu.Lock()
|
||||
if !holdTaken.Load() {
|
||||
clock.Freeze()
|
||||
if headroom() {
|
||||
holdTaken.Store(true)
|
||||
first = true
|
||||
} else {
|
||||
clock.Resume() // try again at a later extension write
|
||||
skippedHolds.Add(1)
|
||||
}
|
||||
}
|
||||
holdMu.Unlock()
|
||||
}
|
||||
if first {
|
||||
heldVol.Store(r.VolumeID) // the volume whose extension write is held
|
||||
holding.Store(true) // before the hold: a renewal started after this saw it
|
||||
close(heldEntered)
|
||||
<-heldRelease
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
// The publisher clock is real time plus an offset. The forced-move volume
|
||||
// is granted at offset -10 s, so by offset 0 its horizon + skew barrier has
|
||||
// passed; the clock only moves forward.
|
||||
clock.SetOffset(-10 * time.Second)
|
||||
p = NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders)
|
||||
ctx := context.Background()
|
||||
bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again
|
||||
clock.SetOffset(0)
|
||||
// Set-up writes are real store writes (fsync): on a loaded machine binding
|
||||
// the volumes can take longer than a TTL, and the first-bound volume would
|
||||
// expire before its renewer starts (by design it never recovers). The clock
|
||||
// stays frozen through the set-up and resumes just before the renewers.
|
||||
clock.Freeze()
|
||||
for i := 0; i < n; i++ {
|
||||
if i != forcedVol {
|
||||
bindAndGrant(t, p, vol(i), "r")
|
||||
}
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
st := p.WorkspaceState(vol(i))
|
||||
lastH[vol(i)], lastEpoch[vol(i)] = st.Lease.ExpiresAtNS, st.Lease.Epoch
|
||||
}
|
||||
clock.Resume()
|
||||
classifying.Store(true)
|
||||
|
||||
var grants [n]atomic.Int64
|
||||
var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held
|
||||
var returnedUnderHold [n]atomic.Int64 // calls (any outcome) that started while the extension write was held
|
||||
var refusedUnderHold atomic.Value // string: a refusal of a call started under the hold, before the writers
|
||||
var writersGo atomic.Bool // set before the writers start
|
||||
var maxGrant [n]atomic.Int64
|
||||
var slowest atomic.Int64
|
||||
stop := make(chan struct{})
|
||||
var stopOnce sync.Once
|
||||
stopRenewers := func() { stopOnce.Do(func() { close(stop) }) }
|
||||
var wg sync.WaitGroup
|
||||
writersDone := make(chan error, 1)
|
||||
closed := make(chan struct{})
|
||||
writersStarted, closeStarted := false, false
|
||||
// Bounded cleanup on every path: release the hold, stop renewers, settle
|
||||
// every worker, and only then let the fixtures close.
|
||||
t.Cleanup(func() {
|
||||
releaseHold()
|
||||
clock.Resume()
|
||||
stopRenewers()
|
||||
settled := make(chan struct{})
|
||||
go func() { wg.Wait(); close(settled) }()
|
||||
select {
|
||||
case <-settled:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("renewers did not settle")
|
||||
}
|
||||
if writersStarted {
|
||||
select {
|
||||
case <-writersDone:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("writers did not settle")
|
||||
}
|
||||
}
|
||||
if closeStarted {
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("Close did not settle")
|
||||
}
|
||||
}
|
||||
})
|
||||
for _, i := range append(append([]int{}, eligible...), cleanVol) {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
fresh := holding.Load() // the call starts while the extension write is held
|
||||
beforeWriters := !writersGo.Load()
|
||||
start := time.Now()
|
||||
l, err := p.RenewWorkspaceLease(ctx, vol(i), "r", 1)
|
||||
if d := int64(time.Since(start)); d > slowest.Load() {
|
||||
slowest.Store(d)
|
||||
}
|
||||
if fresh {
|
||||
returnedUnderHold[i].Add(1)
|
||||
// Headroom was witnessed at the frozen instant: until the
|
||||
// writers start, every such renewal must grant (any refusal,
|
||||
// a horizon error included, fails).
|
||||
if beforeWriters && (err != nil || l.Revoking) {
|
||||
refusedUnderHold.CompareAndSwap(nil, fmt.Sprintf("%s: %+v %v", vol(i), l, err))
|
||||
}
|
||||
}
|
||||
if err == nil && !l.Revoking {
|
||||
grants[i].Add(1)
|
||||
if fresh {
|
||||
underHold[i].Add(1)
|
||||
}
|
||||
if l.ExpiresAtNS > maxGrant[i].Load() {
|
||||
maxGrant[i].Store(l.ExpiresAtNS)
|
||||
}
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
// Handshake 1: the first extension write is held inside the store.
|
||||
// Progress handshakes (#227) with a real-time failure exit (never a pass):
|
||||
// the cleanup releases the hold and joins every worker.
|
||||
select {
|
||||
case <-heldEntered: // renewers keep triggering extensions
|
||||
case <-time.After(30 * time.Second):
|
||||
nh, _ := noHeadroom.Load().(string)
|
||||
t.Fatalf("no extension write was held within 30 s (%d extension writes, %d not held for lack of headroom; last: %s)",
|
||||
extensions.Load(), skippedHolds.Load(), nh)
|
||||
}
|
||||
// A late test goroutine (machine load), longer than a horizon (1.5 x TTL):
|
||||
// with the clock frozen under the hold, no volume can lose its lease here.
|
||||
time.Sleep(3500 * time.Millisecond)
|
||||
// Handshake 2: renewals keep succeeding while it is held.
|
||||
// Progress, no timer (#227): every eligible volume gains a grant from a call
|
||||
// that STARTED while the extension write was held (a reply computed before
|
||||
// the hold does not count); renewals that waited for it would never return.
|
||||
// The hold was taken only with headroom witnessed for every eligible volume
|
||||
// at the frozen instant, so no refusal is allowed here.
|
||||
held, _ := heldVol.Load().(string)
|
||||
for give := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) {
|
||||
if r, _ := refusedUnderHold.Load().(string); r != "" {
|
||||
t.Fatalf("under the held extension of %s, with headroom witnessed: refused %s", held, r)
|
||||
}
|
||||
all := true
|
||||
for _, i := range eligible {
|
||||
if underHold[i].Load() == 0 {
|
||||
all = false
|
||||
}
|
||||
}
|
||||
if all {
|
||||
break
|
||||
}
|
||||
if time.Now().After(give) {
|
||||
t.Fatalf("under the held extension of %s within 30 s: grants %v, returned calls %v", held,
|
||||
underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible))
|
||||
}
|
||||
}
|
||||
t.Logf("under the held extension of %s (%d extension writes not held for lack of headroom): grants %v", held,
|
||||
skippedHolds.Load(), underHoldCounts(&underHold, eligible))
|
||||
// Writers and Close start while the extension write is held.
|
||||
writersGo.Store(true)
|
||||
writersStarted = true
|
||||
go func() {
|
||||
for k := 0; k < 5; k++ {
|
||||
if err := p.apply(AssignmentAsk{VolumeID: vol(0), ReplicaID: "r", DataAddr: fmt.Sprintf("d%d", k), CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err != nil {
|
||||
writersDone <- fmt.Errorf("endpoint refresh: %w", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
// Still frozen since the hold (the refreshes above needed p.mu, which the
|
||||
// held write owned); the clean volume's headroom was witnessed then.
|
||||
if err := p.BeginWorkspaceRevocation(ctx, vol(cleanVol), "r", 1); err != nil {
|
||||
clock.Resume()
|
||||
writersDone <- fmt.Errorf("revocation: %w", err)
|
||||
return
|
||||
}
|
||||
err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "old/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "old/r", RemoteLSN: 42})
|
||||
clock.Resume()
|
||||
if err != nil {
|
||||
writersDone <- fmt.Errorf("ack: %w", err)
|
||||
return
|
||||
}
|
||||
clean := WorkspaceMoveRequest{RequestID: "clean", VolumeID: vol(cleanVol), ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"}
|
||||
if _, err := p.MoveWorkspace(ctx, clean, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42, Detached: true}); err != nil {
|
||||
writersDone <- fmt.Errorf("clean move: %w", err)
|
||||
return
|
||||
}
|
||||
q, h := forcedMove(vol(forcedVol), "forced")
|
||||
if _, err := p.MoveWorkspace(ctx, q, h); err != nil {
|
||||
writersDone <- fmt.Errorf("forced move: %w", err)
|
||||
return
|
||||
}
|
||||
writersDone <- nil
|
||||
}()
|
||||
closeStarted = true
|
||||
go func() { p.CloseWorkspaceExtenders(); close(closed) }()
|
||||
select {
|
||||
case err := <-writersDone:
|
||||
writersDone <- err // keep it for the cleanup join
|
||||
t.Fatalf("writers finished while the extension write held the publisher lock: %v", err)
|
||||
case <-closed:
|
||||
t.Fatal("Close finished while an extension write was held")
|
||||
case <-time.After(150 * time.Millisecond):
|
||||
}
|
||||
releaseHold()
|
||||
var werr error
|
||||
select {
|
||||
case werr = <-writersDone:
|
||||
writersDone <- werr // keep it for the cleanup join
|
||||
case <-time.After(20 * time.Second):
|
||||
t.Fatal("deadlock: writers did not finish after the release", allGoroutineStacks())
|
||||
}
|
||||
if werr != nil {
|
||||
t.Fatal("writer:", werr)
|
||||
}
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(20 * time.Second):
|
||||
t.Fatal("deadlock: Close did not finish after the release", allGoroutineStacks())
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond) // renewals continue after Close
|
||||
stopRenewers()
|
||||
settled := make(chan struct{})
|
||||
go func() { wg.Wait(); close(settled) }()
|
||||
select {
|
||||
case <-settled:
|
||||
case <-time.After(20 * time.Second):
|
||||
t.Fatal("deadlock: renewers did not finish", allGoroutineStacks())
|
||||
}
|
||||
|
||||
if s := time.Duration(slowest.Load()); s >= 2*time.Second {
|
||||
t.Fatalf("slowest renewal %s", s)
|
||||
}
|
||||
for _, i := range eligible {
|
||||
if grants[i].Load() == 0 {
|
||||
t.Fatalf("%s had no successful grant", vol(i))
|
||||
}
|
||||
}
|
||||
if extensions.Load() == 0 {
|
||||
t.Fatal("no horizon-extension write was observed")
|
||||
}
|
||||
// An issued move starts the new holder's lease at the new epoch.
|
||||
if st := p.WorkspaceState(vol(forcedVol)); st == nil || len(st.Moves) != 1 || !st.Moves[0].Issued || st.Moves[0].Kind != "forced" ||
|
||||
st.Lease == nil || st.Lease.Epoch != st.Moves[0].NewEpoch || st.Lease.Revoking {
|
||||
t.Fatalf("forced move not issued: %+v", st)
|
||||
}
|
||||
if st := p.WorkspaceState(vol(cleanVol)); st == nil || len(st.Moves) != 1 || st.Moves[0].Kind != "clean" ||
|
||||
st.Lease == nil || st.Lease.Epoch != st.Moves[0].NewEpoch || st.Lease.Revoking {
|
||||
t.Fatalf("clean move not issued: %+v", st)
|
||||
}
|
||||
assertLeaseViewMatches(t, p, "after concurrency")
|
||||
recs, err := disk.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
onDisk := map[string]int64{}
|
||||
for _, r := range recs {
|
||||
if r.Workspace != nil && r.Workspace.Lease != nil {
|
||||
onDisk[r.VolumeID] = r.Workspace.Lease.ExpiresAtNS
|
||||
}
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
st := p.WorkspaceState(vol(i))
|
||||
if st == nil || st.Lease == nil || st.Lease.Epoch != 1 {
|
||||
continue // a completed move started the next epoch's lease (out of S1's scope)
|
||||
}
|
||||
if onDisk[vol(i)] < st.Lease.ExpiresAtNS || st.Lease.ExpiresAtNS < maxGrant[i].Load() {
|
||||
t.Fatalf("%s: S1 broken: disk %d, published horizon %d, max grant %d", vol(i), onDisk[vol(i)], st.Lease.ExpiresAtNS, maxGrant[i].Load())
|
||||
}
|
||||
}
|
||||
t.Logf("extension writes %d; grants per eligible volume %v", extensions.Load(), func() []int64 {
|
||||
out := []int64{}
|
||||
for _, i := range eligible {
|
||||
out = append(out, grants[i].Load())
|
||||
}
|
||||
return out
|
||||
}())
|
||||
}
|
||||
|
||||
// Control 10a: Close waits for an extender held inside its Put; after Close
|
||||
// no extension is admitted or written.
|
||||
func TestWorkspaceCloseJoinsHeldExtender(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
hs := &hookStore{AuthorityStore: disk}
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, hs, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
first := p.WorkspaceState("v").Lease.ExpiresAtNS
|
||||
var puts atomic.Int64
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
var enterOnce, releaseOnce sync.Once
|
||||
releaseFn := func() { releaseOnce.Do(func() { close(release) }) }
|
||||
hs.setBefore(func(r DurableRecord) error {
|
||||
if isExtension(r, "v", first) {
|
||||
puts.Add(1)
|
||||
enterOnce.Do(func() { close(entered) })
|
||||
<-release
|
||||
}
|
||||
return nil
|
||||
})
|
||||
closed := make(chan struct{})
|
||||
closeStarted := false
|
||||
t.Cleanup(func() { // bounded: release, then settle Close before the store closes
|
||||
releaseFn()
|
||||
if closeStarted {
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("Close did not settle")
|
||||
}
|
||||
}
|
||||
})
|
||||
c.at(10)
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("extender never reached the store")
|
||||
}
|
||||
closeStarted = true
|
||||
go func() { p.CloseWorkspaceExtenders(); close(closed) }()
|
||||
select {
|
||||
case <-closed:
|
||||
t.Fatal("Close returned while an extender was inside its write")
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
releaseFn()
|
||||
select {
|
||||
case <-closed:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Close did not return after the extender finished")
|
||||
}
|
||||
before := puts.Load()
|
||||
c.at(20) // would trigger an extension (horizon 1055 < 1020 + 37.5)
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
if puts.Load() != before {
|
||||
t.Fatal("an extension was written after Close")
|
||||
}
|
||||
}
|
||||
|
||||
// Control 10b: an extender admitted before Close that reaches p.mu after
|
||||
// closing is set aborts with a known no-write. The test holds p.mu itself, so
|
||||
// the renewal also shows it never needs p.mu.
|
||||
func TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
hs := &hookStore{AuthorityStore: disk}
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, hs, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
first := p.WorkspaceState("v").Lease.ExpiresAtNS
|
||||
var puts atomic.Int64
|
||||
hs.setBefore(func(r DurableRecord) error {
|
||||
if isExtension(r, "v", first) {
|
||||
puts.Add(1)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
c.at(10)
|
||||
p.mu.Lock()
|
||||
renewed := make(chan error, 1)
|
||||
go func() { _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); renewed <- err }()
|
||||
select {
|
||||
case err := <-renewed:
|
||||
if err != nil {
|
||||
p.mu.Unlock()
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
p.mu.Unlock()
|
||||
t.Fatal("renewal waited on p.mu")
|
||||
}
|
||||
p.leaseMu.Lock()
|
||||
admitted := p.leaseViews["v"].extending
|
||||
p.leaseClosing = true // Close's first step, while the extender waits for p.mu
|
||||
p.leaseMu.Unlock()
|
||||
p.mu.Unlock()
|
||||
if !admitted {
|
||||
t.Fatal("no extender was admitted")
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
if puts.Load() != 0 || p.WorkspaceState("v").Lease.ExpiresAtNS != first {
|
||||
t.Fatal("an extender admitted before closing wrote after closing")
|
||||
}
|
||||
p.leaseMu.Lock()
|
||||
extending := p.leaseViews["v"].extending
|
||||
p.leaseMu.Unlock()
|
||||
if extending {
|
||||
t.Fatal("aborted extender left the single-flight flag set")
|
||||
}
|
||||
}
|
||||
|
||||
// leaseTestClock is a test publisher clock: real time plus an offset, or a
|
||||
// frozen instant. Now, Freeze, Resume and SetOffset are each one transaction
|
||||
// under mu, and Now never returns an earlier time than a previous Now.
|
||||
|
||||
@@ -1,229 +0,0 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Lease headroom observability. Headroom is the durable horizon minus now:
|
||||
// how long the published lease still covers a holder if no extension lands.
|
||||
// Extensions start below 1.25 TTL of headroom and grants are clamped below
|
||||
// 1 TTL, so a lagging authority store shows first as an extension in flight
|
||||
// with headroom under 1.125 TTL, and only later as clamps.
|
||||
//
|
||||
// The extension store write latency (LeaseStats.ExtensionWrite*) is
|
||||
// completed-write telemetry: a write is sampled when its Put returns, so a
|
||||
// write that is still blocked shows up only after it returns, possibly after
|
||||
// headroom is already lost; it is not an early warning by itself. The alarm
|
||||
// is sampled at renewals, never by a timer: it fires at the latest
|
||||
// together with the first clamped grant of a streak (logged before the clamp
|
||||
// line), and earlier only if a renewal lands in the 1-1.125 TTL band while an
|
||||
// extension is pending. A renewer slower than that band may see both on one
|
||||
// renewal.
|
||||
|
||||
// LeaseStats is a snapshot of the workspace lease renewal counters.
|
||||
type LeaseStats struct {
|
||||
// HeadroomAlarms counts alarm streaks, once per volume per streak: a
|
||||
// renewal that found headroom below 1.125 TTL with an extension in
|
||||
// flight, or the first clamped grant (headroom below 1 TTL) of a streak.
|
||||
HeadroomAlarms uint64
|
||||
// ClampsTotal counts grants clamped to the durable horizon.
|
||||
ClampsTotal uint64
|
||||
// ClampsLastMinute counts clamped grants in the last minute.
|
||||
ClampsLastMinute uint64
|
||||
// MinHeadroom is the smallest headroom observed at a grant; valid only
|
||||
// when MinHeadroomObserved.
|
||||
MinHeadroom time.Duration
|
||||
MinHeadroomObserved bool
|
||||
// ExtensionWriteLast is the duration of the latest lease extension's
|
||||
// durable store write (the write alone, failed or not); valid only when
|
||||
// ExtensionWriteObserved. Completed-write telemetry: recorded when the
|
||||
// Put returns, so a write still blocked is not visible here yet.
|
||||
ExtensionWriteLast time.Duration
|
||||
ExtensionWriteObserved bool
|
||||
// ExtensionWriteMaxLastMinute is the slowest extension write in the last
|
||||
// minute (rolling, one bucket per second like ClampsLastMinute); valid
|
||||
// only when ExtensionWriteInLastMinute.
|
||||
ExtensionWriteMaxLastMinute time.Duration
|
||||
ExtensionWriteInLastMinute bool
|
||||
}
|
||||
|
||||
const clampBuckets = 60 // one per second of the last minute
|
||||
|
||||
// leaseCounters is guarded by Publisher.leaseMu.
|
||||
type leaseCounters struct {
|
||||
alarms uint64
|
||||
clamps uint64
|
||||
buckets [clampBuckets]struct{ sec, n int64 } // clamps by unix second
|
||||
minHeadroom int64
|
||||
minObserved bool
|
||||
// Extension store writes: the latest, and the slowest per second of the
|
||||
// last minute.
|
||||
writeLast int64
|
||||
writeObserved bool
|
||||
writeBuckets [clampBuckets]struct {
|
||||
sec, max int64
|
||||
set bool
|
||||
}
|
||||
// Per-minute summary, emitted by the first renewal attempt after the
|
||||
// window, granted or refused: no goroutine or timer of its own. With no
|
||||
// renewal attempts at all nothing is emitted; the counters above (the
|
||||
// status endpoint) still show the clamps.
|
||||
windowStart time.Time
|
||||
windowClamps uint64
|
||||
windowMin int64
|
||||
windowMinSet bool
|
||||
}
|
||||
|
||||
func (c *leaseCounters) clampsSince(now time.Time) uint64 {
|
||||
cut := now.Unix() - clampBuckets
|
||||
var n uint64
|
||||
for _, b := range c.buckets {
|
||||
if b.n > 0 && b.sec > cut && b.sec <= now.Unix() {
|
||||
n += uint64(b.n)
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (c *leaseCounters) recordClamp(now time.Time) {
|
||||
c.clamps++
|
||||
c.windowClamps++
|
||||
sec := now.Unix()
|
||||
b := &c.buckets[uint64(sec)%clampBuckets]
|
||||
if b.sec != sec {
|
||||
b.sec, b.n = sec, 0
|
||||
}
|
||||
b.n++
|
||||
}
|
||||
|
||||
// recordExtensionWrite records the duration of one extension store write
|
||||
// that returned at now.
|
||||
func (c *leaseCounters) recordExtensionWrite(now time.Time, d time.Duration) {
|
||||
c.writeLast, c.writeObserved = int64(d), true
|
||||
sec := now.Unix()
|
||||
b := &c.writeBuckets[uint64(sec)%clampBuckets]
|
||||
if !b.set || b.sec != sec {
|
||||
b.sec, b.max, b.set = sec, int64(d), true
|
||||
} else if int64(d) > b.max {
|
||||
b.max = int64(d)
|
||||
}
|
||||
}
|
||||
|
||||
// extensionWriteMaxSince returns the slowest extension write of the last
|
||||
// minute, and whether there was one.
|
||||
func (c *leaseCounters) extensionWriteMaxSince(now time.Time) (int64, bool) {
|
||||
cut := now.Unix() - clampBuckets
|
||||
max, ok := int64(0), false
|
||||
for _, b := range c.writeBuckets {
|
||||
if b.set && b.sec > cut && b.sec <= now.Unix() && (!ok || b.max > max) {
|
||||
max, ok = b.max, true
|
||||
}
|
||||
}
|
||||
return max, ok
|
||||
}
|
||||
|
||||
// summaryDue closes a window that has lasted a minute and returns its summary
|
||||
// note when it had clamps. Every renewal attempt calls it, granted or refused,
|
||||
// so a stall through expiry (only refusals after the clamps) is still
|
||||
// summarized. It opens no window: the first grant does.
|
||||
func (c *leaseCounters) summaryDue(now time.Time) string {
|
||||
if c.windowStart.IsZero() || now.Sub(c.windowStart) < time.Minute {
|
||||
return ""
|
||||
}
|
||||
var note string
|
||||
if c.windowClamps > 0 {
|
||||
note = fmt.Sprintf("workspace lease: %d clamped grants in the last %s (total %d, min headroom %s); the authority store is lagging",
|
||||
c.windowClamps, now.Sub(c.windowStart).Round(time.Second), c.clamps, time.Duration(c.windowMin).Round(time.Millisecond))
|
||||
}
|
||||
c.windowStart, c.windowClamps, c.windowMinSet = now, 0, false
|
||||
return note
|
||||
}
|
||||
|
||||
// observeGrant records the headroom of a grant and returns a per-minute
|
||||
// summary note when a window with clamps has just ended. Call it before
|
||||
// recordClamp of the same grant (it may open a new window).
|
||||
func (c *leaseCounters) observeGrant(now time.Time, headroom int64) string {
|
||||
if c.windowStart.IsZero() {
|
||||
c.windowStart = now
|
||||
}
|
||||
note := c.summaryDue(now)
|
||||
if !c.windowMinSet || headroom < c.windowMin {
|
||||
c.windowMin, c.windowMinSet = headroom, true
|
||||
}
|
||||
if !c.minObserved || headroom < c.minHeadroom {
|
||||
c.minHeadroom, c.minObserved = headroom, true
|
||||
}
|
||||
return note
|
||||
}
|
||||
|
||||
// WorkspaceLeaseStats returns a snapshot of the lease renewal counters.
|
||||
func (p *Publisher) WorkspaceLeaseStats() LeaseStats {
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
c := &p.leaseStats
|
||||
now := p.workspaceNow()
|
||||
writeMax, writeRecent := c.extensionWriteMaxSince(now)
|
||||
return LeaseStats{
|
||||
HeadroomAlarms: c.alarms,
|
||||
ClampsTotal: c.clamps,
|
||||
ClampsLastMinute: c.clampsSince(now),
|
||||
MinHeadroom: time.Duration(c.minHeadroom),
|
||||
MinHeadroomObserved: c.minObserved,
|
||||
ExtensionWriteLast: time.Duration(c.writeLast),
|
||||
ExtensionWriteObserved: c.writeObserved,
|
||||
ExtensionWriteMaxLastMinute: time.Duration(writeMax),
|
||||
ExtensionWriteInLastMinute: writeRecent,
|
||||
}
|
||||
}
|
||||
|
||||
// headroomAlarmLocked runs the alarm state machine of one renewal, before the
|
||||
// renewal clamps (a grant clamps exactly when headroom < 1 TTL). Caller holds
|
||||
// leaseMu. It returns a note to log after the unlock, before the clamp note.
|
||||
//
|
||||
// state | condition at a renewal | next | effect
|
||||
// -----------+-----------------------------------------------+------------+------------------
|
||||
// quiet | extending && headroom < 1.125 TTL | alarmed | count + log once
|
||||
// quiet | headroom < 1 TTL (this grant clamps) | alarmed | count + log once
|
||||
// quiet | otherwise | quiet | -
|
||||
// alarmed | headroom >= 1.25 TTL | quiet | streak ends
|
||||
// alarmed | !extending && headroom >= 1.125 TTL | quiet | streak ends
|
||||
// alarmed | otherwise | alarmed | -
|
||||
//
|
||||
// A clamp streak (headroom < 1 TTL) therefore never starts without an alarm
|
||||
// on the same or an earlier renewal, and never re-alarms while it lasts.
|
||||
func (p *Publisher) headroomAlarmLocked(volume string, lv *leaseView, headroom int64) string {
|
||||
ttl := int64(p.workspaceTTL)
|
||||
low, high := ttl+ttl/8, ttl+ttl/4
|
||||
if lv.alarmed {
|
||||
if headroom >= high || (!lv.extending && headroom >= low) {
|
||||
lv.alarmed = false
|
||||
}
|
||||
return ""
|
||||
}
|
||||
var why string
|
||||
switch {
|
||||
case lv.extending && headroom < low:
|
||||
why = "below 1.125 TTL while the extension write is pending"
|
||||
case headroom < ttl:
|
||||
why = "below 1 TTL: this grant is the first clamped to the durable horizon"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
lv.alarmed = true
|
||||
p.leaseStats.alarms++
|
||||
return fmt.Sprintf("workspace lease: volume=%s headroom %s %s; the authority store is lagging",
|
||||
volume, time.Duration(headroom).Round(time.Millisecond), why)
|
||||
}
|
||||
|
||||
func (p *Publisher) logLease(note string) {
|
||||
if note == "" {
|
||||
return
|
||||
}
|
||||
if p.leaseLog != nil {
|
||||
p.leaseLog(note)
|
||||
return
|
||||
}
|
||||
log.Print(note)
|
||||
}
|
||||
@@ -1,393 +0,0 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// blockedLeaseStore holds every armed workspace-lease write until release
|
||||
// closes, standing in for an authority journal stuck behind other fsyncs.
|
||||
type blockedLeaseStore struct {
|
||||
AuthorityStore
|
||||
armed atomic.Bool
|
||||
entered chan struct{}
|
||||
once sync.Once
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (s *blockedLeaseStore) Put(r DurableRecord) error {
|
||||
if s.armed.Load() && r.Workspace != nil && r.Workspace.Lease != nil {
|
||||
s.once.Do(func() { close(s.entered) })
|
||||
<-s.release
|
||||
}
|
||||
return s.AuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
type noteLog struct {
|
||||
mu sync.Mutex
|
||||
lines []string
|
||||
}
|
||||
|
||||
func (l *noteLog) add(s string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.lines = append(l.lines, s)
|
||||
}
|
||||
|
||||
func (l *noteLog) snapshot() []string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return append([]string(nil), l.lines...)
|
||||
}
|
||||
|
||||
func indexOf(lines []string, sub string) int {
|
||||
for i, s := range lines {
|
||||
if strings.Contains(s, sub) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// With the authority store's lease write stuck, renewals at an advancing
|
||||
// clock must raise the headroom alarm on a renewal strictly before the first
|
||||
// clamped grant, then count clamps (total and last minute) and the minimum
|
||||
// headroom, and log a per-minute summary once a minute with clamps ends.
|
||||
func TestWorkspaceLeaseHeadroomAlarmPrecedesFirstClamp(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
store := &blockedLeaseStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{})}
|
||||
var nowNS atomic.Int64
|
||||
t0 := time.Unix(1000, 0)
|
||||
nowNS.Store(t0.UnixNano())
|
||||
at := func(d time.Duration) { nowNS.Store(t0.Add(d).UnixNano()) }
|
||||
const ttl = 30 * time.Second
|
||||
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(ttl, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
notes := ¬eLog{}
|
||||
p.leaseLog = notes.add
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(store.release) }) }
|
||||
t.Cleanup(p.CloseWorkspaceExtenders) // runs after release (LIFO)
|
||||
t.Cleanup(release)
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// First grant: synchronous write, horizon t0+45s.
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := p.WorkspaceLeaseStats(); s.HeadroomAlarms != 0 || s.ClampsTotal != 0 || s.MinHeadroomObserved {
|
||||
t.Fatalf("stats after the first grant: %+v", s)
|
||||
}
|
||||
store.armed.Store(true)
|
||||
renew := func(d time.Duration) (WorkspaceLease, LeaseStats) {
|
||||
t.Helper()
|
||||
at(d)
|
||||
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
|
||||
if err != nil {
|
||||
t.Fatalf("renewal at +%s: %v", d, err)
|
||||
}
|
||||
return l, p.WorkspaceLeaseStats()
|
||||
}
|
||||
|
||||
// +10s: headroom 35s < 1.25 TTL starts the extension, which blocks.
|
||||
_, s := renew(10 * time.Second)
|
||||
if s.HeadroomAlarms != 0 || s.ClampsTotal != 0 {
|
||||
t.Fatalf("+10s (headroom 35s, extension just started): %+v", s)
|
||||
}
|
||||
select {
|
||||
case <-store.entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the extension write never reached the store")
|
||||
}
|
||||
// +12s: headroom 33s < 33.75s (1.125 TTL), extension pending: alarm, no clamp.
|
||||
l, s := renew(12 * time.Second)
|
||||
if s.HeadroomAlarms != 1 || s.ClampsTotal != 0 {
|
||||
t.Fatalf("+12s (headroom 33s, extension pending): want 1 alarm and 0 clamps, got %+v", s)
|
||||
}
|
||||
if want := t0.Add(12*time.Second + ttl).UnixNano(); l.ExpiresAtNS != want {
|
||||
t.Fatalf("+12s grant %d, want unclamped %d", l.ExpiresAtNS, want)
|
||||
}
|
||||
// +13s: same streak, no second alarm.
|
||||
if _, s = renew(13 * time.Second); s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+13s: alarm repeated within one streak: %+v", s)
|
||||
}
|
||||
// +20s, +25s: headroom 25s, 20s < TTL: clamped grants.
|
||||
l, s = renew(20 * time.Second)
|
||||
if want := t0.Add(45 * time.Second).UnixNano(); l.ExpiresAtNS != want {
|
||||
t.Fatalf("+20s grant %d, want clamped to horizon %d", l.ExpiresAtNS, want)
|
||||
}
|
||||
if s.ClampsTotal != 1 || s.ClampsLastMinute != 1 || s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+20s: %+v", s)
|
||||
}
|
||||
_, s = renew(25 * time.Second)
|
||||
if s.ClampsTotal != 2 || s.ClampsLastMinute != 2 || !s.MinHeadroomObserved || s.MinHeadroom != 20*time.Second {
|
||||
t.Fatalf("+25s: want 2 clamps, min headroom 20s; got %+v", s)
|
||||
}
|
||||
lines := notes.snapshot()
|
||||
alarmAt, clampAt := indexOf(lines, "below 1.125 TTL while the extension write is pending"), indexOf(lines, "are clamped to the durable horizon")
|
||||
if alarmAt < 0 || clampAt < 0 || alarmAt >= clampAt {
|
||||
t.Fatalf("alarm line must precede the first clamp line: alarm=%d clamp=%d\n%s", alarmAt, clampAt, strings.Join(lines, "\n"))
|
||||
}
|
||||
if !strings.Contains(lines[alarmAt], "volume=v headroom 33s") {
|
||||
t.Fatalf("alarm line: %q", lines[alarmAt])
|
||||
}
|
||||
|
||||
// The store recovers: the extension lands (horizon +10s+45s = +55s).
|
||||
release()
|
||||
waitExtenders(t, p)
|
||||
// +26s: horizon +55s, headroom 29s < TTL: one more clamp; a new extension
|
||||
// starts (trigger +26s, horizon +71s) and lands at once.
|
||||
_, s = renew(26 * time.Second)
|
||||
waitExtenders(t, p)
|
||||
if s.ClampsTotal != 3 {
|
||||
t.Fatalf("+26s: %+v", s)
|
||||
}
|
||||
// +27s: headroom 44s >= 1.25 TTL: unclamped, the alarm streak ends.
|
||||
if _, s = renew(27 * time.Second); s.ClampsTotal != 3 || s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+27s: %+v", s)
|
||||
}
|
||||
// Healthy renewals keep the lease ahead: no clamps, no alarms.
|
||||
for _, d := range []time.Duration{40 * time.Second, 55 * time.Second} {
|
||||
if _, s = renew(d); s.ClampsTotal != 3 || s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+%s: %+v", d, s)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
}
|
||||
if indexOf(notes.snapshot(), "clamped grants in the last") >= 0 {
|
||||
t.Fatal("summary logged before the minute ended")
|
||||
}
|
||||
// +70s: a minute after the window's first renewal (+10s): the window with
|
||||
// clamps ends and its summary is logged by this renewal.
|
||||
if _, s = renew(70 * time.Second); s.ClampsTotal != 3 {
|
||||
t.Fatalf("+70s: %+v", s)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
lines = notes.snapshot()
|
||||
if i := indexOf(lines, "workspace lease: 3 clamped grants in the last 1m0s (total 3, min headroom 20s)"); i < 0 {
|
||||
t.Fatalf("no per-minute summary:\n%s", strings.Join(lines, "\n"))
|
||||
}
|
||||
// The +20s/+25s/+26s clamps are older than a minute at +87s.
|
||||
at(87 * time.Second)
|
||||
if s = p.WorkspaceLeaseStats(); s.ClampsLastMinute != 0 || s.ClampsTotal != 3 || s.MinHeadroom != 20*time.Second {
|
||||
t.Fatalf("+87s: clamps should age out of the last minute: %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
// stalledLeaseRig is a publisher whose lease writes, once armed, block until
|
||||
// release, with a settable clock (t0 = first grant, TTL 30s, horizon +45s).
|
||||
type stalledLeaseRig struct {
|
||||
p *Publisher
|
||||
store *blockedLeaseStore
|
||||
notes *noteLog
|
||||
t0 time.Time
|
||||
nowNS atomic.Int64
|
||||
release func()
|
||||
}
|
||||
|
||||
func newStalledLeaseRig(t *testing.T) *stalledLeaseRig {
|
||||
t.Helper()
|
||||
disk, _ := newTempStore(t)
|
||||
r := &stalledLeaseRig{store: &blockedLeaseStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{})}, notes: ¬eLog{}, t0: time.Unix(1000, 0)}
|
||||
r.nowNS.Store(r.t0.UnixNano())
|
||||
r.p = NewPublisher(nil, WithStore(r.store), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, r.nowNS.Load()) }))
|
||||
r.p.leaseLog = r.notes.add
|
||||
var once sync.Once
|
||||
r.release = func() { once.Do(func() { close(r.store.release) }) }
|
||||
t.Cleanup(r.p.CloseWorkspaceExtenders) // runs after release (LIFO)
|
||||
t.Cleanup(r.release)
|
||||
if err := r.p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.store.armed.Store(true)
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *stalledLeaseRig) renew(d time.Duration) (WorkspaceLease, LeaseStats, error) {
|
||||
r.nowNS.Store(r.t0.Add(d).UnixNano())
|
||||
l, err := r.p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
|
||||
return l, r.p.WorkspaceLeaseStats(), err
|
||||
}
|
||||
|
||||
func (r *stalledLeaseRig) waitEntered(t *testing.T) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-r.store.entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the extension write never reached the store")
|
||||
}
|
||||
}
|
||||
|
||||
// assertAlarmBeforeClamp checks exactly one alarm line containing want, logged
|
||||
// before the first clamp line.
|
||||
func assertAlarmBeforeClamp(t *testing.T, lines []string, want string) {
|
||||
t.Helper()
|
||||
alarms := 0
|
||||
for _, s := range lines {
|
||||
if strings.Contains(s, "the authority store is lagging") && strings.Contains(s, "headroom") && strings.Contains(s, "volume=v") {
|
||||
alarms++
|
||||
}
|
||||
}
|
||||
alarmAt, clampAt := indexOf(lines, want), indexOf(lines, "are clamped to the durable horizon")
|
||||
if alarms != 1 || alarmAt < 0 || clampAt < 0 || alarmAt >= clampAt {
|
||||
t.Fatalf("want one alarm %q before the first clamp line: alarms=%d alarm=%d clamp=%d\n%s", want, alarms, alarmAt, clampAt, strings.Join(lines, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// Skipped band: the extension starts and stalls at +10s, and the next renewal
|
||||
// (+20s) lands already clamped, never in the 1-1.125 TTL band. The alarm fires
|
||||
// on that same renewal, logged before the clamp line, and counts once.
|
||||
func TestWorkspaceLeaseAlarmWhenTheBandIsSkipped(t *testing.T) {
|
||||
r := newStalledLeaseRig(t)
|
||||
if _, s, err := r.renew(10 * time.Second); err != nil || s.HeadroomAlarms != 0 {
|
||||
t.Fatalf("+10s: %+v %v", s, err)
|
||||
}
|
||||
r.waitEntered(t)
|
||||
l, s, err := r.renew(20 * time.Second)
|
||||
if err != nil || l.ExpiresAtNS != r.t0.Add(45*time.Second).UnixNano() {
|
||||
t.Fatalf("+20s: want a grant clamped to the horizon, got %+v %v", l, err)
|
||||
}
|
||||
if s.HeadroomAlarms != 1 || s.ClampsTotal != 1 {
|
||||
t.Fatalf("+20s: want 1 alarm and 1 clamp, got %+v", s)
|
||||
}
|
||||
if _, s, err = r.renew(25 * time.Second); err != nil || s.HeadroomAlarms != 1 || s.ClampsTotal != 2 {
|
||||
t.Fatalf("+25s: alarm repeated or clamp missed: %+v %v", s, err)
|
||||
}
|
||||
assertAlarmBeforeClamp(t, r.notes.snapshot(), "volume=v headroom 25s below 1.125 TTL while the extension write is pending")
|
||||
}
|
||||
|
||||
// First renewal below one TTL: no extension has started yet (the renewal
|
||||
// itself starts it), and the grant clamps. The alarm still fires with that
|
||||
// first clamp, before the clamp line, and does not repeat in the streak.
|
||||
func TestWorkspaceLeaseAlarmWithAFirstRenewalBelowTTL(t *testing.T) {
|
||||
r := newStalledLeaseRig(t)
|
||||
l, s, err := r.renew(16 * time.Second)
|
||||
if err != nil || l.ExpiresAtNS != r.t0.Add(45*time.Second).UnixNano() {
|
||||
t.Fatalf("+16s: want a grant clamped to the horizon, got %+v %v", l, err)
|
||||
}
|
||||
if s.HeadroomAlarms != 1 || s.ClampsTotal != 1 {
|
||||
t.Fatalf("+16s: want 1 alarm with the first clamp, got %+v", s)
|
||||
}
|
||||
r.waitEntered(t) // the renewal started the extension; it stalls
|
||||
if _, s, err = r.renew(18 * time.Second); err != nil || s.HeadroomAlarms != 1 || s.ClampsTotal != 2 {
|
||||
t.Fatalf("+18s: %+v %v", s, err)
|
||||
}
|
||||
assertAlarmBeforeClamp(t, r.notes.snapshot(), "volume=v headroom 29s below 1 TTL: this grant is the first clamped to the durable horizon")
|
||||
}
|
||||
|
||||
// Stall through expiry: after the clamps, every renewal is refused (no host
|
||||
// validity, then expired) and none is granted again. The per-minute summary
|
||||
// is still logged, by the first refused renewal after the minute, once.
|
||||
func TestWorkspaceLeaseSummaryWithoutALaterGrant(t *testing.T) {
|
||||
r := newStalledLeaseRig(t)
|
||||
if _, _, err := r.renew(10 * time.Second); err != nil { // opens the window, starts the extension
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.waitEntered(t)
|
||||
for _, d := range []time.Duration{20 * time.Second, 25 * time.Second} {
|
||||
if _, _, err := r.renew(d); err != nil {
|
||||
t.Fatalf("+%s: %v", d, err)
|
||||
}
|
||||
}
|
||||
for _, d := range []time.Duration{36 * time.Second, 46 * time.Second, 60 * time.Second} {
|
||||
if l, _, err := r.renew(d); err == nil {
|
||||
t.Fatalf("+%s: granted %+v through a stalled store past the horizon", d, l)
|
||||
}
|
||||
}
|
||||
if indexOf(r.notes.snapshot(), "clamped grants in the last") >= 0 {
|
||||
t.Fatal("summary logged before the minute ended")
|
||||
}
|
||||
if _, s, err := r.renew(71 * time.Second); err == nil || s.ClampsTotal != 2 {
|
||||
t.Fatalf("+71s: %+v %v, want a refusal", s, err)
|
||||
}
|
||||
if _, _, err := r.renew(72 * time.Second); err == nil {
|
||||
t.Fatal("+72s granted")
|
||||
}
|
||||
lines := r.notes.snapshot()
|
||||
want := "workspace lease: 2 clamped grants in the last 1m1s (total 2, min headroom 20s)"
|
||||
n := 0
|
||||
for _, s := range lines {
|
||||
if strings.Contains(s, "clamped grants in the last") {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if indexOf(lines, want) < 0 || n != 1 {
|
||||
t.Fatalf("want the summary %q once from refused renewals, got %d summaries:\n%s", want, n, strings.Join(lines, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// delayedLeaseStore makes every lease write take delay (when set): a slow
|
||||
// authority journal that still completes.
|
||||
type delayedLeaseStore struct {
|
||||
AuthorityStore
|
||||
delay atomic.Int64
|
||||
}
|
||||
|
||||
func (s *delayedLeaseStore) Put(r DurableRecord) error {
|
||||
if d := time.Duration(s.delay.Load()); d > 0 && r.Workspace != nil && r.Workspace.Lease != nil {
|
||||
time.Sleep(d)
|
||||
}
|
||||
return s.AuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
// The extension's store write latency is recorded at every extension write:
|
||||
// the latest one, and the slowest of the last minute (rolling per second),
|
||||
// which ages out a minute after the write. The first grant's write is not an
|
||||
// extension and records nothing.
|
||||
func TestWorkspaceLeaseExtensionWriteLatency(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
store := &delayedLeaseStore{AuthorityStore: disk}
|
||||
var nowNS atomic.Int64
|
||||
t0 := time.Unix(1000, 0)
|
||||
nowNS.Store(t0.UnixNano())
|
||||
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
p.leaseLog = func(string) {}
|
||||
t.Cleanup(p.CloseWorkspaceExtenders)
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
renew := func(d time.Duration) LeaseStats {
|
||||
t.Helper()
|
||||
nowNS.Store(t0.Add(d).UnixNano())
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatalf("renewal at +%s: %v", d, err)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
return p.WorkspaceLeaseStats()
|
||||
}
|
||||
if s := renew(0); s.ExtensionWriteObserved || s.ExtensionWriteInLastMinute { // first grant
|
||||
t.Fatalf("the first grant recorded an extension write: %+v", s)
|
||||
}
|
||||
const slow = 300 * time.Millisecond
|
||||
store.delay.Store(int64(slow))
|
||||
// +10s: headroom 35s < 1.25 TTL starts an extension; its write takes 300 ms.
|
||||
s := renew(10 * time.Second)
|
||||
if !s.ExtensionWriteObserved || s.ExtensionWriteLast < slow || s.ExtensionWriteLast > slow+time.Second {
|
||||
t.Fatalf("+10s: want the last extension write ~%s, got %+v", slow, s)
|
||||
}
|
||||
if !s.ExtensionWriteInLastMinute || s.ExtensionWriteMaxLastMinute < slow {
|
||||
t.Fatalf("+10s: want max >= %s in the last minute, got %+v", slow, s)
|
||||
}
|
||||
store.delay.Store(0)
|
||||
// +20s: horizon +55s, headroom 35s: a fast extension write.
|
||||
s = renew(20 * time.Second)
|
||||
if s.ExtensionWriteLast >= slow || s.ExtensionWriteMaxLastMinute < slow {
|
||||
t.Fatalf("+20s: want a fast last write and the 300 ms max kept, got %+v", s)
|
||||
}
|
||||
// +71s: the +10s write is older than a minute; the +20s one is not.
|
||||
nowNS.Store(t0.Add(71 * time.Second).UnixNano())
|
||||
if s = p.WorkspaceLeaseStats(); !s.ExtensionWriteInLastMinute || s.ExtensionWriteMaxLastMinute >= slow || s.ExtensionWriteLast >= slow {
|
||||
t.Fatalf("+71s: the 300 ms max must age out, got %+v", s)
|
||||
}
|
||||
// +81s: no write in the last minute; the last write stays reported.
|
||||
nowNS.Store(t0.Add(81 * time.Second).UnixNano())
|
||||
if s = p.WorkspaceLeaseStats(); s.ExtensionWriteInLastMinute || !s.ExtensionWriteObserved {
|
||||
t.Fatalf("+81s: want no write in the last minute, last still observed; got %+v", s)
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -28,20 +27,18 @@ type leaseDerived struct {
|
||||
movePending bool // the last workspace move is reserved, not issued
|
||||
uncertain bool // a workspace write of the volume failed (INV-AUTH-UNCERTAIN-001)
|
||||
storeless bool
|
||||
horizon int64 // published Lease.ExpiresAtNS: durable upper bound of every grant
|
||||
horizon int64 // published Lease.ExpiresAtNS: read by nothing but replyExpiryNS's unreachable fallback
|
||||
maxSkewNS int64
|
||||
lease WorkspaceLease // the published (durable) lease
|
||||
}
|
||||
|
||||
// leaseView is one volume's renewal state. Guarded by Publisher.leaseMu.
|
||||
// deadline (the latest grant, or the restart rule's now+TTL) and extending
|
||||
// are owned by the view; d is derived.
|
||||
// deadline (the latest grant, or after a restart the restart floor
|
||||
// restart+TTL; a barrier adds the skew bound to it) is owned by the view; d
|
||||
// is derived.
|
||||
type leaseView struct {
|
||||
d leaseDerived
|
||||
deadline time.Time
|
||||
extending bool
|
||||
clamped bool // a renewal was clamped below now+TTL; logged once per streak
|
||||
alarmed bool // a headroom alarm streak is open (headroomAlarmLocked)
|
||||
d leaseDerived
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
// deriveLeaseLocked computes the derived lease view from published state.
|
||||
@@ -124,21 +121,29 @@ func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise boo
|
||||
}
|
||||
}
|
||||
|
||||
// replyExpiryNS is the expiry reported to a host: never the raw durable
|
||||
// horizon, only what was granted (min(horizon, deadline)).
|
||||
// replyExpiryNS is the expiry reported to a host: what was granted (the
|
||||
// deadline), never a persisted value. Without a deadline (a published lease
|
||||
// always has one) it reports 0, which gives the host no validity: fail
|
||||
// closed.
|
||||
func (lv *leaseView) replyExpiryNS() int64 {
|
||||
if lv.deadline.IsZero() {
|
||||
return lv.d.horizon // unreachable: a published lease always has a deadline
|
||||
return 0
|
||||
}
|
||||
if dl := lv.deadline.UnixNano(); dl < lv.d.horizon {
|
||||
return dl
|
||||
}
|
||||
return lv.d.horizon
|
||||
return lv.deadline.UnixNano()
|
||||
}
|
||||
|
||||
// WorkspaceLeaseReply returns the published lease with its expiry clamped to
|
||||
// what was granted (min(durable horizon, granted deadline)), for replies that
|
||||
// report a lease to a host or operator. ok is false without a lease.
|
||||
// deadlineValidity is the host validity a grant expiring at deadline leaves
|
||||
// at now: deadline minus half the skew bound, capped at the TTL, never
|
||||
// negative. Both times are this process's, so the difference uses their
|
||||
// monotonic readings.
|
||||
func (p *Publisher) deadlineValidity(deadline time.Time, maxSkewNS int64, now time.Time) time.Duration {
|
||||
skew := p.workspaceSkew(&WorkspaceLease{MaxClockSkewNS: maxSkewNS})
|
||||
return max(0, min(deadline.Add(-skew/2).Sub(now), p.workspaceTTL))
|
||||
}
|
||||
|
||||
// WorkspaceLeaseReply returns the published lease with its expiry set to
|
||||
// what was granted (the deadline), for replies that report a lease to a host
|
||||
// or operator. ok is false without a lease.
|
||||
func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) {
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
@@ -222,9 +227,10 @@ func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine {
|
||||
|
||||
// RenewWorkspaceLease answers a live holder from memory: it takes only the
|
||||
// leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant
|
||||
// is min(now+TTL, durable horizon); a background extender (an ordinary p.mu
|
||||
// writer) pushes the horizon ahead. A first grant and an expired re-grant
|
||||
// after the shared move barrier write synchronously.
|
||||
// is now+TTL; nothing is written. A restarted master grants a different
|
||||
// holder only once its restart floor (deadline restart + TTL, set at load)
|
||||
// plus the skew bound has passed, so no durable horizon is needed. A first grant and an
|
||||
// expired re-grant after the shared move barrier write synchronously.
|
||||
func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceLease{}, err
|
||||
@@ -232,14 +238,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
p.beforeWorkspaceGrantLock("renewal")
|
||||
p.leaseMu.Lock()
|
||||
now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it
|
||||
// unlock releases leaseMu on a path that grants nothing and logs a due
|
||||
// per-minute summary after the unlock: every renewal attempt, granted or
|
||||
// refused, may close the window (a stall through expiry refuses only).
|
||||
unlock := func() {
|
||||
summary := p.leaseStats.summaryDue(now)
|
||||
p.leaseMu.Unlock()
|
||||
p.logLease(summary)
|
||||
}
|
||||
unlock := p.leaseMu.Unlock
|
||||
if p.deleteReserved[volume] {
|
||||
unlock()
|
||||
return WorkspaceLease{}, ErrWorkspaceDeleteReserved
|
||||
@@ -267,7 +266,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
unlock()
|
||||
return l, nil
|
||||
}
|
||||
if now.UnixNano() >= lv.d.horizon || !now.Before(lv.deadline) {
|
||||
if !now.Before(lv.deadline) {
|
||||
unlock()
|
||||
return p.regrantWorkspaceLease(ctx, volume, holder, epoch)
|
||||
}
|
||||
@@ -277,60 +276,30 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain")
|
||||
}
|
||||
// The headroom alarm is sampled here, before the clamp: at the latest it
|
||||
// fires on the first clamped grant of a streak (headroomAlarmLocked).
|
||||
headroom := lv.d.horizon - now.UnixNano()
|
||||
alarm := p.headroomAlarmLocked(volume, lv, headroom)
|
||||
grant := now.Add(p.workspaceTTL).UnixNano()
|
||||
clamped := grant > lv.d.horizon
|
||||
if clamped {
|
||||
grant = lv.d.horizon
|
||||
}
|
||||
// The grant stays a time.Time with its monotonic reading: the deadline
|
||||
// it raises is what admission compares (this process's own clock); only
|
||||
// the reply carries wall nanoseconds.
|
||||
grant := now.Add(p.workspaceTTL)
|
||||
// A grant without positive host validity (expiry minus half the skew
|
||||
// bound, leaseFact) would make the host fence on an invalid reply and lose
|
||||
// its remaining validity; refuse with an error instead.
|
||||
if p.workspaceLeaseValidityAt(WorkspaceLease{ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS}, now) == 0 {
|
||||
horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242)
|
||||
summary := p.leaseStats.summaryDue(now)
|
||||
p.leaseMu.Unlock()
|
||||
p.logLease(alarm)
|
||||
p.logLease(summary)
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, horizon).UTC().Format(time.RFC3339Nano))
|
||||
if p.deadlineValidity(grant, lv.d.maxSkewNS, now) == 0 {
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: a grant of %s leaves no host validity under skew bound %s", p.workspaceTTL, time.Duration(lv.d.maxSkewNS))
|
||||
}
|
||||
if g := time.Unix(0, grant); g.After(lv.deadline) {
|
||||
lv.deadline = g
|
||||
if grant.After(lv.deadline) {
|
||||
lv.deadline = grant
|
||||
}
|
||||
summary := p.leaseStats.observeGrant(now, headroom)
|
||||
if clamped {
|
||||
p.leaseStats.recordClamp(now)
|
||||
}
|
||||
var note string
|
||||
switch {
|
||||
case clamped && !lv.clamped:
|
||||
lv.clamped = true
|
||||
note = fmt.Sprintf("workspace lease: grants of volume=%s are clamped to the durable horizon %s (%s remaining); extensions are behind",
|
||||
volume, time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano), time.Duration(lv.d.horizon-now.UnixNano()).Round(time.Millisecond))
|
||||
case !clamped && lv.clamped:
|
||||
lv.clamped = false
|
||||
note = fmt.Sprintf("workspace lease: grants of volume=%s are no longer clamped (horizon %s)", volume, time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
if lv.d.horizon < now.Add(p.workspaceTTL+p.workspaceTTL/4).UnixNano() && !lv.extending && !p.leaseClosing {
|
||||
lv.extending = true
|
||||
p.extWG.Add(1) // under leaseMu with !closing: no Add can follow CloseWorkspaceExtenders
|
||||
go p.extendWorkspaceLease(volume, holder, epoch, now)
|
||||
}
|
||||
l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS}
|
||||
l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lv.d.maxSkewNS}
|
||||
p.leaseMu.Unlock()
|
||||
p.logLease(alarm)
|
||||
p.logLease(note)
|
||||
p.logLease(summary)
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// firstWorkspaceGrant creates a lease synchronously under p.mu (one write per
|
||||
// assignment epoch) for an epoch that has none: a move issue already started
|
||||
// its holder's lease. A host whose first renewal fails does not fence: it has
|
||||
// no deadline yet and retries. The durable horizon starts at now+1.5*TTL.
|
||||
// no deadline yet and retries. The record's ExpiresAtNS is now+1.5*TTL, the
|
||||
// form v1.0.x reads; this process's deadline is now+TTL.
|
||||
func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
p.beforeWorkspaceGrantLock("first grant")
|
||||
p.mu.Lock()
|
||||
@@ -401,16 +370,15 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st
|
||||
}
|
||||
_, now, err := p.forcedMoveBarrierLocked(volume, s.Lease)
|
||||
if err != nil {
|
||||
// The same two predicates as admission: lease expiry plus skew (wall
|
||||
// time, persisted) and the grant deadline plus skew (this process's
|
||||
// monotonic clock), each measured from now. A client adds the result
|
||||
// to its own request start; it never compares clocks.
|
||||
// The admission's predicate: the grant deadline plus skew (this
|
||||
// process's monotonic clock; after a restart, the restart floor),
|
||||
// measured from now. A client adds the result to its own request
|
||||
// start; it never compares clocks.
|
||||
skew := p.workspaceSkew(s.Lease)
|
||||
retry := max(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).Sub(now), p.leaseDeadlineLocked(volume).Add(skew).Sub(now), 0)
|
||||
retry := max(p.leaseDeadlineLocked(volume).Add(skew).Sub(now), 0)
|
||||
return WorkspaceLease{}, &LeaseBarrierError{Until: now.Add(retry), RetryAfter: retry, err: err}
|
||||
}
|
||||
lease, grant := p.newWorkspaceLease(holder, epoch, now)
|
||||
lease.ExpiresAtNS = max(lease.ExpiresAtNS, s.Lease.ExpiresAtNS)
|
||||
lease.MaxClockSkewNS = int64(p.workspaceSkew(s.Lease))
|
||||
s.Lease = lease
|
||||
if err := p.persistWorkspaceLocked(volume, s); err != nil {
|
||||
@@ -420,91 +388,15 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st
|
||||
return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lease.MaxClockSkewNS}, nil
|
||||
}
|
||||
|
||||
// newWorkspaceLease starts a lease at now: the durable horizon is
|
||||
// now+1.5*TTL and the grant (the deadline) now+TTL. A first grant, expired
|
||||
// re-grant and move issue start a lease this way.
|
||||
// newWorkspaceLease starts a lease at now: the grant (the deadline) is
|
||||
// now+TTL. The record's ExpiresAtNS (now+1.5*TTL) is kept for the record's
|
||||
// shape and is read by nothing: a v1.0.x master would trust it, which is why
|
||||
// the record's envelope version is 2. A first grant, expired re-grant and
|
||||
// move issue start a lease this way.
|
||||
func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time) (*WorkspaceLease, time.Time) {
|
||||
return &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))}, now.Add(p.workspaceTTL)
|
||||
}
|
||||
|
||||
// extendWorkspaceLease is an ordinary writer: under p.mu it rechecks the
|
||||
// lease and writes horizon H = trigger + 1.5*TTL through
|
||||
// persistWorkspaceLocked, so its write and its publication are one p.mu
|
||||
// section. Any write error is an unknown write and latches uncertainty
|
||||
// (INV-AUTH-UNCERTAIN-001); a failed recheck is a known no-write.
|
||||
func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, trigger time.Time) {
|
||||
defer p.extWG.Done()
|
||||
p.beforeWorkspaceGrantLock("extension")
|
||||
var note string
|
||||
defer func() {
|
||||
if note != "" {
|
||||
log.Print(note)
|
||||
}
|
||||
}()
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
defer func() {
|
||||
p.leaseMu.Lock()
|
||||
if lv := p.leaseViews[volume]; lv != nil {
|
||||
lv.extending = false
|
||||
}
|
||||
p.leaseMu.Unlock()
|
||||
}()
|
||||
p.leaseMu.Lock()
|
||||
closing := p.leaseClosing
|
||||
p.leaseMu.Unlock()
|
||||
if closing || p.deleteReserved[volume] {
|
||||
return
|
||||
}
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
s := cloneWorkspace(p.workspace[volume])
|
||||
if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch || s == nil || s.Lease == nil || s.Lease.Revoking ||
|
||||
s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) ||
|
||||
p.workspaceUncertain[volume] || p.store == nil {
|
||||
return
|
||||
}
|
||||
h := trigger.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano()
|
||||
old := s.Lease.ExpiresAtNS
|
||||
if h <= old {
|
||||
return
|
||||
}
|
||||
s.Lease.ExpiresAtNS = h
|
||||
write, wrote, err := p.persistWorkspaceTimedLocked(volume, s)
|
||||
if wrote {
|
||||
// The store write alone, failed or not, recorded when it returns
|
||||
// (completed-write telemetry; a blocked write is not seen until then).
|
||||
p.leaseMu.Lock()
|
||||
p.leaseStats.recordExtensionWrite(p.workspaceNow(), write)
|
||||
p.leaseMu.Unlock()
|
||||
}
|
||||
took := write.Round(time.Millisecond)
|
||||
if err != nil {
|
||||
if p.extendFailures[volume] == 0 {
|
||||
note = fmt.Sprintf("workspace lease: extension of volume=%s failed after %s (horizon %s, %s remaining); the volume is now uncertain and its renewals are refused: %v",
|
||||
volume, took, time.Unix(0, old).UTC().Format(time.RFC3339Nano), time.Until(time.Unix(0, old)).Round(time.Millisecond), err)
|
||||
}
|
||||
p.extendFailures[volume]++
|
||||
return
|
||||
}
|
||||
if n := p.extendFailures[volume]; n > 0 {
|
||||
note = fmt.Sprintf("workspace lease: extension of volume=%s recovered after %d failures, took %s, horizon now %s", volume, n, took, time.Unix(0, h).UTC().Format(time.RFC3339Nano))
|
||||
delete(p.extendFailures, volume)
|
||||
}
|
||||
}
|
||||
|
||||
// CloseWorkspaceExtenders stops admitting lease extensions and joins every
|
||||
// admitted extender. Owners call it before closing the authority store:
|
||||
// closing is set under p.mu -> leaseMu, so an extender either finished its
|
||||
// write before or sees closing and does not write.
|
||||
func (p *Publisher) CloseWorkspaceExtenders() {
|
||||
p.mu.Lock()
|
||||
p.leaseMu.Lock()
|
||||
p.leaseClosing = true
|
||||
p.leaseMu.Unlock()
|
||||
p.mu.Unlock()
|
||||
p.extWG.Wait()
|
||||
}
|
||||
|
||||
// LeaseBarrierError is an expired re-grant refused because the forced-move
|
||||
// barrier has not passed. Until is when it passes (master wall time) and
|
||||
// RetryAfter is Until minus the master's time at the refusal, so a client
|
||||
|
||||
@@ -14,7 +14,8 @@ import (
|
||||
// WorkspaceLostRange records what a forced move abandoned: the old holder's
|
||||
// writes after LostAfterLSN (the HEAD frontier the move keeps) are lost, and
|
||||
// none of them was acknowledged later than LostUntilNS (master time: the
|
||||
// forced barrier, the lease horizon or restart deadline plus skew). The
|
||||
// forced barrier: the lease deadline, or after a restart the restart floor,
|
||||
// plus skew). The
|
||||
// lease carries no write frontier, so the upper bound is a time.
|
||||
//
|
||||
// HeadTimeNS is the kept HEAD entry's filer mtime, read with that HEAD at the
|
||||
|
||||
@@ -32,11 +32,9 @@ func forcedLostRangeFixture(t *testing.T, store AuthorityStore, restart bool) (p
|
||||
if restart && !p.leaseDeadlineLockedForTest("v").After(time.Unix(0, lease.ExpiresAtNS)) {
|
||||
t.Fatal("fixture: the restart deadline is not the later barrier term")
|
||||
}
|
||||
barrier = time.Unix(0, lease.ExpiresAtNS)
|
||||
if d := p.leaseDeadlineLockedForTest("v"); d.After(barrier) {
|
||||
barrier = d
|
||||
}
|
||||
return p, now, barrier.Add(p.workspaceSkew(lease))
|
||||
// The barrier is this process's deadline (the grant's, or after a
|
||||
// restart its floor) plus skew; the persisted ExpiresAtNS is not a term.
|
||||
return p, now, p.leaseDeadlineLockedForTest("v").Add(p.workspaceSkew(lease))
|
||||
}
|
||||
|
||||
var forcedLostRangeReq = WorkspaceMoveRequest{RequestID: "f", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1,
|
||||
@@ -44,8 +42,8 @@ var forcedLostRangeReq = WorkspaceMoveRequest{RequestID: "f", VolumeID: "v", Exp
|
||||
var forcedLostRangeHead = WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42}
|
||||
|
||||
// A forced move records the abandoned range beside its record: the kept HEAD
|
||||
// frontier and the forced barrier (lease horizon, or after a restart the
|
||||
// later restart deadline, plus skew) as the latest master time an old-holder
|
||||
// frontier and the forced barrier (the lease deadline, or after a restart
|
||||
// the restart floor, plus skew) as the latest master time an old-holder
|
||||
// write can have been acknowledged. A reload returns it; the move record's
|
||||
// own encoding is unchanged, so older binaries still verify and load it.
|
||||
func TestWorkspaceForcedMoveRecordsTheLostRange(t *testing.T) {
|
||||
|
||||
@@ -73,7 +73,6 @@ 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) {
|
||||
|
||||
@@ -214,17 +214,16 @@ func TestWorkspaceLeaseRegrantWaitsForFullSkew(t *testing.T) {
|
||||
clock := newTestClock()
|
||||
store := &hookStore{AuthorityStore: disk}
|
||||
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(10*time.Second, clock.now), WithWorkspaceMaxClockSkew(4*time.Second))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders)
|
||||
grant := bindAndGrant(t, p, "v", "r")
|
||||
if grant.ExpiresAtNS != clock.sec(10).UnixNano() || p.WorkspaceState("v").Lease.ExpiresAtNS != clock.sec(15).UnixNano() {
|
||||
t.Fatal("fixture did not create the declared grant/horizon", grant)
|
||||
t.Fatal("fixture did not create the declared grant and record", grant)
|
||||
}
|
||||
writes := 0
|
||||
store.setBefore(func(DurableRecord) error { writes++; return nil })
|
||||
// The deadline+skew boundary is 14 s; horizon+skew is 19 s.
|
||||
// Re-grant uses the same MAX barrier as a forced move, including the
|
||||
// interval after the shorter deadline has passed and its final ns.
|
||||
for _, now := range []time.Time{clock.sec(13), clock.sec(14), clock.sec(19).Add(-time.Nanosecond)} {
|
||||
// The barrier is deadline+skew, 14 s; the persisted record's 15 s is
|
||||
// not a term. Re-grant uses the same barrier as a forced move, including
|
||||
// the interval after the deadline has passed and its final ns.
|
||||
for _, now := range []time.Time{clock.sec(10), clock.sec(13), clock.sec(14).Add(-time.Nanosecond)} {
|
||||
clock.ns.Store(now.UnixNano())
|
||||
if got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil {
|
||||
t.Fatal("re-grant crossed the later expiry/skew boundary early", now, got)
|
||||
@@ -236,7 +235,7 @@ func TestWorkspaceLeaseRegrantWaitsForFullSkew(t *testing.T) {
|
||||
t.Fatal("unsafe early re-grant attempted persistence", writes)
|
||||
}
|
||||
}
|
||||
clock.at(19)
|
||||
clock.at(14)
|
||||
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "force", "r", 1); err != nil {
|
||||
t.Fatal("fixture did not reach the shared forced-move barrier", err)
|
||||
}
|
||||
@@ -251,10 +250,8 @@ func TestWorkspaceLeaseRegrantRetainsPersistedSkewAfterRestart(t *testing.T) {
|
||||
clock := newTestClock()
|
||||
first := newLeasePublisher(t, disk, time.Second, clock)
|
||||
before := bindAndGrant(t, first, "v", "r")
|
||||
first.CloseWorkspaceExtenders()
|
||||
clock.at(3)
|
||||
returned := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, clock.now), WithWorkspaceMaxClockSkew(time.Millisecond))
|
||||
t.Cleanup(returned.CloseWorkspaceExtenders)
|
||||
// Restart deadline is 4 s. The newly configured 1 ms bound has passed,
|
||||
// but the original persisted bound still protects the previous process.
|
||||
clock.at(4.5)
|
||||
|
||||
@@ -27,14 +27,14 @@ func (s *slowLeaseStore) Put(r DurableRecord) error {
|
||||
|
||||
// A renewal of a live lease must not wait for the authority store's fsync:
|
||||
// the host's renewal RPC times out after 2 s, so a slower store write on the
|
||||
// renewal path turns into a host fence and a volume shutdown (issue #205).
|
||||
// renewal path turns into a host fence and a volume shutdown (issue #205). A
|
||||
// renewal writes nothing, so it never reaches the stalled store.
|
||||
func TestWorkspaceRenewalDoesNotWaitForSlowStore(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
slow := &slowLeaseStore{AuthorityStore: disk}
|
||||
var nowNS atomic.Int64
|
||||
nowNS.Store(time.Unix(1000, 0).UnixNano())
|
||||
p := NewPublisher(nil, WithStore(slow), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -58,9 +58,8 @@ func TestWorkspaceRenewalDoesNotWaitForSlowStore(t *testing.T) {
|
||||
t.Fatalf("renewal of a live lease took %s behind a 2.5 s store write; the host's renewal RPC times out at 2 s", took.Round(time.Millisecond))
|
||||
}
|
||||
t.Logf("renewal took %s", took)
|
||||
waitExtenders(t, p)
|
||||
if slow.puts.Load() == 0 {
|
||||
t.Fatal("no lease write went through the 2.5 s stall: the test did not exercise it")
|
||||
if slow.puts.Load() != 0 {
|
||||
t.Fatalf("a renewal of a live lease wrote %d lease records; it writes nothing", slow.puts.Load())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +72,6 @@ func TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore(t *testing.T) {
|
||||
var nowNS atomic.Int64
|
||||
nowNS.Store(time.Unix(1000, 0).UnixNano())
|
||||
p := NewPublisher(nil, WithStore(slow), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes
|
||||
const n = 6
|
||||
for i := 0; i < n; i++ {
|
||||
v := fmt.Sprintf("v%d", i)
|
||||
@@ -116,9 +114,8 @@ func TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore(t *testing.T) {
|
||||
t.Fatalf("slowest of %d concurrent renewals took %s (all: %v); renewals serialize behind each other's store writes", n, slowest.Round(time.Millisecond), took)
|
||||
}
|
||||
t.Logf("slowest of %d concurrent renewals took %s", n, slowest)
|
||||
waitExtenders(t, p)
|
||||
if slow.puts.Load() == 0 {
|
||||
t.Fatal("no lease write went through the 0.5 s stall: the test did not exercise it")
|
||||
if slow.puts.Load() != 0 {
|
||||
t.Fatalf("renewals of live leases wrote %d lease records; they write nothing", slow.puts.Load())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,7 +153,6 @@ func TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite(t *testing.T) {
|
||||
var nowNS atomic.Int64
|
||||
nowNS.Store(time.Unix(1000, 0).UnixNano())
|
||||
p := NewPublisher(nil, WithStore(held), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes
|
||||
for _, v := range []string{"a", "b"} {
|
||||
if err := p.apply(AssignmentAsk{VolumeID: v, ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -16,7 +16,6 @@ func TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor(t *testing.T
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, disk, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r") // t=0: lease horizon t=45 (1.5 TTL), grant deadline t=30
|
||||
p.CloseWorkspaceExtenders()
|
||||
|
||||
c.at(40) // the master restarts while the lease is still live
|
||||
p2 := newLeasePublisher(t, disk, 30*time.Second, c)
|
||||
@@ -45,7 +44,6 @@ func TestAfterARestartTheSameLiveHolderRenewsAtOnce(t *testing.T) {
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, disk, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
p.CloseWorkspaceExtenders()
|
||||
|
||||
c.at(20)
|
||||
p2 := newLeasePublisher(t, disk, 30*time.Second, c)
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Renewals write nothing durable: a grant is now+TTL from memory, and no
|
||||
// horizon is kept current behind it. 1,000 renewals over 100 volumes (50 s
|
||||
// at TTL 30 s) add no record. (The horizon design wrote one extension per
|
||||
// volume about every quarter TTL.)
|
||||
func TestRenewalWritesNothingDurable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c := newTestClock()
|
||||
st := &deleteGrantStore{}
|
||||
p := newLeasePublisher(t, st, 30*time.Second, c)
|
||||
for i := 0; i < 100; i++ {
|
||||
bindAndGrant(t, p, fmt.Sprintf("v%03d", i), "r")
|
||||
}
|
||||
base := len(st.records)
|
||||
for round := 1; round <= 10; round++ {
|
||||
c.at(float64(round * 5))
|
||||
for i := 0; i < 100; i++ {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, fmt.Sprintf("v%03d", i), "r", 1); err != nil {
|
||||
t.Fatalf("round %d, v%03d: %v", round, i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond) // an asynchronous writer, had one started, would have written
|
||||
if n := len(st.records) - base; n != 0 {
|
||||
t.Fatalf("1,000 renewals wrote %d records, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// After a restart, a different holder is admitted at the restart floor
|
||||
// (restart + TTL + skew, on the new process's own clock), whatever wall
|
||||
// value an earlier process wrote: here the clock was stepped back an hour
|
||||
// across the restart, and the old record's horizon lies an hour ahead.
|
||||
func TestForcedAdmissionIgnoresAPersistedHorizon(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c := newTestClock()
|
||||
st := &deleteGrantStore{}
|
||||
p := newLeasePublisher(t, st, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r") // t=0: the record's ExpiresAtNS is t=45 s (wall)
|
||||
c.at(-3600) // the clock steps back an hour; the master restarts
|
||||
p2 := newLeasePublisher(t, st, 30*time.Second, c)
|
||||
c.at(-3600 + 49)
|
||||
if err := p2.WorkspaceForcedMoveAdmitted(ctx, "v", "fm-early", "r", 1); err == nil {
|
||||
t.Fatal("a forced move was admitted before the restart floor (restart + TTL + skew)")
|
||||
}
|
||||
c.at(-3600 + 50)
|
||||
if err := p2.WorkspaceForcedMoveAdmitted(ctx, "v", "fm-floor", "r", 1); err != nil {
|
||||
t.Fatalf("a forced move at the restart floor was refused (it waited for a wall value an earlier process wrote): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The authority record's envelope is version 2: v1.0.x's decoder refuses
|
||||
// every envelope version but 1 (its loader then skips the record, so this
|
||||
// alone does not stop a v1.0.x master: the store's attestation envelope
|
||||
// fails its whole start, TestAV100MasterRefusesTheAttestationEnvelope in
|
||||
// core/host/master). Today's decoder reads both.
|
||||
func TestARecordWrittenNowFailsTheV100Decoder(t *testing.T) {
|
||||
r := DurableRecord{VolumeID: "v", ReplicaID: "r", Epoch: 1}
|
||||
raw, err := encodeEnvelope(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var env struct {
|
||||
Version int `json:"v"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// v1.0.x's decodeEnvelope: "if env.Version != 1 { ErrCorruptRecord }".
|
||||
if env.Version == storeEnvelopeVersionV100 {
|
||||
t.Fatalf("a record written now carries envelope version %d, which v1.0.x's decoder accepts", env.Version)
|
||||
}
|
||||
if _, err := decodeEnvelope(raw, "v"); err != nil {
|
||||
t.Fatalf("today's decoder refuses today's record: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The deadline admission compares keeps its monotonic reading through a
|
||||
// first grant and through every renewal, so a wall-clock step inside one
|
||||
// master neither shortens nor extends a lease (Go prints a monotonic
|
||||
// reading as "m=").
|
||||
func TestLeaseDeadlineKeepsItsMonotonicReading(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
p := NewPublisher(nil, WithStore(&deleteGrantStore{}), WithWorkspaceLeaseConfig(30*time.Second, nil)) // the real clock
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
monotonic := func(what string) {
|
||||
t.Helper()
|
||||
if d := p.leaseDeadlineLockedForTest("v"); !strings.Contains(d.String(), "m=") {
|
||||
t.Fatalf("%s: the deadline %v has no monotonic reading: admission would compare wall time", what, d)
|
||||
}
|
||||
}
|
||||
monotonic("after the first grant")
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
monotonic("after a renewal")
|
||||
}
|
||||
@@ -23,10 +23,9 @@ func TestWorkspaceClockSkewPersistsAndProtectsRestart(t *testing.T) {
|
||||
if lease.MaxClockSkewNS != int64(4*time.Second) {
|
||||
t.Fatal("configured margin not in durable grant", lease)
|
||||
}
|
||||
// The first grant persists the durable horizon start+1.5*TTL (9 s),
|
||||
// the upper bound of every later grant; the forced barrier is
|
||||
// horizon + skew, TTL/2 later than the grant itself (#205).
|
||||
boundary := start.Add(9*time.Second + 4*time.Second)
|
||||
// The forced barrier is the grant's deadline (start+TTL) plus the
|
||||
// persisted skew; after a restart, the restart floor plus it.
|
||||
boundary := start.Add(6*time.Second + 4*time.Second)
|
||||
if restart {
|
||||
now = start.Add(7 * time.Second)
|
||||
p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(6*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(time.Second))
|
||||
|
||||
@@ -35,7 +35,7 @@ func TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant(t *testing.T) {
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Past the durable horizon (1.5*TTL) plus skew, not only the grant (#205).
|
||||
// Past the grant's deadline plus skew.
|
||||
now = now.Add(3 * time.Second)
|
||||
req := WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42}
|
||||
@@ -172,7 +172,9 @@ func TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry(t *testing.T) {
|
||||
if _, err := p.MoveWorkspace(ctx, req, head); err == nil {
|
||||
t.Fatal("unexpired lease moved")
|
||||
}
|
||||
now = now.Add(2 * time.Second)
|
||||
// Past the deadline, before deadline plus skew: the expired holder is
|
||||
// not re-granted (a re-grant waits for the move barrier).
|
||||
now = now.Add(1500 * time.Millisecond)
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err == nil {
|
||||
t.Fatal("expired host renewed")
|
||||
}
|
||||
@@ -236,7 +238,7 @@ func TestWorkspaceMoveUsesQualifiedHEADHolder(t *testing.T) {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "same", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Past the durable horizon (1.5*TTL) plus skew, not only the grant (#205).
|
||||
// Past the grant's deadline plus skew.
|
||||
now = now.Add(3 * time.Second)
|
||||
q := WorkspaceMoveRequest{RequestID: "qualified", VolumeID: "v", ExpectedReplicaID: "same", TargetReplicaID: "same", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
for _, holder := range []string{"same", "other-node/same", "old-node/other"} {
|
||||
|
||||
@@ -94,12 +94,15 @@ func TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry(t *testing.T) {
|
||||
assertLeaseViewMatches(t, p, "after restart")
|
||||
}
|
||||
skew := p.workspaceSkew(p.WorkspaceState("v").Lease)
|
||||
// The horizon (issue+1.5*TTL) is the later bound: the deadline is
|
||||
// issue+TTL, or restart+TTL after a restart 0.2*TTL later.
|
||||
barrier := issued.Add(grantTTL + grantTTL/2 + skew)
|
||||
// The deadline is issue+TTL, or the restart floor restart+TTL
|
||||
// after a restart 0.2 s later; the barrier is it plus skew.
|
||||
barrier := issued.Add(grantTTL + skew)
|
||||
if restart {
|
||||
barrier = barrier.Add(200 * time.Millisecond)
|
||||
}
|
||||
// The predecessor's lease (renewed 0.1 s before the issue) has
|
||||
// expired plus skew by then: only the grant's lease may admit.
|
||||
if old := issued.Add(-100*time.Millisecond + grantTTL + grantTTL/2 + skew); !barrier.Add(-time.Nanosecond).After(old) {
|
||||
if old := issued.Add(-100*time.Millisecond + grantTTL + skew); !barrier.Add(-time.Nanosecond).After(old) {
|
||||
t.Fatal("test clock does not separate the predecessor's barrier from the grant's")
|
||||
}
|
||||
now = barrier.Add(-time.Nanosecond)
|
||||
@@ -214,18 +217,15 @@ func TestWorkspaceUnclaimedGrantGranteeRenewsNormally(t *testing.T) {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil {
|
||||
t.Fatal("old epoch renewed after the move")
|
||||
}
|
||||
// Past 0.25*TTL the renewal starts an extension of the issued lease.
|
||||
// A later renewal moves the deadline and writes nothing: the persisted
|
||||
// lease stays the one the issue wrote.
|
||||
now = issued.Add(grantTTL / 2)
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil {
|
||||
t.Fatal(err)
|
||||
if l, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil || l.ExpiresAtNS != now.Add(grantTTL).UnixNano() {
|
||||
t.Fatal("later renewal:", l, err)
|
||||
}
|
||||
st := p.WorkspaceState("v")
|
||||
for wait := time.Now().Add(5 * time.Second); time.Now().Before(wait) && (st.Lease == nil || st.Lease.ExpiresAtNS == issued.Add(grantTTL+grantTTL/2).UnixNano()); st = p.WorkspaceState("v") {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
p.CloseWorkspaceExtenders()
|
||||
if st.Lease == nil || st.Lease.Epoch != 2 || st.Lease.ExpiresAtNS != now.Add(grantTTL+grantTTL/2).UnixNano() {
|
||||
t.Fatalf("issued lease not extended: %+v", st.Lease)
|
||||
if store.puts.Load() != writes || st.Lease == nil || st.Lease.Epoch != 2 || st.Lease.ExpiresAtNS != issued.Add(grantTTL+grantTTL/2).UnixNano() {
|
||||
t.Fatalf("a renewal wrote: %d records, lease %+v", store.puts.Load()-writes, st.Lease)
|
||||
}
|
||||
if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(st.Moves) != 1 {
|
||||
t.Fatal("renewals changed authority", line)
|
||||
|
||||
@@ -16,9 +16,9 @@ func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) {
|
||||
{"before", 28*time.Second - time.Nanosecond, true, false},
|
||||
{"at", 28 * time.Second, false, false},
|
||||
{"after", 29 * time.Second, false, false},
|
||||
{"horizon-before", 43*time.Second - time.Nanosecond, true, true},
|
||||
{"horizon-at", 43 * time.Second, false, true},
|
||||
{"horizon-after", 44 * time.Second, false, true},
|
||||
{"restart-before", 48*time.Second - time.Nanosecond, true, true},
|
||||
{"restart-at", 48 * time.Second, false, true},
|
||||
{"restart-after", 49 * time.Second, false, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
@@ -36,8 +36,9 @@ func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tc.restart {
|
||||
// Reopening at +20s gives a restart deadline of +50s, beyond
|
||||
// the persisted +45s horizon. ACK must stop at +43s.
|
||||
// Reopening at +20s gives a restart floor of +50s, beyond the
|
||||
// persisted record's +45s: the ACK follows the floor and stops
|
||||
// at +48s (the floor minus half the skew).
|
||||
now = start.Add(20 * time.Second)
|
||||
p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second))
|
||||
p.mu.Lock()
|
||||
|
||||
@@ -336,6 +336,9 @@ type volHandle struct {
|
||||
// startupIdentityRefused is the definite full-id refusal for startupEnded.
|
||||
// endChunkStartup is its decision writer, guarded by p.mu.
|
||||
startupIdentityRefused bool
|
||||
// startupNewerVersion: startupEnded's refusal was a HEAD written by a
|
||||
// newer version (layout.ErrHeadNewerVersion). endChunkStartup writes it.
|
||||
startupNewerVersion bool
|
||||
|
||||
// ImplWALStoreChunk. fresh: the local volume is new and starts from
|
||||
// the remote HEAD. It mirrors the durable fresh marker beside the
|
||||
@@ -1165,6 +1168,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R
|
||||
h.startupEnded = 0
|
||||
h.startupSuperseded = false
|
||||
h.startupIdentityRefused = false
|
||||
h.startupNewerVersion = false
|
||||
p.mu.Unlock()
|
||||
}
|
||||
report := recoverContext(ctx, h.storage, volumeID)
|
||||
|
||||
@@ -44,6 +44,15 @@ func (p *DurableProvider) ChunkStartupIdentityRefused(volumeID string, gen uint6
|
||||
return !p.closed && h != nil && gen != 0 && h.recoverGen == gen && h.startupEnded == gen && h.startupIdentityRefused
|
||||
}
|
||||
|
||||
// ChunkStartupNewerVersion reports that this recovery's startup ended on a
|
||||
// HEAD written by a newer version: no restart of this binary can read it.
|
||||
func (p *DurableProvider) ChunkStartupNewerVersion(volumeID string, gen uint64) bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
h := p.volumes[volumeID]
|
||||
return !p.closed && h != nil && gen != 0 && h.recoverGen == gen && h.startupEnded == gen && h.startupNewerVersion
|
||||
}
|
||||
|
||||
func (p *DurableProvider) endChunkStartup(h *volHandle, gen uint64, cause error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
@@ -53,6 +62,7 @@ func (p *DurableProvider) endChunkStartup(h *volHandle, gen uint64, cause error)
|
||||
h.startupEnded = gen
|
||||
h.startupSuperseded = errors.Is(cause, errChunkForeignClaim)
|
||||
h.startupIdentityRefused = errors.Is(cause, layout.ErrIdentity)
|
||||
h.startupNewerVersion = errors.Is(cause, layout.ErrHeadNewerVersion)
|
||||
h.startupCure = ""
|
||||
switch {
|
||||
case errors.Is(cause, layout.ErrStaleLocalRoot):
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
package durable
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
func TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake(t *testing.T) {
|
||||
h := &volHandle{recoverGen: 1}
|
||||
@@ -55,3 +60,20 @@ func TestChunkStartupForeignProofIsGenerationBound(t *testing.T) {
|
||||
t.Fatal("old foreign proof poisoned current retry")
|
||||
}
|
||||
}
|
||||
|
||||
// A startup that ends on a HEAD written by a newer version is latched for
|
||||
// that recovery only; another cause (a malformed HEAD) is not it.
|
||||
func TestChunkStartupNewerVersionIsGenerationBound(t *testing.T) {
|
||||
h := &volHandle{recoverGen: 1}
|
||||
p := &DurableProvider{volumes: map[string]*volHandle{"v": h}, startupUpdates: make(chan struct{}, 1)}
|
||||
p.endChunkStartup(h, 1, fmt.Errorf("attach: %w", layout.ErrHeadNewerVersion))
|
||||
if !p.ChunkStartupNewerVersion("v", 1) || p.ChunkStartupNewerVersion("v", 2) || p.ChunkStartupNewerVersion("other", 1) {
|
||||
t.Fatal("the newer-version refusal escaped its volume or recovery generation")
|
||||
}
|
||||
h2 := &volHandle{recoverGen: 1}
|
||||
p2 := &DurableProvider{volumes: map[string]*volHandle{"v": h2}, startupUpdates: make(chan struct{}, 1)}
|
||||
p2.endChunkStartup(h2, 1, fmt.Errorf("attach: %w", layout.ErrMalformed))
|
||||
if p2.ChunkStartupNewerVersion("v", 1) {
|
||||
t.Fatal("a malformed HEAD was taken for a newer version")
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,13 @@ import (
|
||||
"bytes"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
@@ -76,19 +79,74 @@ func TestAttestationGoldenFileIsTheV100File(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Today's store writes the v1.0.0 file for the same steps.
|
||||
func TestAttestationsWriteTheV100File(t *testing.T) {
|
||||
// Today's store writes the v1.0.0 file's volumes for the same steps, inside
|
||||
// this version's envelope: {"format":2,"volumes":<the v1.0.0 bytes>}. The
|
||||
// one change since v1.0.0, by the format path: a v1.0.x master refuses the
|
||||
// envelope at start (TestAV100MasterRefusesTheAttestationEnvelope).
|
||||
func TestAttestationsWriteTheV100FileInTheEnvelope(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
goldenAttestations(t, dir)
|
||||
got, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := readGoldenAttestations(t); !bytes.Equal(got, want) {
|
||||
want := append(append([]byte(`{"format":2,"volumes":`), readGoldenAttestations(t)...), '}')
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("%s\n got %s\n want %s", goldenAttestationFix, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A v1.0.x master decodes store-attestations.json as a bare map of volume
|
||||
// records (json.Unmarshal into map[string]attestedStores, its
|
||||
// loadStoreAttestations), and its New returns that error before it listens
|
||||
// or publishes. The envelope fails that decode; today's master reads both
|
||||
// forms, and a master started on a v1.0.x store rewrites it as the envelope
|
||||
// before it serves.
|
||||
func TestAV100MasterRefusesTheAttestationEnvelope(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
goldenAttestations(t, dir)
|
||||
b, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var v100 map[string]attestedStores // v1.0.x's decode, verbatim
|
||||
if err := json.Unmarshal(b, &v100); err == nil {
|
||||
t.Fatalf("a v1.0.x master's decode accepted the file written now: %v", v100)
|
||||
}
|
||||
if bad := readAttestations(dir); len(bad) != 0 {
|
||||
t.Fatalf("today's master does not read its own envelope: %v", bad)
|
||||
}
|
||||
// A v1.0.x store (the bare map) is read, and ensureEnvelope rewrites it.
|
||||
old := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(old, storeAttestationFile), readGoldenAttestations(t), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := loadStoreAttestations(old)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bad := readAttestations(old); len(bad) != 0 {
|
||||
t.Fatalf("today's master does not read the v1.0.x form: %v", bad)
|
||||
}
|
||||
if err := s.ensureEnvelope(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err = os.ReadFile(filepath.Join(old, storeAttestationFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.Unmarshal(b, &v100); err == nil {
|
||||
t.Fatal("after ensureEnvelope, a v1.0.x master's decode still accepts the store")
|
||||
}
|
||||
// An envelope of a later format is refused by this master too.
|
||||
if err := os.WriteFile(filepath.Join(old, storeAttestationFile), []byte(`{"format":3,"volumes":{}}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := loadStoreAttestations(old); err == nil {
|
||||
t.Fatal("this master accepted attestation format 3")
|
||||
}
|
||||
}
|
||||
|
||||
// wantAttestations is the v1.0.0 file's content, written out independently
|
||||
// of the store: every volume's primary, epoch, stores and initial replicas.
|
||||
var wantAttestations = map[string]attestedStores{
|
||||
@@ -158,3 +216,129 @@ func TestAttestationReadCheckSeesLostState(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The envelope's volumes are an explicit object: a missing or null one is
|
||||
// refused (never read as no attestations), {} is no volumes. A v1.0.x file
|
||||
// whose volumes are named "format" or "volumes" is still read as the bare
|
||||
// map it is.
|
||||
func TestAttestationEnvelopeNeedsItsVolumesObject(t *testing.T) {
|
||||
load := func(body string) (*storeAttestations, error) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return loadStoreAttestations(dir)
|
||||
}
|
||||
for _, body := range []string{`{"format":2}`, `{"format":2,"volumes":null}`, `{"format":2, "volumes" : null }`, `{"format":2,"volumes":[]}`, `{"format":2,"volumes":"x"}`, `{"format":2,"volumes":{},"Volumes":null}`} {
|
||||
if _, err := load(body); err == nil {
|
||||
t.Errorf("%s was read (as no attestations)", body)
|
||||
}
|
||||
}
|
||||
if s, err := load(`{"format":2,"volumes":{}}`); err != nil || len(s.vols) != 0 || !s.enveloped {
|
||||
t.Errorf("an empty volumes object: %v %+v", err, s)
|
||||
}
|
||||
s, err := load(`{"format":{"primary":"r1","epoch":2,"stores":{}},"volumes":{"primary":"r2","epoch":3,"stores":{}}}`)
|
||||
if err != nil || s.enveloped || s.vols["format"].Primary != "r1" || s.vols["volumes"].Primary != "r2" {
|
||||
t.Errorf("a v1.0.x file with volumes named format and volumes: %v %+v", err, s)
|
||||
}
|
||||
}
|
||||
|
||||
// An envelope already on disk is fsynced again (file and directory) on every
|
||||
// start: a start that renamed it in and then failed its directory fsync must
|
||||
// not leave the next start serving on an envelope that may not survive a
|
||||
// crash.
|
||||
func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), readGoldenAttestations(t), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved := syncAttestationDir
|
||||
t.Cleanup(func() { syncAttestationDir = saved })
|
||||
syncs := 0
|
||||
syncAttestationDir = func(string) error { syncs++; return errors.New("injected directory fsync failure") }
|
||||
s, err := loadStoreAttestations(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ensureEnvelope(); err == nil {
|
||||
t.Fatal("a failed directory fsync of the first envelope write was not an error (the master would serve)")
|
||||
}
|
||||
// The process restarts: the envelope is on disk (the rename happened).
|
||||
s, err = loadStoreAttestations(dir)
|
||||
if err != nil || !s.enveloped {
|
||||
t.Fatalf("restart: %v enveloped=%v", err, s != nil && s.enveloped)
|
||||
}
|
||||
syncs = 0
|
||||
if err := s.ensureEnvelope(); err == nil || syncs != 1 {
|
||||
t.Fatalf("restart with the directory fsync still failing: err=%v, %d directory fsyncs (want an error after one)", err, syncs)
|
||||
}
|
||||
syncAttestationDir = func(string) error { syncs++; return nil }
|
||||
syncs = 0
|
||||
if err := s.ensureEnvelope(); err != nil || syncs != 1 {
|
||||
t.Fatalf("restart: err=%v, %d directory fsyncs, want one before serving", err, syncs)
|
||||
}
|
||||
}
|
||||
|
||||
// The envelope round-trips: loading a written envelope and writing it again
|
||||
// gives the same bytes.
|
||||
func TestAttestationEnvelopeRoundTrips(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
goldenAttestations(t, dir)
|
||||
first, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := loadStoreAttestations(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.mu.Lock()
|
||||
err = s.persist(s.vols)
|
||||
s.mu.Unlock()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
|
||||
if err != nil || !bytes.Equal(first, again) {
|
||||
t.Fatalf("round trip changed the envelope (%v): %s / %s", err, first, again)
|
||||
}
|
||||
}
|
||||
|
||||
// master.New refuses to serve when the attestation envelope cannot be made
|
||||
// durable: it returns the error before it listens.
|
||||
func TestMasterNewRefusesWhenTheEnvelopeIsNotDurable(t *testing.T) {
|
||||
saved := syncAttestationDir
|
||||
t.Cleanup(func() { syncAttestationDir = saved })
|
||||
syncAttestationDir = func(string) error { return errors.New("injected directory fsync failure") }
|
||||
h, err := New(Config{AuthorityStoreDir: t.TempDir(), Listen: "127.0.0.1:0"})
|
||||
if err == nil {
|
||||
closeTestMaster(t, h)
|
||||
t.Fatal("master.New served with a failed attestation envelope fsync")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "injected directory fsync failure") {
|
||||
t.Fatalf("master.New failed for another reason: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A v1.0.x file that is null holds no attestations (as v1.0.x read it): it
|
||||
// migrates to an envelope with an explicit {} that the next start reads.
|
||||
func TestAV100NullAttestationFileMigrates(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte("null"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := loadStoreAttestations(dir)
|
||||
if err != nil || len(s.vols) != 0 {
|
||||
t.Fatalf("a null v1.0.x file: %v %+v", err, s)
|
||||
}
|
||||
if err := s.ensureEnvelope(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
|
||||
if err != nil || string(b) != `{"format":2,"volumes":{}}` {
|
||||
t.Fatalf("migrated to %s (%v)", b, err)
|
||||
}
|
||||
if _, err := loadStoreAttestations(dir); err != nil {
|
||||
t.Fatalf("the next start refuses the migrated file: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -283,6 +283,14 @@ func New(cfg Config) (*Host, error) {
|
||||
// An unknown identity (stat error, unsupported platform) never matches.
|
||||
h.journal.setSelf(storeident.Of(cfg.AuthorityStoreDir))
|
||||
if h.attest, err = loadStoreAttestations(cfg.AuthorityStoreDir); err != nil {
|
||||
_ = boot.Close() // release the store lock: this master never serves
|
||||
return nil, fmt.Errorf("master.New: %w", err)
|
||||
}
|
||||
// Under the authority store's lock and before anything is served: the
|
||||
// attestation file in this version's envelope, which a v1.0.x master
|
||||
// refuses at start (store_attestation.go).
|
||||
if err := h.attest.ensureEnvelope(); err != nil {
|
||||
_ = boot.Close()
|
||||
return nil, fmt.Errorf("master.New: %w", err)
|
||||
}
|
||||
|
||||
@@ -630,10 +638,6 @@ func (h *Host) Close(ctx context.Context) error {
|
||||
}
|
||||
|
||||
h.wg.Wait()
|
||||
// Join lease extenders (authority writers) before the store closes.
|
||||
if h.boot != nil && h.boot.Publisher != nil {
|
||||
h.boot.Publisher.CloseWorkspaceExtenders()
|
||||
}
|
||||
return errors.Join(statusErr, h.boot.Close())
|
||||
}
|
||||
|
||||
|
||||
@@ -13,8 +13,8 @@ import (
|
||||
|
||||
// journalIsolation tracks nodes whose durable root shares the authority
|
||||
// store's file system. On one ext4 file system every fsync goes through one
|
||||
// jbd2 journal: a volume's WAL fsync storm delays the authority journal's
|
||||
// lease extensions, grants clamp to the durable horizon and leases run out.
|
||||
// jbd2 journal: a volume's WAL fsync storm delays every authority write
|
||||
// (grants, moves, revocations) behind it.
|
||||
//
|
||||
// The colocated set is the latest heartbeat fact per server (memory only): a
|
||||
// node that moves its durable root off the store's file system leaves the set
|
||||
@@ -189,38 +189,19 @@ func ValidateControlListen(flag, addr string) error {
|
||||
return fmt.Errorf("--%s %q is not a loopback address: an unauthenticated listener stays on loopback", flag, addr)
|
||||
}
|
||||
|
||||
// WorkspaceLeaseStatus is the GET /status/workspace-lease body.
|
||||
// WorkspaceLeaseStatus is the GET /status/workspace-lease body: the
|
||||
// journal-isolation counters. (The lease horizon's headroom, clamp and
|
||||
// extension-write counters are gone with the horizon: renewals write
|
||||
// nothing.)
|
||||
type WorkspaceLeaseStatus struct {
|
||||
ColocatedNodes int `json:"colocated_nodes"`
|
||||
HeadroomAlarms uint64 `json:"headroom_alarms"`
|
||||
ClampsTotal uint64 `json:"clamps_total"`
|
||||
ClampsLastMinute uint64 `json:"clamps_last_minute"`
|
||||
MinHeadroomMS int64 `json:"min_headroom_ms"` // -1: no grant observed yet
|
||||
StrictJournalIsolation bool `json:"strict_journal_isolation"`
|
||||
// Lease extension store write latency, the earliest lag signal.
|
||||
ExtensionWriteLastMS int64 `json:"extension_write_last_ms"` // -1: no extension write yet
|
||||
ExtensionWriteMaxLastMinuteMS int64 `json:"extension_write_max_last_minute_ms"` // -1: none in the last minute
|
||||
ColocatedNodes int `json:"colocated_nodes"`
|
||||
StrictJournalIsolation bool `json:"strict_journal_isolation"`
|
||||
}
|
||||
|
||||
// WorkspaceLeaseStatus returns the journal-isolation and lease headroom
|
||||
// counters served by the status endpoint.
|
||||
// WorkspaceLeaseStatus returns the journal-isolation counters served by the
|
||||
// status endpoint.
|
||||
func (h *Host) WorkspaceLeaseStatus() WorkspaceLeaseStatus {
|
||||
st := WorkspaceLeaseStatus{ColocatedNodes: h.journal.count(), MinHeadroomMS: -1, StrictJournalIsolation: h.cfg.StrictJournalIsolation,
|
||||
ExtensionWriteLastMS: -1, ExtensionWriteMaxLastMinuteMS: -1}
|
||||
if p := h.Publisher(); p != nil {
|
||||
s := p.WorkspaceLeaseStats()
|
||||
st.HeadroomAlarms, st.ClampsTotal, st.ClampsLastMinute = s.HeadroomAlarms, s.ClampsTotal, s.ClampsLastMinute
|
||||
if s.MinHeadroomObserved {
|
||||
st.MinHeadroomMS = s.MinHeadroom.Milliseconds()
|
||||
}
|
||||
if s.ExtensionWriteObserved {
|
||||
st.ExtensionWriteLastMS = s.ExtensionWriteLast.Milliseconds()
|
||||
}
|
||||
if s.ExtensionWriteInLastMinute {
|
||||
st.ExtensionWriteMaxLastMinuteMS = s.ExtensionWriteMaxLastMinute.Milliseconds()
|
||||
}
|
||||
}
|
||||
return st
|
||||
return WorkspaceLeaseStatus{ColocatedNodes: h.journal.count(), StrictJournalIsolation: h.cfg.StrictJournalIsolation}
|
||||
}
|
||||
|
||||
func (h *Host) statusHandler() http.Handler {
|
||||
|
||||
@@ -2,13 +2,11 @@ package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -301,51 +299,6 @@ func TestHostCloseForceClosesAStalledStatusConnection(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The status endpoint carries the extension write latency: -1 before any
|
||||
// extension, then the measured write once a renewal past 1.25 TTL of
|
||||
// headroom (7.5 s after the first grant, TTL 30 s) has started one.
|
||||
func TestStatusReportsExtensionWriteLatency(t *testing.T) {
|
||||
h, c, _ := reviewBindingHost(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
reviewLegacyBind(t, h, c, ctx, "vol-b")
|
||||
line := waitAuthorityLine(t, h.Publisher(), "vol-b")
|
||||
svc := &services{host: h}
|
||||
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
|
||||
if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err != nil {
|
||||
t.Fatal(err) // first grant: not an extension
|
||||
}
|
||||
get := func() map[string]any {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
h.statusHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/status/workspace-lease", nil))
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
if b := get(); b["extension_write_last_ms"] != float64(-1) || b["extension_write_max_last_minute_ms"] != float64(-1) {
|
||||
t.Fatalf("before any extension: %v", b)
|
||||
}
|
||||
time.Sleep(8 * time.Second)
|
||||
if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(20 * time.Millisecond) {
|
||||
b := get()
|
||||
last, _ := b["extension_write_last_ms"].(float64)
|
||||
max, _ := b["extension_write_max_last_minute_ms"].(float64)
|
||||
if last >= 0 && max >= last {
|
||||
t.Logf("extension write: last %v ms, max in the last minute %v ms", last, max)
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("no extension write reported: %v", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// With a known file system id on both sides, machine id + device alone no
|
||||
// longer make a node co-located: a different fsid is another file system.
|
||||
// The same three facts are co-located; a heartbeat without an fsid (an older
|
||||
|
||||
@@ -316,14 +316,18 @@ func TestStatusEndpointLoopbackOnlyAndServesJSON(t *testing.T) {
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, k := range []string{"colocated_nodes", "headroom_alarms", "clamps_total", "clamps_last_minute", "min_headroom_ms", "strict_journal_isolation",
|
||||
"extension_write_last_ms", "extension_write_max_last_minute_ms"} {
|
||||
for _, k := range []string{"colocated_nodes", "strict_journal_isolation"} {
|
||||
if _, ok := body[k]; !ok {
|
||||
t.Fatalf("status JSON lacks %q: %v", k, body)
|
||||
}
|
||||
}
|
||||
if body["strict_journal_isolation"] != true || body["colocated_nodes"] != float64(0) || body["min_headroom_ms"] != float64(-1) ||
|
||||
body["extension_write_last_ms"] != float64(-1) || body["extension_write_max_last_minute_ms"] != float64(-1) {
|
||||
// The lease horizon's counters are gone with the horizon.
|
||||
for _, k := range []string{"headroom_alarms", "clamps_total", "min_headroom_ms", "extension_write_last_ms"} {
|
||||
if _, ok := body[k]; ok {
|
||||
t.Fatalf("status JSON still serves %q: %v", k, body)
|
||||
}
|
||||
}
|
||||
if body["strict_journal_isolation"] != true || body["colocated_nodes"] != float64(0) {
|
||||
t.Fatalf("status JSON values: %v", body)
|
||||
}
|
||||
if post, err := http.Post("http://"+m.StatusAddr()+"/status/workspace-lease", "application/json", nil); err != nil || post.StatusCode != http.StatusMethodNotAllowed {
|
||||
|
||||
@@ -19,6 +19,19 @@ import (
|
||||
// write (temp file, fsync, rename, directory fsync).
|
||||
const storeAttestationFile = "store-attestations.json"
|
||||
|
||||
// storeAttestationFormat is the envelope this master writes:
|
||||
// {"format": 2, "volumes": {...}}. A v1.0.x master decodes the file as a
|
||||
// bare map of volume records, so the number under "format" fails its whole
|
||||
// start (before any listener or authority publication): the downgrade guard
|
||||
// for what this version stops keeping current (the lease horizon). The
|
||||
// bare map (v1.0.x's form) is still read.
|
||||
const storeAttestationFormat = 2
|
||||
|
||||
type storeAttestationEnvelope struct {
|
||||
Format int `json:"format"`
|
||||
Volumes map[string]attestedStores `json:"volumes"`
|
||||
}
|
||||
|
||||
// attestedStores is one volume's last attestation: the primary line that
|
||||
// made it and, per replica, the store that counted toward its write ACKs.
|
||||
type attestedStores struct {
|
||||
@@ -55,6 +68,9 @@ type storeAttestations struct {
|
||||
mu sync.Mutex
|
||||
path string // "" = memory only
|
||||
vols map[string]attestedStores
|
||||
// enveloped: the file on disk is this version's envelope (persist always
|
||||
// writes it; ensureEnvelope writes it at start).
|
||||
enveloped bool
|
||||
// changed[vol] is closed (and dropped) when vol's record changes.
|
||||
changed map[string]chan struct{}
|
||||
}
|
||||
@@ -72,15 +88,102 @@ func loadStoreAttestations(dir string) (*storeAttestations, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store attestations: %w", err)
|
||||
}
|
||||
if err := json.Unmarshal(b, &s.vols); err != nil {
|
||||
vols, enveloped, err := decodeStoreAttestations(b)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store attestations %s: %w", s.path, err)
|
||||
}
|
||||
if s.vols == nil {
|
||||
s.vols = map[string]attestedStores{}
|
||||
}
|
||||
s.vols, s.enveloped = vols, enveloped
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// decodeStoreAttestations reads either form: the envelope (a number under
|
||||
// "format": this master reads format 2 only) or v1.0.x's bare map.
|
||||
func decodeStoreAttestations(b []byte) (map[string]attestedStores, bool, error) {
|
||||
var probe map[string]json.RawMessage
|
||||
if err := json.Unmarshal(b, &probe); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if raw, ok := probe["format"]; ok {
|
||||
var format int
|
||||
if json.Unmarshal(raw, &format) == nil {
|
||||
if format != storeAttestationFormat {
|
||||
return nil, false, fmt.Errorf("format %d, this master reads format %d", format, storeAttestationFormat)
|
||||
}
|
||||
var env storeAttestationEnvelope
|
||||
if err := json.Unmarshal(b, &env); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
// The volumes are an explicit object ({} when there are none):
|
||||
// whatever left the decoded map nil (missing, null, a later key of
|
||||
// another case) is refused, never read as no attestations.
|
||||
if env.Volumes == nil {
|
||||
return nil, false, fmt.Errorf("format %d without a volumes object", format)
|
||||
}
|
||||
return env.Volumes, true, nil
|
||||
}
|
||||
}
|
||||
var vols map[string]attestedStores
|
||||
if err := json.Unmarshal(b, &vols); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if vols == nil {
|
||||
// v1.0.x read a null file as no attestations; so does this master,
|
||||
// and the envelope it migrates to says {} explicitly.
|
||||
vols = map[string]attestedStores{}
|
||||
}
|
||||
return vols, false, nil
|
||||
}
|
||||
|
||||
// ensureEnvelope makes the file in this version's envelope durable before
|
||||
// the master serves anything, so a v1.0.x master started on this store
|
||||
// afterwards refuses its whole start: it writes the envelope when the file is
|
||||
// absent or in v1.0.x's form, and fsyncs an envelope already there (file and
|
||||
// directory) on every start, since an earlier start may have renamed it in
|
||||
// and then failed its directory fsync.
|
||||
func (s *storeAttestations) ensureEnvelope() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.path == "" {
|
||||
return nil
|
||||
}
|
||||
if !s.enveloped {
|
||||
if err := s.persist(s.vols); err != nil {
|
||||
return err
|
||||
}
|
||||
s.enveloped = true
|
||||
return nil
|
||||
}
|
||||
f, err := os.OpenFile(s.path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("store attestations: %w", err)
|
||||
}
|
||||
serr := f.Sync()
|
||||
if cerr := f.Close(); serr == nil {
|
||||
serr = cerr
|
||||
}
|
||||
if serr != nil {
|
||||
return fmt.Errorf("store attestations: fsync: %w", serr)
|
||||
}
|
||||
return syncAttestationDir(filepath.Dir(s.path))
|
||||
}
|
||||
|
||||
// syncAttestationDir fsyncs the attestation file's directory (the commit of
|
||||
// its rename). A variable so a test can fail it.
|
||||
var syncAttestationDir = func(dir string) error {
|
||||
if runtime.GOOS == "windows" {
|
||||
return nil // a directory cannot be fsynced there; the rename is the commit
|
||||
}
|
||||
d, err := os.Open(dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("store attestations: directory: %w", err)
|
||||
}
|
||||
defer d.Close()
|
||||
if err := d.Sync(); err != nil {
|
||||
return fmt.Errorf("store attestations: directory fsync: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lookup returns the store a primary of the volume last attested for
|
||||
// replica; false when none ever did. A replica dropped from the write-ACK
|
||||
// set since keeps it.
|
||||
@@ -334,7 +437,7 @@ func (s *storeAttestations) persist(vols map[string]attestedStores) error {
|
||||
if s.path == "" {
|
||||
return nil
|
||||
}
|
||||
payload, err := json.Marshal(vols)
|
||||
payload, err := json.Marshal(storeAttestationEnvelope{Format: storeAttestationFormat, Volumes: vols})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -357,18 +460,7 @@ func (s *storeAttestations) persist(vols map[string]attestedStores) error {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("store attestations: %w", werr)
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
return nil // a directory cannot be fsynced there; the rename is the commit
|
||||
}
|
||||
d, err := os.Open(filepath.Dir(s.path))
|
||||
if err != nil {
|
||||
return fmt.Errorf("store attestations: directory: %w", err)
|
||||
}
|
||||
defer d.Close()
|
||||
if err := d.Sync(); err != nil {
|
||||
return fmt.Errorf("store attestations: directory fsync: %w", err)
|
||||
}
|
||||
return nil
|
||||
return syncAttestationDir(filepath.Dir(s.path))
|
||||
}
|
||||
|
||||
// ingestStoreAttestation records a heartbeat's attestation when the
|
||||
|
||||
@@ -32,9 +32,10 @@ func (s *stalledGuardStore) Put(r authority.DurableRecord) error {
|
||||
}
|
||||
|
||||
// Control 1 (host side): with the master's store stalled for good, a real
|
||||
// guard keeps serving on clamped grants and fences by the durable horizon
|
||||
// minus half the skew bound, not earlier and not later than the horizon.
|
||||
func TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore(t *testing.T) {
|
||||
// guard keeps serving: a renewal writes nothing, so a stalled store cannot
|
||||
// make a grant short or late. The guard stays healthy for more than two TTLs
|
||||
// and no lease write reaches the stalled store.
|
||||
func TestWorkspaceLeaseGuardServesThroughAStalledStore(t *testing.T) {
|
||||
disk, err := authority.NewFileAuthorityStore(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -50,7 +51,6 @@ func TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore(t *testing.T) {
|
||||
dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)}
|
||||
p := authority.NewPublisher(dir, authority.WithStore(stall), authority.WithWorkspaceLeaseConfig(3*time.Second, nil))
|
||||
seedSkewPublisher(t, p, dir)
|
||||
t.Cleanup(p.CloseWorkspaceExtenders)
|
||||
var releaseOnce sync.Once
|
||||
t.Cleanup(func() { releaseOnce.Do(func() { close(stall.release) }) }) // runs first: unblock the extender
|
||||
var stops atomic.Int32
|
||||
@@ -76,30 +76,18 @@ func TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore(t *testing.T) {
|
||||
t.Fatal("first grant did not arrive")
|
||||
}
|
||||
}
|
||||
lease := p.WorkspaceState("v").Lease
|
||||
horizon := time.Unix(0, lease.ExpiresAtNS)
|
||||
halfSkew := time.Duration(lease.MaxClockSkewNS) / 2
|
||||
stall.armed.Store(true)
|
||||
var fencedAt time.Time
|
||||
for deadline := horizon.Add(2 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
|
||||
for end := time.Now().Add(2*3*time.Second + time.Second); time.Now().Before(end); time.Sleep(50 * time.Millisecond) {
|
||||
if !g.Projection().Healthy {
|
||||
fencedAt = time.Now()
|
||||
break
|
||||
t.Fatal("the guard fenced while the master's store was stalled: a renewal waited on the store")
|
||||
}
|
||||
}
|
||||
if fencedAt.IsZero() {
|
||||
t.Fatalf("guard still serving 2 s past the durable horizon %s", horizon.Format(time.RFC3339Nano))
|
||||
if n := stall.puts.Load(); n != 0 {
|
||||
t.Fatalf("%d lease writes reached the stalled store during renewals, want 0", n)
|
||||
}
|
||||
if fencedAt.After(horizon.Add(300 * time.Millisecond)) {
|
||||
t.Fatalf("guard fenced %s after the durable horizon", fencedAt.Sub(horizon))
|
||||
if stops.Load() != 0 {
|
||||
t.Fatalf("the guard stopped the volume %d times", stops.Load())
|
||||
}
|
||||
if early := horizon.Add(-halfSkew - 500*time.Millisecond); fencedAt.Before(early) {
|
||||
t.Fatalf("guard fenced %s before horizon - skew/2: grants did not clamp to the horizon", early.Sub(fencedAt))
|
||||
}
|
||||
if stall.puts.Load() == 0 {
|
||||
t.Fatal("no extender write reached the stalled store")
|
||||
}
|
||||
t.Logf("guard fenced %s before the durable horizon (half skew %s)", horizon.Sub(fencedAt).Round(time.Millisecond), halfSkew)
|
||||
}
|
||||
|
||||
// Control 6a and the reply clamp: through the services layer, QueryWorkspace
|
||||
|
||||
@@ -86,15 +86,15 @@ func TestLeaseRefusalKinds(t *testing.T) {
|
||||
t.Fatal("first grant:", err)
|
||||
}
|
||||
|
||||
// BARRIER: past the grant (TTL) but before the horizon (1.5 TTL) plus
|
||||
// the default skew (2/3 TTL), i.e. 65 s after the grant.
|
||||
// BARRIER: past the grant (TTL, 30 s) but before it plus the default
|
||||
// skew (2/3 TTL), i.e. 50 s after the grant.
|
||||
nowNS.Add(int64(40 * time.Second))
|
||||
text, r := refusalOf(t, "expired re-grant before the barrier", func() error { _, err := ws.RenewWorkspaceLease(ctx, e1); return err }())
|
||||
if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_BARRIER {
|
||||
t.Fatalf("re-grant before the barrier: detail %v; want BARRIER", r)
|
||||
}
|
||||
if left := time.Duration(r.GetRetryAfterNs()); left < 24*time.Second || left > 26*time.Second {
|
||||
t.Fatalf("BARRIER retry_after %v; want 25 s (the barrier 65 s after the grant, now +40 s)", left)
|
||||
if left := time.Duration(r.GetRetryAfterNs()); left < 9*time.Second || left > 11*time.Second {
|
||||
t.Fatalf("BARRIER retry_after %v; want 10 s (the barrier 50 s after the grant, now +40 s)", left)
|
||||
}
|
||||
if !strings.HasPrefix(text, "workspace forced move lease expiry plus clock-skew margin has not elapsed") || !strings.Contains(text, "re-grant refused until") {
|
||||
t.Fatalf("BARRIER text %q: want the barrier text with its time", text)
|
||||
|
||||
@@ -85,7 +85,12 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldBarrier := time.Unix(0, p.WorkspaceState("v").Lease.ExpiresAtNS)
|
||||
// The predecessor's deadline (this process's grant, not the record's).
|
||||
oldLease, ok := p.WorkspaceLeaseReply("v")
|
||||
if !ok {
|
||||
t.Fatal("no predecessor lease")
|
||||
}
|
||||
oldBarrier := time.Unix(0, oldLease.ExpiresAtNS)
|
||||
|
||||
fixture := testutil.NewLayoutFixture(t, "v", 64, 4)
|
||||
readHead := func() authority.WorkspaceHead {
|
||||
@@ -176,7 +181,8 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) {
|
||||
t.Fatalf("grantee lease %+v", lease)
|
||||
}
|
||||
skew := time.Duration(lease.MaxClockSkewNS)
|
||||
grantBarrier := time.Unix(0, lease.ExpiresAtNS).Add(skew)
|
||||
granted, _ := p.WorkspaceLeaseReply("v") // the grantee's deadline after its renewal
|
||||
grantBarrier := time.Unix(0, granted.ExpiresAtNS).Add(skew)
|
||||
forced := authority.WorkspaceMoveRequest{RequestID: "forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2,
|
||||
TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true}
|
||||
|
||||
|
||||
@@ -101,13 +101,13 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) {
|
||||
case <-ctx.Done():
|
||||
t.Fatal("renewal did not enter", ctx.Err())
|
||||
}
|
||||
// A renewal is answered from memory: the grant is in the reply, and
|
||||
// the durable lease holds the horizon (>= every grant), so the
|
||||
// persisted expiry is not the grant any more (#205).
|
||||
// A renewal is answered from memory: the grant is in the reply and
|
||||
// nothing is written, so the persisted lease is still the first
|
||||
// grant's record.
|
||||
renewed := *p.WorkspaceState("v").Lease
|
||||
freshEarly := requestStart.Add(time.Duration(reply.ValidForNs))
|
||||
if freshEarly.Sub(oldEarly) < time.Second || reply.ExpiresAtNs <= client.initial.ExpiresAtNs || renewed.ExpiresAtNS < reply.ExpiresAtNs || renewed.MaxClockSkewNS != int64(4*time.Second) {
|
||||
t.Fatal("fixture did not extend the grant under the durable horizon", client.initial, reply, oldLease, renewed)
|
||||
t.Fatal("fixture did not extend the grant", client.initial, reply, oldLease, renewed)
|
||||
}
|
||||
arrival := oldEarly.Add(-time.Second)
|
||||
if late {
|
||||
@@ -140,14 +140,10 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) {
|
||||
}
|
||||
q := authority.WorkspaceMoveRequest{RequestID: "renewed-forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
head := authority.WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42}
|
||||
// The barrier is max(durable horizon, renewed grant) + skew; the old
|
||||
// The barrier is the renewed grant + the persisted skew; the old
|
||||
// grant's expiry plus skew is still too early.
|
||||
barrierBase := renewed.ExpiresAtNS
|
||||
if reply.ExpiresAtNs > barrierBase {
|
||||
barrierBase = reply.ExpiresAtNs
|
||||
}
|
||||
boundary := time.Unix(0, barrierBase).Add(time.Duration(renewed.MaxClockSkewNS))
|
||||
for _, when := range []time.Time{time.Unix(0, client.initial.ExpiresAtNs).Add(4 * time.Second), time.Unix(0, reply.ExpiresAtNs).Add(4 * time.Second), boundary.Add(-time.Nanosecond)} {
|
||||
boundary := time.Unix(0, reply.ExpiresAtNs).Add(time.Duration(renewed.MaxClockSkewNS))
|
||||
for _, when := range []time.Time{time.Unix(0, client.initial.ExpiresAtNs).Add(4 * time.Second), boundary.Add(-time.Nanosecond)} {
|
||||
masterNS.Store(when.UnixNano())
|
||||
if _, err := p.MoveWorkspace(ctx, q, head); err == nil {
|
||||
t.Fatal("forced move ignored renewed expiry plus persisted margin")
|
||||
|
||||
@@ -149,8 +149,7 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
|
||||
})
|
||||
dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)}
|
||||
p := authority.NewPublisher(dir, authority.WithStore(slow), authority.WithWorkspaceLeaseConfig(6*time.Second, nil))
|
||||
t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes
|
||||
t.Cleanup(slow.release) // runs before the join above: frees a held Put first
|
||||
t.Cleanup(slow.release) // runs before the join above: frees a held Put first
|
||||
seedSkewPublisher(t, p, dir)
|
||||
var stops atomic.Int32
|
||||
g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}},
|
||||
@@ -173,7 +172,8 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
|
||||
|
||||
// Every lease write is now held until a renewal succeeded during its hold,
|
||||
// so a renewal that waited for the store would deadlock this test. The
|
||||
// sampler records any fence while armed; three held writes must complete.
|
||||
// sampler records any fence while armed; four renewals must succeed (about
|
||||
// 5 s), and none of them may write the lease (a renewal writes nothing).
|
||||
var fenced atomic.Bool
|
||||
var sinceOKAtFence atomic.Int64 // time since the latest successful renewal when the fence was first seen
|
||||
sampled := make(chan struct{})
|
||||
@@ -189,14 +189,20 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}()
|
||||
for slow.held.Load() < 3 {
|
||||
if fenced.Load() {
|
||||
base := slow.renewals.Load()
|
||||
for wait := time.Now().Add(30 * time.Second); slow.renewals.Load() < base+4 && !fenced.Load(); time.Sleep(20 * time.Millisecond) {
|
||||
if time.Now().After(wait) {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
slow.armed.Store(false)
|
||||
<-sampled
|
||||
if n := slow.renewals.Load() - base; n < 4 && !fenced.Load() {
|
||||
t.Fatalf("only %d renewals succeeded in 30 s while armed", n)
|
||||
}
|
||||
if n := slow.gen.Load(); n != 0 {
|
||||
t.Fatalf("renewals wrote the lease %d times while armed; a renewal writes nothing", n)
|
||||
}
|
||||
if fenced.Load() || !g.Projection().Healthy || stops.Load() != 0 {
|
||||
// The gaps tell a starved runner (a gap near the 4 s validity) from a
|
||||
// guard that fenced although renewals kept succeeding in time.
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestWorkspaceSkewSeparatesOldServingFromForcedGrant(t *testing.T) {
|
||||
if err := g.Refresh(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease := p.WorkspaceState("v").Lease
|
||||
lease, _ := p.WorkspaceLeaseReply("v") // this process's deadline for the grant
|
||||
q := authority.WorkspaceMoveRequest{RequestID: "forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
|
||||
head := authority.WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42}
|
||||
if check == "host-early-fence" {
|
||||
|
||||
@@ -35,7 +35,7 @@ func seedDetachedHead(t *testing.T, ctx context.Context, remote *storage.MemChun
|
||||
// then) and is granted on the predecessor's unchanged HEAD. A late claim by
|
||||
// the dead grantee never displaces the new owner's higher epoch.
|
||||
func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
|
||||
// The real lease horizon (1.5 x the 30 s TTL) plus skew takes ~45 s.
|
||||
// The real lease (the 30 s TTL) plus skew takes ~50 s.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
@@ -114,7 +114,8 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
|
||||
if st == nil || st.Lease == nil || st.Lease.ReplicaID != "r1" || st.Lease.Epoch != grantee || st.Lease.Revoking {
|
||||
t.Fatalf("the issued move must start node-b's lease: %+v", st)
|
||||
}
|
||||
barrier := time.Unix(0, st.Lease.ExpiresAtNS).Add(skew)
|
||||
granted, _ := m.Publisher().WorkspaceLeaseReply("vol-a") // the issue's deadline, not the record's
|
||||
barrier := time.Unix(0, granted.ExpiresAtNS).Add(skew)
|
||||
if q, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-a"}); err != nil || q.GetLease() == nil || q.GetLease().GetEpoch() != grantee {
|
||||
t.Fatalf("QueryWorkspace after the issue: %+v %v", q.GetLease(), err)
|
||||
}
|
||||
|
||||
@@ -313,7 +313,7 @@ intents remain rooted after restart; elapsed TTL is not a settlement proof.
|
||||
|
||||
**Host guard** (`core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard`, enabled with `blockvolume --workspace-lease`; see [workspace lease](../workspace-lease.md)): frontend I/O and cuts are admitted only with a granted, unexpired lease for the exact `{volume, replica, epoch}`. Validity is anchored to the renewal request's start time, and blockmaster's `ValidForNs` already subtracts half the clock-skew bound (`core/host/master/workspace_service.go` `leaseFact`). A late reply cannot extend admission. A fenced guard never reopens. The lease is 30 s (`core/authority/authority.go`, `workspaceTTL`); the skew bound defaults to 20 s (`blockmaster --workspace-max-clock-skew`).
|
||||
|
||||
**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).
|
||||
**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 now + TTL, and nothing is written: a restarted blockmaster does not need a stored expiry, because it grants a different holder only after its restart floor (its own start + TTL + the skew bound, on its own clock), by which time every grant an earlier process made has ended. Only the first grant of a lease (and an expired re-grant, a move issue) is written synchronously. A volume whose authority write failed is uncertain and refuses renewals that would issue a new 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.
|
||||
|
||||
@@ -328,9 +328,9 @@ flowchart LR
|
||||
|
||||
**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.
|
||||
**FORCED move:** blockmaster waits until the granted deadline (the latest grant it made) or, after a restart, its restart floor, plus the full skew bound, has passed; it reads no lease value an earlier process wrote (`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.
|
||||
|
||||
**Move issue starts the new holder's lease.** The write that issues epoch e+1 also writes the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view update; the holder's first renewal is an ordinary renewal of it (`core/authority/workspace.go` `issueWorkspaceMove`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`). A new holder that dies before it renews or claims HEAD therefore expires like any holder, and a forced move away from it waits for that lease's expiry and deadline plus the skew bound, never a predecessor's. Blockmaster reads HEAD for a forced move only after that admission holds (`core/host/master/workspace_service.go` `MoveWorkspace`): the holder then starts no new claim or cut, but a claim it already sent may still land, so HEAD is not frozen. A forced move accepts a HEAD that names the expected holder at the expected epoch, or any HEAD at an older epoch (the expected holder never claimed it, or an earlier holder's late claim landed); its lost range starts at that HEAD's `RemoteLSN`. A HEAD at the expected or a higher epoch that is not the expected holder's is refused. A returning holder is stopped by two fences: its lease-gated attach refuses to claim (its lease has expired), and a HEAD that already carries a higher epoch fences its claim.
|
||||
**Move issue starts the new holder's lease.** The write that issues epoch e+1 also writes the new holder's lease (granted deadline issue + TTL), published with the epoch in one lease-view update; the holder's first renewal is an ordinary renewal of it (`core/authority/workspace.go` `issueWorkspaceMove`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`). A new holder that dies before it renews or claims HEAD therefore expires like any holder, and a forced move away from it waits for that lease's deadline plus the skew bound, never a predecessor's. Blockmaster reads HEAD for a forced move only after that admission holds (`core/host/master/workspace_service.go` `MoveWorkspace`): the holder then starts no new claim or cut, but a claim it already sent may still land, so HEAD is not frozen. A forced move accepts a HEAD that names the expected holder at the expected epoch, or any HEAD at an older epoch (the expected holder never claimed it, or an earlier holder's late claim landed); its lost range starts at that HEAD's `RemoteLSN`. A HEAD at the expected or a higher epoch that is not the expected holder's is refused. A returning holder is stopped by two fences: its lease-gated attach refuses to claim (its lease has expired), and a HEAD that already carries a higher epoch fences its claim.
|
||||
|
||||
**Takeover** (`core/storage/chunk_restore.go` `ClaimChunkHead`, called before the chunk layer attaches in `core/frontend/durable/provider_chunk.go`): read HEAD; fence if HEAD has a higher epoch or another holder at the same epoch; seed the local LSN frontier from HEAD (`PrepareRestore`); CAS HEAD to the new epoch and holder with `State = active`; on an unknown outcome, succeed only if a re-read shows the exact proposal. I/O opens afterwards; blocks load lazily on first read.
|
||||
|
||||
@@ -353,7 +353,7 @@ sequenceDiagram
|
||||
A->>A: self-fence when ValidForNs runs out
|
||||
M->>M: wait for expiry, restart deadline and skew bound, then mint epoch e+1
|
||||
end
|
||||
M->>M: the issue write also starts B's lease (horizon issue+1.5·TTL, deadline issue+TTL)
|
||||
M->>M: the issue write also starts B's lease (deadline issue+TTL)
|
||||
Note over M,B: target B may be source A; the same clean proof or forced barrier applies
|
||||
M->>B: assignment at epoch e+1 and a lease
|
||||
opt B dies before renewing or claiming (HEAD still at epoch e)
|
||||
@@ -381,17 +381,17 @@ stateDiagram-v2
|
||||
state "Lease (blockmaster)" as L {
|
||||
[*] --> Granted: first Renew after bind (registered server id, from its registered host)
|
||||
[*] --> Granted: move issue starts the new holder's lease
|
||||
Granted --> Granted: Renew before horizon and deadline (from memory; registered server id, from its registered host)
|
||||
Granted --> Granted: Renew before the deadline (from memory, no write; registered server id, from its registered host)
|
||||
Granted --> Revoking: BeginWorkspaceRevocation
|
||||
Revoking --> Acked: registered host acks detached HEAD gen; publisher-clock validity after half max(configured, persisted) skew is positive
|
||||
Acked --> Moved: CLEAN move, including same host, new epoch
|
||||
Granted --> Expired: horizon or deadline passes
|
||||
Granted --> Expired: the deadline passes
|
||||
Expired --> Granted: unchanged holder from its registered host, no move/revocation, MAX expiry + skew passed; durable re-grant
|
||||
Expired --> Moved: FORCED move after expiry + skew bound, then HEAD read (an older-epoch HEAD is accepted)
|
||||
Granted --> DeleteReserved: lifecycle deletion committed, then exclusion published under publisher mu -> leaseMu
|
||||
Expired --> DeleteReserved: same permanent reservation
|
||||
DeleteReserved --> DeleteReserved: every grant/renewal/extension refuses; restart rebuilds exclusion before serving
|
||||
DeleteReserved --> NoLiveLease: durable horizon and granted/restart deadline plus skew have both passed
|
||||
DeleteReserved --> NoLiveLease: the granted or restart deadline plus skew has passed
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -144,8 +144,8 @@ flowchart LR
|
||||
| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` |
|
||||
| Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` |
|
||||
| Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` |
|
||||
| any authority line | DeleteReserved (permanent) | the existing lifecycle reservation is committed durably; then `mu -> leaseMu` publishes the exclusion. Publication, move issue, first grant, expired re-grant, renewal and background horizon extension check it under their writer lock. Restart reloads every committed exclusion before serving. Deleting HEAD requires the persisted lease horizon and restart deadline plus skew to have ended, including unclaimed grants; the check returns a refusal rather than waiting | `core/authority/workspace_delete_reservation.go` `ReserveWorkspaceDeletion`, `NoLiveWorkspaceLease`; `core/host/master/volume_delete_authority.go`; `host.go` `New` | `INV-SNAPK-DELETE-GATE-001` |
|
||||
| any authority line, stores still awaited (stage 1) | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends the store wait; the mark freezes the record in stage 1 (the wait never ends after it, so the primary, whose assignment keeps awaiting the stores, never serves); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease horizon as above. Past stage 1, also while the end of creation is unrecorded (the volume may be serving), the live-lease refusal stays | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` |
|
||||
| any authority line | DeleteReserved (permanent) | the existing lifecycle reservation is committed durably; then `mu -> leaseMu` publishes the exclusion. Publication, move issue, first grant, expired re-grant and renewal check it under their writer lock. Restart reloads every committed exclusion before serving. Deleting HEAD requires the granted or restart deadline plus skew to have ended, including unclaimed grants; the check returns a refusal rather than waiting | `core/authority/workspace_delete_reservation.go` `ReserveWorkspaceDeletion`, `NoLiveWorkspaceLease`; `core/host/master/volume_delete_authority.go`; `host.go` `New` | `INV-SNAPK-DELETE-GATE-001` |
|
||||
| any authority line, stores still awaited (stage 1) | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends the store wait; the mark freezes the record in stage 1 (the wait never ends after it, so the primary, whose assignment keeps awaiting the stores, never serves); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease as above. Past stage 1, also while the end of creation is unrecorded (the volume may be serving), the live-lease refusal stays | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` |
|
||||
|
||||
**Volume creation phase, in blockmaster's store record** (`core/host/master/store_attestation.go`, decided by `inCreationPhase` in `core/host/master/product_loop.go`). Every replacement entry (both promotion gates, the operator's failover and planned move, the rebalance) acts only on Established.
|
||||
|
||||
@@ -230,10 +230,10 @@ a pre-issued publication.
|
||||
| Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), an authoritative detached HEAD matching the ACK epoch/holder/position, for a first ACK, positive granted validity after half the configured/persisted skew on the publisher clock; a matching recorded stop answers before any lease check without writing, while a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
|
||||
| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation; the target may be the same host, with a newly issued epoch and every binding/collision/isolation check retained | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `validateWorkspaceMoveRequest`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-SAME-HOST-CLEAN-MOVE-001` |
|
||||
| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (including the source host; clean proof or forced-move lease barrier still required), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` |
|
||||
| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` |
|
||||
| Granted or Revoking | Expired | the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` |
|
||||
| Expired | Granted | Same current primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` |
|
||||
| Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait (`INV-WS-MASTER-WAIT-001`: 30 s of answered contact past the master's barrier time; no bound while the master gives no reply) or lease fence exits 75 after bounded cleanup; a typed master FINAL refusal for a recorded revocation exits 79, while MOVED or DELETED exits 78 at once (an issued moved source may be refused on subscription before any own assignment); a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` |
|
||||
| Expired | Moved (forced) | target may be the source host; explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced <volume>@<expected epoch>`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-SAME-HOST-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` |
|
||||
| Expired | Moved (forced) | target may be the source host; explicit force; the granted or restart deadline plus the clock-skew bound has passed (this process's own deadline: the latest grant it made, or after a restart the restart floor; no wall value an earlier process wrote is read), for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced <volume>@<expected epoch>`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-SAME-HOST-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` |
|
||||
| none, Granted, Revoking or Expired | Deleting | the chunk volume delete is admitted with `WorkspaceHolderState` = never started or deleting (`TERM-LIVE-HOLDER-001`): HEAD, read by blockmaster before its locks, is below the line's epoch, or already past the fence (deleting, purging, deleted: the rerun of a delete that stopped midway); no move pending. From then on renewals, grants, re-grants, revocations and moves of the volume are refused; the delete's HEAD compare-and-swap to deleting is its linearization point: a claim applied before it makes the delete refuse `volume_in_use` and give the reservation back, a claim after it fails. The lifecycle `DeleteVolume` reads no HEAD and keeps the ACK rule | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence`; `core/frontend/chunkstore/volume_delete.go` (HEAD to deleting) | `INV-WS-DELETE-NO-LIVE-HOLDER-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` |
|
||||
| Moved | epoch issued | the moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` |
|
||||
|
||||
@@ -807,12 +807,14 @@ Notes:
|
||||
| `INV-AUTH-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`, `refreshAsk` (conditional on the line it read); `core/host/master/product_loop.go` `RunLifecycleProductTick`, `restartedHolderRefresh` (the product loop's direct path for a workspace-bound RF1 volume, conditional on the line it read); `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestRF1RuntimeVolumeIsReissuedToARestartedHolder`, `TestRF1RuntimeLineNamingNoProcessIsReissued`, `TestRF1RefreshDecidedBeforeACrossHostMoveIsNotApplied` (`core/host/master/rf1_restart_reissue_test.go`); `TestRefreshIsConditionalOnTheLineItWasDecidedAgainst`, `TestControllerRefreshNamesTheLineItWasDecidedAgainst` (`core/authority/refresh_expected_line_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | ACTIVE |
|
||||
| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, a failed write does not publish it, and an unknown outcome (directory fsync after the rename failed) fail-stops blockmaster: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (`failStopDurabilityUnknown` after a failed directory open or fsync behind the rename, every record; a close error after a good fsync is reported written; Windows keeps its previous behaviour) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename`, `TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE |
|
||||
| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE |
|
||||
| `INV-AUTH-UNCERTAIN-001` | A failed authority write for a workspace volume, a lease extension included, latches uncertainty until a restart reloads the store: later authority changes and new or extended grants for that volume are refused. See M2 any (workspace) → Uncertain and Uncertain → Uncertain (move answer). | M2 any (workspace) → Uncertain; Uncertain → Uncertain (move answer) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal` (`core/authority/workspace_outcome_uncertain_test.go`), `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (`core/host/master/workspace_uncertain_precedence_test.go`), `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`) | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped`, `UncertainReplyClass` | ACTIVE |
|
||||
| `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). | M2 every workspace transition | `core/authority/workspace_lease_view.go` `deriveLeaseLocked`, `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`, `setLeaseDeadlineLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE |
|
||||
| `INV-AUTH-UNCERTAIN-001` | A failed authority write for a workspace volume latches uncertainty until a restart reloads the store: later authority changes and new or extended grants for that volume are refused. See M2 any (workspace) → Uncertain and Uncertain → Uncertain (move answer). | M2 any (workspace) → Uncertain; Uncertain → Uncertain (move answer) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `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). | M2 every workspace transition | `core/authority/workspace_lease_view.go` `deriveLeaseLocked`, `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`, `setLeaseDeadlineLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE |
|
||||
| `INV-LEASE-VIEW-OWNED-001` | The granted deadline and the extender flag exist only in the lease view; refreshing the view from its derive inputs never changes either of them. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `setLeaseDeadlineLocked`, `extendWorkspaceLease` | — | — | STUB |
|
||||
| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch, the `Lease.ExpiresAtNS` persisted in the authority store is at least the published horizon, and the published horizon is at least every grant issued since the last reload. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant`, `newWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked`, `issueWorkspaceMove` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-LEASE-HORIZON-MONO-001` | Within one lease the published horizon never decreases: an extension writes a new horizon only when it is greater than the current one. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-LEASE-HORIZON-001` | Retired: v1.1 keeps no lease horizon current; renewals write nothing and a restarted master waits for its own restart floor (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED |
|
||||
| `INV-WS-LEASE-HORIZON-MONO-001` | Retired with the lease horizon (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED |
|
||||
| `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-RESTART-GRACE-001` | A renewal writes nothing durable. A forced move, an expired re-grant and a delete's no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL, own monotonic clock); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE |
|
||||
| `INV-WS-AUTH-RECORD-V2-001` | Before it serves, this master writes the store's attestation file as format 2, on which a v1.0.x master refuses its whole start; its authority records are envelope version 2 (a v1.0.x master would skip them). It reads both forms of each. | M2 every workspace write; master start | `core/host/master/store_attestation.go` `ensureEnvelope`, `decodeStoreAttestations`; `core/host/master/host.go` `New`; `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestAV100MasterRefusesTheAttestationEnvelope`, `TestAttestationsWriteTheV100FileInTheEnvelope`, `TestAttestationsReadTheV100File` (`core/host/master/golden_v100_test.go`); `TestARecordWrittenNowFailsTheV100Decoder` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE |
|
||||
| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
|
||||
| `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE |
|
||||
| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE |
|
||||
@@ -904,8 +906,8 @@ Notes:
|
||||
| `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A same-host move issues a higher epoch: a clean move needs the current holder's sealed HEAD and its recorded epoch/holder/position ACK, and the successor reads that sealed image; a forced move needs the normal lease barrier and a durable lost-range record. | M2 Acked or Expired → Moved; M9 detached → higher-epoch idle | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim` | `TestWorkspaceSameHostForcedMoveRecordsLostRange` (`core/authority/workspace_same_host_forced_test.go`); `TestWorkspaceRPCSameHostForcedRecoveryRecordsLoss` (`core/host/master/workspace_same_host_forced_test.go`); `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestLayoutSameHostCleanSuccessorReadsSealedImage` (`core/frontend/durable/provider_layout_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed`; `INV-SNAPK-DETACHED-001`. The B provider test performs a real plain detach, same-host higher-epoch fresh-root Start, and reads the sealed bytes. | ACTIVE |
|
||||
| `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Revoking/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestDeleteAdmissionVerdicts` (`core/authority/workspace_delete_admission_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r2 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost`, re-run can finish, re-run can settle (exhaustive, 21 of 21 configurations as expected). Not modelled: two delete processes at the same instant; the gap between HEAD deleted and the volume marked deleted. Limit (v1): a never-started line that holds a lease is deleted once its lease horizon passed (about 60 s; the reservation refuses a live lease before it); the immediate exit is 1.0.1 | ACTIVE |
|
||||
| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a revocation ACK matching its epoch, holder and published position; generation is readout only. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation`; `core/host/master/workspace_layout_head.go` `NewLayoutWorkspaceHEADReader` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`); `TestWorkspaceLayoutHEADUsesTheMasterIdentity`, `TestWorkspaceLayoutHEADRefusalsAndStates`, `TestWorkspaceLayoutHEADReaderWiring`; also in `core/host/master/workspace_layout_head_test.go`, `cmd/blockmaster/workspace_layout_head_test.go` | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
|
||||
| `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`); `TestProcedureMasterUnreachableFencesBeforeForcedMove` (`cmd/blockvolume/master_loss_integration_test.go`, tags `subprocess chunkstore_integration`) | — | ACTIVE |
|
||||
| `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the granted or restart deadline plus the clock-skew bound has passed for the lease the last move issue started (never a predecessor's; `INV-WS-RESTART-GRACE-001`): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`); `TestProcedureMasterUnreachableFencesBeforeForcedMove` (`cmd/blockvolume/master_loss_integration_test.go`, tags `subprocess chunkstore_integration`) | — | ACTIVE |
|
||||
| `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry (the deadline), never a persisted value. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-FORCED-MOVE-HALF-SKEW-001` | The validity the master gives a host with a lease ends half the clock-skew bound before the reported lease expiry. | M2 Granted → Granted (reply); M4 NoLease, Valid → Valid | `core/authority/workspace_lease_view.go` `WorkspaceLeaseValidity`, `workspaceLeaseValidityAt`; `core/host/master/workspace_service.go` `leaseFact`; `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/volume/workspace_lease.go` `Refresh` | `TestWorkspaceLeaseFactUsesPublisherClockAndSkew` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceAckUsesGrantedHalfSkewBoundary` (`core/authority/workspace_validity_test.go`); `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-LOST-RANGE-READOUT-001` | Every issued forced grant the master returns, also on a replay and after a restart, carries the lost range stored in the authority store before the issue, never a recomputed one: see M2 Moved → epoch issued. | M2 lease: Expired → Moved (forced); Moved → epoch issued | `core/authority/workspace_lost_range.go` `recordLostRangeLocked`, `WorkspaceLostRangeReadouts`, `encodeLostRangeEnvelope`; `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/host/master/workspace_layout_head.go` `NewLayoutWorkspaceHEADReader`; `core/host/master/workspace_service.go` `grantWithLostRange`, `issuedRecord`; `core/rpc/wsclient/wsclient.go` `Readout` | `TestWorkspaceForcedMoveRecordsTheLostRange`, `TestWorkspaceForcedMoveLostRangeOrdering`, `TestWorkspaceForcedReservationResumeNeedsItsRange` (`core/authority/workspace_lost_range_test.go`); `TestWorkspaceForcedMoveStoresHeadFilerTime` (`core/authority/workspace_lost_range_readout_test.go`); `TestWorkspaceForcedMoveLostRangeOverRPC` (`core/host/master/workspace_lost_range_readout_test.go`); `TestReadoutWording` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-LOST-RANGE-QUERY-001` | `QueryWorkspaceLostRange` returns the stored ranges unchanged: every issued forced move's range in issue order, or the single range of a given request id. | M2 lease: Moved → epoch issued (readout) | `core/authority/workspace_lost_range.go` `WorkspaceLostRangeReadouts`; `core/host/master/workspace_service.go` `QueryWorkspaceLostRange`; `core/rpc/wsclient/wsclient.go` `LostRanges`; `cmd/sw-block/workspace.go` `runWorkspaceLostRange` | `TestWorkspaceLostRangeAccumulatesInIssueOrder` (`core/authority/workspace_lost_range_readout_test.go`); `TestLostRangesBindsTheAnswer` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceLostRangeListsAllInOrder` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE |
|
||||
@@ -923,11 +925,11 @@ Notes:
|
||||
| `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE |
|
||||
| `INV-ATTACH-ASSIGNMENT-BOUND-001` | Without a master wait, the assignment allowance is checked between attach attempts; it never cancels a granted attempt's manifest read. Per-fetch bounds, recovery progress and provider Close still apply. | M1 Recovering to Serving (wait scheduling only) | `DurableProvider.chunkAuthorityWait` | `TestDefaultAttachAt262144EntriesOutlivesAssignmentWait`, `TestDefaultGrantedAttachFailureEndsAtAssignmentAllowance` (`core/frontend/durable/default_attach_attempt_test.go`); `TestRestoreDeferredAssignmentWaitEndsOnDeadlineAndClose` (`core/frontend/durable/provider_assignment_test.go`) | none (scheduling; authority guards unchanged) | ACTIVE |
|
||||
| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/frontend/durable/provider_startup.go` `ChunkStartupIdentityRefused`, `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE |
|
||||
| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. Newer HEAD/store format: 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/frontend/durable/provider_startup.go` `ChunkStartupIdentityRefused`, `ChunkStartupNewerVersion`, `endChunkStartup`; `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`, `durableOpenFatalExit` | `TestANewerHeadVersionExits78NotRestartable`, `TestAStoreOfANewerFormatExits78` (`cmd/blockvolume/newer_version_exit_test.go`); `TestChunkStartupNewerVersionIsGenerationBound` (`core/frontend/durable/provider_startup_internal_test.go`); `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE |
|
||||
| `INV-WS-MASTER-WAIT-001` | Startup waits without a bound while the master gives no reply or refuses credentials or identity; after contact it ends 30 s beyond the later of recovery's first reply or the master barrier. Typed MOVED or DELETED ends it with 78, including a confirmed moved source without an own assignment. | M2 Awaiting assignment → Process exited | `core/host/volume/master_wait.go` `masterWait` (contact from heartbeat, stream and renewal results; the refusal kind from the status detail only); `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` (`ChunkMasterWait`); `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`; `core/host/master/workspace_service.go` `leaseRefusal`, `renewalMoved`; `core/authority/workspace.go` `WorkspaceSourceMoved`; `core/host/master/services.go` `SubscribeAssignments`; `core/authority/workspace_lease_view.go` `LeaseBarrierError`; `core/host/volume/workspace_lease.go` `renewDelay` (sleeps until just past the barrier time, jittered, at most 2 min; then a 200 ms poll for 5 s); `core/rpc/link/link.go` `MasterReconnect` | `TestChunkAuthorityWaitStartsAtFirstContact`, `TestLeaseGuardSleepsUntilTheBarrier`, `TestStatusShowsTheMasterWait`, `TestCredentialsRefusedForAnHourWaitsAndLogs`, `TestHeartbeatLogsTheMasterWait`, `TestFlappingMasterNeverExpiresEarly` (`core/host/volume/master_wait_test.go`); `TestMasterLinkReconnectsWithinTwoSeconds` (`core/host/volume/master_reconnect_test.go`); `TestChunkAuthorityWaitFollowsTheMasterWait`, `TestChunkAuthorityWaitPassesItsOwnStart`, `TestChunkGrantedAttachThatKeepsFailingIsBounded`, `TestChunkAuthorityWaitAttachesAGrantOnTheBoundsTick` (`core/frontend/durable/provider_master_wait_test.go`); `TestIdentityRefusalWaitsVisibly`, `TestChunkAuthorityWaitAfterASlowOpenGetsItsFullLimit`, `TestIdentityRefusalEndsAndDecays` (`core/host/volume/master_wait_test.go`); `TestIdentityRefusalEndsOnADeliveredAssignment` (`cmd/blockvolume/process_exit_authority_test.go`); `TestIdentityRefusalIsTyped` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestLeaseRefusalKinds`, `TestRenewalReplicaMismatchAtOlderLineEpochIsOther` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestChunkStartupExitFinalGives78`, `TestRestartedMovedSourceExits78WithoutAnOwnLine` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceSourceMovedProof`, `TestMovedSourceProofCallers`, `TestMasterWaitFinalSites`, `TestMovedAssignmentStreamIsFinalWithoutAnyOwnAssignment`; also in `core/authority/workspace_source_moved_test.go`, `core/host/master/workspace_moved_source_guard_test.go` | Real systemd moved-source and prestarted-target controls remain qualification gates. | ACTIVE |
|
||||
|
||||
- `INV-WS-DELETE-NO-LIVE-HOLDER-001`: the verdict is the first admission's only. A rerun of a delete whose token already holds the reservation (or a committed one) is admitted without a new verdict and goes on to the catalog step, whose HEAD compare-and-swap is the fence: a HEAD a holder claimed in between is refused there and the reservation given back, so an interrupted delete strands neither the volume nor its id. A reservation may hold several tokens (one per delete request); a new token on an admitted reservation is decided by the verdict; on a committed one it skips the verdict too (committed only once the HEAD is being purged, so no holder can claim it). The HEAD read before the lock still runs for a rerun, and its result is then unused: it is kept outside the workspace lock on purpose. Availability window: a delete admitted for a never-started line that stops before it marks HEAD leaves the volume reserved for deletion; if the holder then claims HEAD, the volume cannot be used until that delete is re-run (the catalog step then refuses the live HEAD and gives the reservation back). Re-run an interrupted delete.
|
||||
- `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75 unless the master proves this server was an issued move's source and returns typed MOVED), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process.
|
||||
- `INV-WS-STARTUP-RETRY-001`: a startup ended on a HEAD written by a newer version exits 78 `head_newer_version`, and a fatal open of a local store written by a newer format exits 78 `store_format_newer`: no restart of this binary can read either, so neither restarts. Exit 78 is also permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75 unless the master proves this server was an issued move's source and returns typed MOVED), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process.
|
||||
- `INV-WS-MASTER-WAIT-001`: every reply produced by blockmaster's handler starts or continues a contact streak; a transport failure (`Unavailable`, `DeadlineExceeded`, `Canceled`) ends it. So a master that answers and drops in turn postpones the 30 s bound for as long as it flaps, also for an obsolete unit; it never ends the wait early (`TestFlappingMasterNeverExpiresEarly`). The barrier time travels as a duration the master computes from the same two predicates as admission, added by the volume to its own monotonic request start; the master re-checks the barrier on every re-grant, so a wrong duration only moves the 75 exit. The status codes alone still mean retry 75 (`INV-WS-STARTUP-RETRY-001`); only the typed `WorkspaceLeaseRefusal` detail (MOVED, DELETED) permits the early 78. Scale: after a master restart every lapsed volume has the same barrier time T and the master grants them one at a time, each grant one store write W under the publisher lock, so the last of N volumes is granted about T + 0.1 s + N x W; a volume whose grant comes 30 s past T exits 75 and is started again, so that starts at N >= 30 s / W. Measured: W p50 1.03 ms, p99 2.33 ms, max 14.5 ms (400 writes of the file authority store on an NVMe ext4 disk, `TestWorkspaceGrantStoreWriteTime`), so 200 volumes about T + 0.6 s and the 30 s point near 12,900 volumes (p99); 20 real volume processes served at most 0.81 s after T (`TestManyVolumesServeTogetherAfterMasterRestart`). The bound holds for that store device: on a device whose flushes stall (an fsync held for seconds), one stalled write puts every waiting volume behind it, so the blockmaster store's device is a deployment premise of serving within 2 s of the barrier. A granted process whose attach keeps failing (the chunk store unreachable) retries inside the same bound and then exits 75: it does not hold the lease while never serving. An identity refusal has no bound until an identity-checked call (a renewal, a delivered assignment) is accepted, or until 30 s of replies pass with no new identity refusal; the window then opens again. A serving holder that starts getting identity refusals is outside this row: its lease expires and it fences and exits 75 (`lease_expired`).
|
||||
- Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal.
|
||||
- Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with a foreign master line newer than nonzero observed-own; absent proof means retry 75.
|
||||
|
||||
Reference in new issue
Block a user